Post 搜索索引的预处理函数

Post pre-processing function for search indexing

有没有一种方法可以在保存之前 运行 通过过滤器 post 以确定应该与之关联的搜索词。

例如,您可以定义要在搜索词中用空格替换连字符吗?

您可以将其包含在您的主题中(在 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;
});