【问题标题】:Algolia - Wordpress - exclude category from indexingAlgolia - Wordpress - 从索引中排除类别
【发布时间】:2018-11-21 18:54:34
【问题描述】:

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

【问题讨论】:

  • 您能告诉我们您使用的插件的版本吗?
  • 目前 - 0.1 版我也尝试了 0.2.4 版 - 但我无法排除特定类别 - 只有一般类别

标签: wordpress algolia


【解决方案1】:

首先,我建议您坚持使用新版本的插件。在撰写本文时,最新版本是 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;
    }

有关扩展 WordPress 的 Algolia Search 插件的更多信息,请访问 documentation: Basics of extending the plugin

更新:

代码已更新,以确保在产品与多个类别相关联且并非所有类别都被排除时,它不会排除该产品。

【讨论】:

  • 谢谢!我下载了 0.2.8 版本,并在主题的 functions.php 中尝试了上面的代码,然后在 wordpress 管理面板中点击了 reindex,没有记录被索引到 Algolia。
  • 对这个问题有帮助吗? - 使用我的 ID 激活上面的代码(在插件文件中)并重新索引时,根本没有记录被索引到 Algolia。
  • Algolia 插件的日志菜单中没有记录错误。这是我使用的代码:codeshare.io/CFu6V
  • 您介意试用最新版本的插件吗? wordpress.org/plugins/…一定要先卸载以前的版本。从现在开始,您可以直接从 WordPress 插件部分安装插件。
  • 代码解决方案缺少实际的过滤器回调。它现在应该可以更好地工作了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
  • 2017-12-27
  • 1970-01-01
  • 2013-10-29
  • 2014-12-27
相关资源
最近更新 更多