• Resolved nivi_ms

    (@nivi_ms)


    Hello,
    I wonder if you could possibly help me. I have created a shortcode to display a custom post type on a yellow box within the pages of the site I am working on. I must warn you this is the fist time I write a shortcode so it’s not perfect.
    What I would like to do is set up and attribute so that only posts published in the last 24 hours are displayed by this shortcode. Any posts older thatn 24 hours will just not come up. This is the code I have so far.

    //[servicealert] - outputs a link
    function service_alert($atts){
       extract(shortcode_atts(array(
          'posts' => 1,
       ), $atts));
    };
    function alertwd_shortcode() {
       query_posts(array('post_type' => 'alert', 'post_per_page' => '1' , 'showposts' => 1));
       if (have_posts()) :
          while (have_posts()) : the_post();
             $return_string = '<div class="alert">'.'<h3>'.get_the_title().'</h3>'.'<p>'.get_the_content().'</p>'.'</div>';
          endwhile;
       endif;
       wp_reset_query();
       return $return_string;
    }
    add_shortcode( 'servicealert', 'alertwd_shortcode' );
    ?>

    Could you help?
    Thank you!

Viewing 2 replies - 1 through 2 (of 2 total)
  • You can do it with a “posts_where” filter. Add a filter just before your query and remove it just after. Inside your filter, alter the condition using post_date and current date to take just posts published in the last 24 hours.

    It’s not a good idea to use query_posts if you don’t want to alter main query. You could use get_posts or directly WP_Query 😉

    Thread Starter nivi_ms

    (@nivi_ms)

    Thank you! Yes I ended up going for the filter option but will look into doing it via get_posts. Just need to get this out and ready at the moment 🙂

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Shortcode attribute to display post from the last 24 hours’ is closed to new replies.