How to exclude one category

时间:2016-10-09 作者:RodneyHawk

这个脚本我用来在我的单个帖子中显示来自同一类别的文章,排除了实际显示的帖子。。。我怎样才能排除这个脚本的类别1,这样他就可以进一步显示同一类别中的artikels,而不是类别1中的artikels?

<?php
// Default arguments
$args = array(
    \'posts_per_page\' => 6, // How many items to display
    \'post__not_in\'   => array( get_the_ID() ), // Exclude current post
    \'no_found_rows\'  => true, // We don\'t ned pagination so this speeds up the query
         \'orderby\'       => \'rand\',

);

// Check for current post category and add tax_query to the query arguments
$cats = wp_get_post_terms( get_the_ID(), \'category\' ); 
$cats_ids = array();  
foreach( $cats as $wpex_related_cat ) {
    $cats_ids[] = $wpex_related_cat->term_id; 
}
if ( ! empty( $cats_ids ) ) {
    $args[\'category__in\'] = $cats_ids;
}

// Query posts
$wpex_query = new wp_query( $args );

// Loop through posts
foreach( $wpex_query->posts as $post ) : setup_postdata( $post ); ?>

<div class="weitere_interessante_artikel_container">
<div class="weitere-artikel-pic-wrapper">
<a href="<?php the_permalink() ?>"><?php the_post_thumbnail(\'middle\');?></a>
</div>
<div class="text_container">
<a href="<?php the_permalink() ?>"><span><?php echo str_replace(\':\', \':</span>\', get_the_title()); ?></a>
</div>
</div>


<?php
// End loop
endforeach;

// Reset post data
wp_reset_postdata(); ?>

1 个回复
SO网友:Natan Zasepa

您可以使用“category\\uu not\\u in”数组参数。另外,我对您的代码做了一些修改,您应该使用wordpress最佳实践,即“if->while”来显示帖子。请尝试下面的代码,因为我还没有测试它。

<?php
// Default arguments
$args = array(
    \'posts_per_page\'    => 6, // How many items to display
    \'post__not_in\'      => array( get_the_ID() ), // Exclude current post
    \'no_found_rows\'     => true, // We don\'t ned pagination so this speeds up the query
    \'orderby\'           => \'rand\',
    \'category__not_in\'  => array( 1 )

);

// Check for current post category and add tax_query to the query arguments
$cats = wp_get_post_terms( get_the_ID(), \'category\' ); 
$cats_ids = array();  
foreach( $cats as $wpex_related_cat ) {
    $cats_ids[] = $wpex_related_cat->term_id; 
}
if ( ! empty( $cats_ids ) ) {
    $args[\'category__in\'] = $cats_ids;
}

// Query posts
$wpex_query = new WP_Query( $args );

// Loop through posts
if( $wpex_query->have_posts() ) :
while( $wpex_query->have_posts() ) : $wpex_query->the_post(); ?>

<div class="weitere_interessante_artikel_container">
<div class="weitere-artikel-pic-wrapper">
<a href="<?php the_permalink() ?>"><?php the_post_thumbnail(\'middle\');?></a>
</div>
<div class="text_container">
<a href="<?php the_permalink() ?>"><span><?php echo str_replace(\':\', \':</span>\', get_the_title()); ?></a>
</div>
</div>


<?php
// End loop
endwhile;

// Reset post data
wp_reset_postdata(); 

endif; ?>

相关推荐

如何在EXCLUDE命令中包含多个ID?

$product_cats = get_terms(\'product_cat\',array(\'hide_empty\'=>1,\'exclude\'=>8,\'parent\'=>0)); 在上文中,我如何在排除字段中添加多个id(当前是8,我想添加9、10和11)?