How to amend wordpress search so it queries taxonomy terms and category terms?

后端 未结 2 851
北荒
北荒 2021-02-04 22:36

I want to amend the search so if say I have taxonomy called \"author\" and add a term of \"Ian Rankin\" to a post, if I search for \"Ian Rankin\", I want that post to come up.

2条回答
  •  醉梦人生
    2021-02-04 22:46

    It could also be done by using MySQL's EXISTS function with a subquery that joins term_relationships with terms. I have created the following snippet and put it into functions.php:

    // Search titles and tags
    function and_extend_search( $search, &$wp_query ) {
    
        global $wpdb;
    
        if ( empty( $search ))
            return $search;
    
        $terms = $wp_query->query_vars[ 's' ];
        $exploded = explode( ' ', $terms );
        if( $exploded === FALSE || count( $exploded ) == 0 )
            $exploded = array( 0 => $terms );
    
        $search = '';
    
        foreach( $exploded as $tag ) {
            $search .= " AND (
                ($wpdb->posts.post_title LIKE '%$tag%')
    
                OR EXISTS
                (
                    SELECT 
                        *
                    FROM 
                        $wpdb->term_relationships 
                    LEFT JOIN 
                        $wpdb->terms 
                    ON 
                        $wpdb->term_relationships.term_taxonomy_id = $wpdb->terms.term_id
                    WHERE
                            $wpdb->terms.name LIKE '%$tag%'
                        AND
                            $wpdb->term_relationships.object_id = $wpdb->posts.ID
                )
            )";
        }
    
        return $search;
    }
    add_filter('posts_search', 'and_extend_search', 500, 2);
    

提交回复
热议问题