发布用于搜索索引的预处理功能

时间:2015-06-08 13:49:05

标签: php post wordpress-theming wordpress

有没有办法可以在保存之前通过过滤器运行帖子,以便确定哪些搜索字词应与之关联。

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

1 个答案:

答案 0 :(得分:0)

您可以在主题中包含此内容(在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;
});