You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress中显示标签‘video’的4篇最新文章?

Fixing Your WordPress Video Tag Post Loop

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:11:05