后预处理功能搜索索引


Post pre-processing function for search indexing

您是否可以在保存之前通过过滤器运行帖子,以便确定应该与之关联的搜索词。

例如,您是否可以定义要将搜索条件中的连字符替换为空格?

你可以把它包含在你的主题中(在functions.php中):

<?php
/**
 * Creates a list of keywords associated with the post
 * and stores the value in a custom field called "search keywords"
 */
add_filter('save_post', function () {
    global $post;
    // Get post content
    $words = strtolower($post->post_title . ' ' . $post->post_content);
    /* Do any extra processing here */    
    // Save
    if (!add_post_meta($post->ID, 'search keywords', $words, true)) { 
        update_post_meta($post->ID, 'search keywords', $words);
    }
});
/**
 * This is needed to search against a custom field
 */
add_filter('posts_join', function ($join) {
    global $wpdb;
    if (!is_search()) {
        return $join;
    }
    $join .= " LEFT JOIN $wpdb->postmeta ON (
        $wpdb->postmeta.post_id = $wpdb->posts.ID
        AND $wpdb->postmeta.meta_key = 'search keywords'
    ) ";
    return $join;
});
/**
 * This filters the actual search result
 */
add_filter('posts_where', function ($where) {
    global $wpdb;
    // Only change the search function
    if (!is_search()) {
        return $where;
    }
    // Get the search terms
    $search_query = strtolower(get_search_query());
    $search_terms = explode(' ', $search_query);
    // Only show published posts
    $where = " AND $wpdb->posts.post_status = 'publish' ";
    // Only show posts, not any other post types
    $where .= " AND $wpdb->posts.post_type IN ('post') ";
    // Search
    $where .= " AND ( 0 ";
    foreach ($search_terms as $search_term) {
        $where .= $wpdb->prepare(
            " OR (0
                OR ($wpdb->posts.post_title LIKE '%%%s%%')
                OR ($wpdb->posts.post_content LIKE '%%%s%%')
                OR (1
                    AND $wpdb->postmeta.meta_key = 'search keywords'
                    AND $wpdb->postmeta.meta_value LIKE '%%%s%%'
                )
            ) ",
            $search_term,
            $search_term,
            $search_term
        );
    }
    $where .= " ) ";
    return $where;
});