我如何使用类别ID获取wordpress帖子?

时间:2014-09-04 14:11:12

标签: php wordpress plugins

我使用query_posts在wordpress中遇到问题。

这是我的代码:

$args = array('category__in' => array(9),'post_type'=>'banner-slider','post_status'=>'publish');
query_posts( $args );
while ( have_posts() ) : the_post();
the_title();
endwhile;

query_post返回以下查询:

SELECT SQL_CALC_FOUND_ROWS  bib_posts.* FROM bib_posts  WHERE 1=1  AND 0 = 1 AND bib_posts.post_type = 'banner-slider' AND ((bib_posts.post_status = 'publish')) GROUP BY bib_posts.ID ORDER BY bib_posts.post_date DESC LIMIT 0, 10

在上面的查询中,我得到0 = 1这是错误的。但是当我从查询帖子中删除category__in时,我的查询工作正常。

请建议我在哪里错。

1 个答案:

答案 0 :(得分:1)

query_posts并不意味着插件或主题使用,更具体地说,codex说:

  

此功能不适用于插件或主题。如   稍后解释,有更好的,更高性能的选项可以改变   主要查询。 query_posts()过于简单和有问题的方式   通过将其替换为新的实例来修改页面的主要查询   查询。它是低效的(重新运行SQL查询)并且将彻底   在某些情况下失败(特别是在处理职位时经常失败)   分页)。任何现代WP代码都应该使用更可靠的方法,比如   为此目的,使用pre_get_posts钩子。

引自: http://codex.wordpress.org/Function_Reference/query_posts

query_posts

WordPress codex建议使用WP_Queryget_posts()。在你的情况下,我认为get_posts()应该足够了,所以这个例子将使用它。以下示例实际上来自WordPress codex,对您的categorypost_typepost_status进行了一些修改:

<?php
$args = array( 'category' => 9, 'post_type' => 'banner-slider', 'post_status' => 'publish' );

$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
    <li>
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    </li>
<?php
endforeach; 
wp_reset_postdata();
?>

Codex: http://codex.wordpress.org/Template_Tags/get_posts

相关问题