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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
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