Wordpress show next 3 x number adjacent custom posts from existing

本秂侑毒 提交于 2019-12-24 08:22:31

问题


On a single/detail Custom Post Page I would like to display a custom nav of li's or divs in a sidebar that displays both title, excerpt and permalink for the next 3 posts within the custom post series. So if we are on custom post 3 then it would show 4, 5, 6 in the sidebar.

The closest I've found to this is :-=

global $post;
$current_post = $post; // remember the current post

for($i = 1; $i <= 3; $i++){
 $post = get_previous_post(); // this uses $post->ID
setup_postdata($post);

// do your stuff here       
the_title();

}

$post = $current_post; // restore

Problem is this only shows the first next post and I need to show 3.

Thanks Glennyboy


回答1:


Your code from above is very close. It looks like you're just missing an endfor; and maybe a bit of html. Try the blow code:

<ul>
    <?php
        global $post;
        $current_post = $post;

        for($i = 1; $i <= 3; $i++):
        $post = get_previous_post();
        setup_postdata($post);

        echo '<li>';
        echo '<h3>' . get_the_title() . '</h3>';
        the_excerpt();
        echo get_post_meta($post->ID, 'your_metafield_name', true);
        echo '</li>';

        endfor;
        $post = $current_post; 

    ?>
</ul>

When using the_excerpt() it should include a "read more" link already to the post, so you won't need to use the_permalink() function. If you don't have 3 or more previous posts, it will only show how many previous posts there are. I tested this in the single.php template file, but it should work in a custom post type single template file if you are using a custom one. Let me know if you have any questions.




回答2:


The problem with your code is that get_previous_post() gets the post previous to the current post, so your for loop just gets the same post 3 times.

What you need to use is wp_get_recent_posts. You would use it inside the WordPress loop, using a secondary loop to make that query.

Depending on where you're adding the code, you might just be able to use wp_get_recent_posts():

$args = array(
    'numberposts' => 3,
    'orderby' => 'post_date',
    'order' => 'DESC',
    'post_type' => 'post');

$recent_posts = wp_get_recent_posts( $args, ARRAY_A );


来源:https://stackoverflow.com/questions/25361996/wordpress-show-next-3-x-number-adjacent-custom-posts-from-existing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!