dr5648 2014-09-04 14:11
浏览 32
已采纳

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

I am getting problem in wordpress using query_posts.

Here is my code:

$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 return following query:

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

In the above query, i am getting 0=1 which is wrong. but when i remove category__in from query post then my query working fine.

Please suggest me where I am wrong.

  • 写回答

1条回答 默认 最新

  • dongque1462 2014-09-04 14:20
    关注

    query_posts is not meant to be used by plugins or themes, more specifically the codex says:

    This function isn't meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination). Any modern WP code should use more reliable methods, like making use of pre_get_posts hook, for this purpose.

    Quoted from: http://codex.wordpress.org/Function_Reference/query_posts

    query_posts

    The WordPress codex recommends using WP_Query or get_posts(). In your case, I think get_posts() should be sufficient, so this example is going to use that. The below example is actually from the WordPress codex, with a couple of modifications for your category, post_type, and post_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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding