How can I create a shortcode to show the number of posts of actual day?

The question:

I want to create a shortcode to display the posts posted on actual day.

I found this code:
show number of posts posted today
And I’m trying with it, but return 0

function ts_day_f() {
// we get the date for today
$today = getdate();
//we set the variables, i am ignoring sticky posts so they dont get counted
$args = array(
    'ignore_sticky_posts' => 1,
    'posts_per_page' => -1, //all posts 
    'date_query' => array(
        array(
            'year'  => $today["year"],
            'month' => $today["mon"],
            'day'   => $today["mday"],
        ),
    ),
);
//we create the query
$today_posts = new WP_Query( $args );
//the result already has a property with the number of posts returned
$count = $today_posts->post_count;
//show it
return $count;
}

add_shortcode('ts_day','ts_day_f');

Any idea?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

I tried some codes, and I think finally works after several tries:

function ts_day_f() {
    $posts= get_posts(array(
            'numberposts' => -1,
            'post_status' => 'publish',
            'orderby' => 'date',
            'order'   => 'DESC',
            'date_query'    => array(
                'column'  => 'post_date',
                'after'     => 'today',
                'before'    => 'tomorrow - 1 second',
            )
        ));

    if ( is_user_logged_in()) {
        //return count($posts);
        $c = count($posts);

        return "Today: <span style="font-size: 1.5em;">" .$c. "</span> posts.";
    }
    else  {
        return $null;
    }
}

add_shortcode('ts_day','ts_day_f');

Additionally with the function to show only to users log in.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment