简体   繁体   English

WordPress简码功能

[英]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. 我想返回所有具有与当前url相同的自定义字段值的结果。 It will ony return 1. Does it need a for each or something? 它只会返回1。 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;

};?>

You "return" from the function after the first element inside the while loop. 您可以在while循环中第一个元素之后从函数“返回”。

example returning all the posts: 返回所有帖子的示例:

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

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

Because you have added the return inside the loop it will only display the last one. 因为您已在循环内添加了return,所以它将仅显示最后一个。 You have to place the return outside the loop for it to display all. 您必须将return放置在循环之外才能显示所有内容。

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! 它很可能会在一行中显示所有标题,因此只需设置所需格式即可!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM