Algolia - Wordpress - 从索引中排除类别

Fil*_*mit 5 wordpress algolia

如何排除某些WordPress页面类别在Algolia中被编入索引?

ray*_*jes 7

首先,我建议你坚持使用新版本的插件.在撰写本文时,最新版本为0.2.5.实际上旧版本(0.0.1)将不再受支持.

关于你的问题,确实可以过滤你想推送到Algolia的帖子并进行搜索.

我从您的问题中了解到,您已将页面分配到类别,并且您希望避免在搜索结果中显示某些类别的页面.如果这些初始陈述有误,请对此答案发表评论,我很乐意推动更新!

您可以使用WordPress过滤器来决定索引帖子.在您的情况下,如果您愿意从searchable_posts索引中排除页面,则可以使用algolia_should_index_searchable_post过滤器.如果您愿意从posts_page索引中排除页面,则可以使用algolia_should_index_post过滤器.

以下是如何排除其ID标识的类别列表的所有页面的示例.

<?php
    // functions.php of your theme
    // or in a custom plugin file.

    // We alter the indexing decision making for both the posts index and the searchable_posts index. 
    add_filter('algolia_should_index_post', 'custom_should_index_post', 10, 2);
    add_filter('algolia_should_index_searchable_post', 'custom_should_index_post', 10, 2);


    /**
     * @param bool    $should_index
     * @param WP_Post $post
     *
     * @return bool
     */
    function custom_should_index_post( $should_index, WP_Post $post ) {
        // Replace these IDs with yours ;)
        $categories_to_exclude = array( 7, 22 );

        if ( false === $should_index ) {
            // If the decision has already been taken to not index the post
            // stick to that decision.
            return $should_index;
        }

        if ( $post->post_type !== 'page' ) {
            // We only want to alter the decision making for pages.
            // We we are dealing with another post_type, return the $should_index as is.
            return  $should_index;
        }


        $post_category_ids = wp_get_post_categories( $post->ID );
        $remaining_category_ids = array_diff( $post_category_ids, $categories_to_exclude );
        if ( count( $remaining_category_ids ) === 0 ) {
            // If the post is a page and belongs to an excluded category,
            // we return false to inform that we do not want to index the post.
            return false;
        }

        return $should_index;
    }
Run Code Online (Sandbox Code Playgroud)

有关为WordPress扩展Algolia Search插件的更多信息,请参阅文档:扩展插件的基础知识

更新:

代码已更新,以确保它不会排除产品,如果它与多个类别相关联,并且不排除所有类别.