简体   繁体   English

在WordPress中使用in_category而不是query_posts

[英]using in_category rather than query_posts in wordpress

In wordpress I have a page template called news that I want to display all the posts from one category - 'News'. 在wordpress中,我有一个名为新闻的页面模板,我想显示一个类别的所有帖子-“新闻”。 I don't want to use the category.php because there is a massive blog on the site already. 我不想使用category.php,因为该站点上已经有一个庞大的博客。

 query_posts('cat=145');  
 while ( have_posts() ) : the_post();
 //do something
 endwhile; 

Works fine but I have read that query_posts has drawbacks (like speed) 效果很好,但我已阅读到query_posts有缺点(例如速度)

I tried doing this but it just showed me nothing: 我尝试这样做,但它什么都没显示:

while ( have_posts() ) : the_post();
if ( in_category( '145' ) ) : //also tried 'News'
//do something

Why doesn't' in_category work here? 为什么in_category在这里不起作用?

You could WP Query for achieving your requirement. 您可以通过WP查询来实现您的要求。

Documentation: https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters Example: 文档: https : //codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters示例:

<?php
$args = array(
  'cat' => 145,
);
$the_query = new WP_Query( $args ); ?>

<?php if ( $the_query->have_posts() ) : ?>

  <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    <h2><?php the_title(); ?></h2>
  <?php endwhile; ?>

  <?php wp_reset_postdata(); ?>

<?php endif; ?>

please try this code: 请尝试以下代码:

$args = array('post_type' => 'post',
        'tax_query' => array(
                array(
                        'taxonomy' => 'category',
                        'field'    => 'slug',
                        'terms'    => 'news'  // please pass here you news category slugs 
                    ),
                )
        );

    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
        print_r($post);
    endwhile;

    wp_reset_postdata();

Try to use get_posts() function: 尝试使用get_posts()函数:

$get_p_args = array('category'=> 145,'posts_per_page'=>-1);

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

Try this: 尝试这个:

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
global $wp_query;
$args = array_merge( $wp_query->query_vars, array(
    'post_type' => 'post', // You can add a custom post type if you like
    'paged' => $paged,
    'posts_per_page' => 6, // limit of posts
    'post_status' => 'publish',
    'orderby' => 'publish_date',
    'order' => 'DESC',
    'lang' => 'en', // use language slug in the query
) );
query_posts( $args );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM