簡體   English   中英

排除類別 Wordpress(WP_Query 不起作用)

[英]Exclude category Wordpress (WP_Query not working)

誰能解釋為什么這個查詢不起作用? 我想排除標有主頁的帖子。 它仍然顯示類別名稱為“主頁”的帖子......

<?php
    $query = new WP_Query( 'category_name=-homepage');
?>

<?php if ( $query->have_posts() ) : ?>
    <?php while ( have_posts() ) : the_post(); ?>
        <?php
            get_template_part( 'content', 'news' );
        ?>
    <?php endwhile; ?>
    <?php the_posts_navigation(); ?>
    <?php else : ?>
        <?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>

如文檔中所給出的,如果要排除類別,則必須使用其ID而不是笨拙(請在此處檢查)。

您可以嘗試:

$query = new WP_Query( array( 'category__not_in' => array( 11 ) ) );

您的代碼中有2個問題。

您正在使用子彈而不是ID來排除類別,並且您的自定義查詢沒有正確使用循環。

<?php
$query = new WP_Query( array(
    'cat' => -5, // replace with correct category ID. 
) );

if ( $query->have_posts() ) :

    // make sure we use have_posts and the_post method of our custom query.
    while ( $query->have_posts() ) : $query->the_post();
        get_template_part( 'content', 'news' );
    endwhile;

else:
    get_template_part( 'content', 'none' );
endif;

超出最初問題的范圍,您不能在自定義循環內使用the_posts_navigation() 它作用於全局$wp_query 我懷疑您可能想看一下pre_get_posts過濾器。

進一步閱讀:

http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters

http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts

要在搜索中排除類別,請使用:

<?php
function search_filter($query)
{
    if ( !is_admin() && $query->is_main_query() ) {
        if ($query->is_search)
        {
            $taxquery = array(
                array(
                    'taxonomy'  => 'category',
                    'field'     => 'term_taxonomy_id',
                    'terms'     => 244,
                    'operator'  => 'NOT IN',
                )
            );
            $query->set( 'tax_query', $taxquery );
        }
    }
}

add_action('pre_get_posts','search_filter');

如果您想排除小部件類別中的類別,請復制以下代碼:

<?php
function custom_category_widget($args) {
    $exclude = "244"; // Category IDs to be excluded
    $args["exclude"] = $exclude;
    return $args;
}
add_filter("widget_categories_args","custom_category_widget"); 

上面的代碼在 Wordpress 6.0 和 Avada 7.7.1 主題中對我有用

我希望我能幫上忙,有什么事寫信給我

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM