[resolved] How to query posts or attachments in a shortcode? (3 posts)

  1. Josiah Sprague
    Posted 3 years ago #

    I am trying to write a short code that queries either posts or media attachments (it doesn't matter which) and puts them into some HTML markup for a JS carousel. The WP documentation suggests that I shouldn't use query_posts() inside the main loop, which I would assume means that I can't use it within a shortcode either, since that is called from within a post in the main loop. But the problem I am having, is that when I use get_posts() the output of the query is put at the top of my shortcode loop (and therefore outside of the markup I'm trying to put it in. For example; I have the code;

    $return_string = '<div>Items:';
    $args = array( 'numberposts' => $posts, 'order'=> 'ASC', 'orderby' => 'title' );
    $postslist = get_posts( $args );
    foreach ($postslist as $post) :  setup_postdata($post);
       $return_string .= '<p>'.the_date().'<br />'.the_title().the_excerpt().'</p>';
       $return_string .= '</div>';

    And instead of the paragraphs with the post information being inside of that div, they are outside of the div, (at the top of the main loop of the page, actually) and the div just contains <div>Items:</div>

    What am I doing wrong?

  2. manon1165
    Posted 2 years ago #

    Isn't it supposed to be:

    return $return_string .= '</div>';

  3. Josiah Sprague
    Posted 2 years ago #

    Nope. The problem was that I needed to be using get_the_date(), get_the_title(), etc.

Topic Closed

This topic has been closed to new replies.

About this Topic