如何在WordPress中显示标签‘video’的4篇最新文章?
Hey there! The problem with your current code is that you haven’t specified a limit on how many posts to display—right now it’s defaulting to showing every post tagged "video". Let’s fix that, plus I’ll share a better practice approach too.
Quick Fix For Your Existing Code
Just add the posts_per_page=4 parameter to your query_posts call. I also included a reset for the main query at the end, which is crucial to avoid messing up other parts of your site:
<?php query_posts('tag=video&posts_per_page=4'); ?> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php the_title(); ?> <?php endwhile; ?> <?php else : ?> no video <?php endif; ?> <?php wp_reset_query(); ?> <!-- Resets the main query to its original state -->
Better Practice: Use WP_Query Instead
While the above fix works, WordPress officially recommends avoiding query_posts because it alters the main page query and can cause unexpected issues. A cleaner, more reliable approach is to use WP_Query, which creates a separate, isolated query:
<?php // Create a custom query for video-tagged posts $video_posts = new WP_Query(array( 'tag' => 'video', 'posts_per_page' => 4, 'orderby' => 'date', // Explicitly set to sort by date (default behavior) 'order' => 'DESC' // Show latest posts first (also default, but clear here) )); // Loop through the custom query results if ($video_posts->have_posts()) : while ($video_posts->have_posts()) : $video_posts->the_post(); ?> <?php the_title(); ?> <?php endwhile; wp_reset_postdata(); // Reset post data back to the main query else : ?> no video <?php endif; ?>
This method keeps your main page query intact and follows WordPress best practices, making your code more maintainable long-term.
内容的提问来源于stack exchange,提问作者x1024

