Shortcode for latest -not expired- posts

I’ve made a short code (part of a plugin) to display the posts which aren’t expired.
For saving the expiration date, i made already a meta key called newsbox-date.

Handy for micro-news, short messages and holliday announcements. My client will not use the posts for blogging but more for short messages a few times a year. With the shortcode we can paste the newsbox on the homepage and contactpage. (as mentioned: handy for holidays)

Read More

So far i have this:

function my_recent_posts_shortcode( $atts ) {
extract( shortcode_atts( array( 'limit' => 5 ), $atts ) );
$q = new WP_Query( 'posts_per_page=' . $limit );
$list = '<div class="newsbox-posts">';
while ( $q->have_posts() ) {
    $q->the_post();
    $expdate = get_post_meta(get_the_ID(), 'newsbox-date', true);
    $nowdatetime = current_time("mysql");
    if ($expdate >= $nowdatetime) {
    $list .= '<h4>' . get_the_title() . '</h4>' . get_the_content() . '';
    }
}
wp_reset_query();
return $list . '</div>';
}
add_shortcode( 'recent-posts', 'my_recent_posts_shortcode' );

There are a few things i need to handle:

  • can i do the filtering of expiration date in the WP_Query already ? Now all posts are first requested, right ?
  • When all posts are expired, the div newsbox-posts must not be showed. So, an if-statement must be handled before the div; but i don’t know yet the best way to get the meta key in this stage.

Thanks for any tips.
If this thing is working, i’ll share the plugin in the rep.

Related posts

1 comment

  1. Thanks, i got it now; indeed with meta_query.

    function my_recent_posts_shortcode( $atts ) {
    global $post;
    $currenttime = current_time("mysql");
    
    $args = array(
    'post_type' => 'post',
    'meta_query' => array(
        array(
            'key' => 'newsbox-date',
            'value' => $currenttime,
            'compare' => '>'
        )
    )
    );
    
    $newsbox = new WP_Query( $args );
    
    if ( $newsbox->have_posts() ) :
    $list = '<div class="newsbox-posts">';
    while ( $newsbox->have_posts() ) : $newsbox->the_post();
    $list .= '<h4>' . get_the_title() . '</h4>' . get_the_content() . '';
    endwhile;
    $list .= '</div>';
    endif;
    
    wp_reset_query();
    return $list;
    
     }
    add_shortcode( 'recent-posts', 'my_recent_posts_shortcode' );
    

Comments are closed.