首页 文章

Wordpress WP_Query没有返回post_type

提问于
浏览
0

我正在我的WordPress网站主页上创建一个“精选内容”部分 . 我添加了一个功能,允许将标签添加到页面中 .

然后,在 index.php 我添加了:

<?php $featured_pages = new WP_Query( array(
    'post_type' => 'page',
    'tag' => 'featured', 
    'posts_per_page' => 5
));
if ( $featured_pages-> have_posts() ) : 
    while ( $featured_pages->have_posts() ) : $featured_pages-> the_post();
        get_template_part( 'template-parts/content-featured');
    endwhile; 
endif;
wp_reset_postdata(); ?>

但由于某种原因, WP_Query 数组的 post_type 部分无效 . 它返回所有post_types . 如果我将其更改为 'attachment' ,它仍会返回帖子和页面 .

我是WordPress的新手,我在这里错过了一些东西吗?


经过进一步调查后,似乎'tag'会覆盖'post_type' . 没有它,它只显示页面 . 有了它,帖子也包括在内 .

1 回答

  • 0

    这个问题是无法回答的,因为我没有意识到问题是由我在其他地方添加的功能引起的,我没有在这里添加 .

    但是,其他人可能会发现这很有用,因为我使用的代码主要取自此资源https://www.sitepoint.com/wordpress-pages-use-tags .

    我添加了这个功能(从其他地方复制并粘贴):

    function tags_support_query($wp_query) {
        if ($wp_query->get('tag')) $wp_query->set('post_type', 'any');
    }
    
    add_action('pre_get_posts', 'tags_support_query');
    

    我认为这意味着,如果您使用 WP_Query 来获取'tag',那么'll always set the post type to '任何'. Which I guess isn'好,所以我删除它并且问题中的代码按预期工作 .

相关问题