【发布时间】:2018-11-21 18:54:34
【问题描述】:
如何在 Algolia 中排除某些 WordPress 页面类别的索引?
【问题讨论】:
-
您能告诉我们您使用的插件的版本吗?
-
目前 - 0.1 版我也尝试了 0.2.4 版 - 但我无法排除特定类别 - 只有一般类别
如何在 Algolia 中排除某些 WordPress 页面类别的索引?
【问题讨论】:
首先,我建议您坚持使用新版本的插件。在撰写本文时,最新版本是 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
更新:
代码已更新,以确保在产品与多个类别相关联且并非所有类别都被排除时,它不会排除该产品。
【讨论】: