dmt
dmt

Reputation: 201

Wordpress shortcode function

Can anyone explain why this only returns the 1st result only. I want to return all results that have the same custom field value as the current url. It will ony return 1. Does it need a for each or something? Thank you!!

<?php add_shortcode( 'feed', 'display_custom_post_type' );

    function display_custom_post_type(){

    $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];

    $args = array( 
       'post_type'       => 'custom_post_type',
       'posts_per_page'  => -1  
    );

    $new_query = new WP_Query($args);

    while($new_query->have_posts()) : $new_query->the_post();

    return get_title();

    endwhile;

};?>

Upvotes: 0

Views: 49

Answers (2)

fabio
fabio

Reputation: 624

You "return" from the function after the first element inside the while loop.

example returning all the posts:

$args = array(
    'post_type' => 'custom_post_type',
    'posts_per_page'  => -1  

);
$results = get_posts($args);
return $results;

Upvotes: 1

Pascal
Pascal

Reputation: 133

Because you have added the return inside the loop it will only display the last one. You have to place the return outside the loop for it to display all.

Just a small example to see it work, change this bit:

while($new_query->have_posts()) : $new_query->the_post();

return get_title();

endwhile;

to this:

while($new_query->have_posts()) : $new_query->the_post();

$all_titles .= get_title();

endwhile;

return $all_titles;

It will most probably show all the titles in a single row, so just format as you wish!

Upvotes: 1

Related Questions