0

I have three custom fields (not using ACF). I want the search form to search for a match in:

  • _cth_featured_zip_code_1

  • _cth_featured_zip_code_2

  • _cth_featured_zip_code_3

This is the query I've written:

$wpdb->prepare(
                " LEFT JOIN $wpdb->postmeta AS laddress_meta ON laddress_meta.post_id = {$wpdb->posts}.ID AND laddress_meta.meta_key = %s",
                '_cth_featured_zip_code_1','_cth_featured_zip_code_2','_cth_featured_zip_code_3'                
            );

Am I thinking about this correctly? i.e. does this statement accomplish joining the post meta table and asking it to search just those fields from within that table?

When I go to test, it looks like all I get are results that match the first custom field listed. When I try adding in another 'AND' or 'OR' condition while trying to include the other two fields, this causes a critical error on the site.

What's the proper way to query the other 2 custom fields in addition to the first? Is there another operator I should be using? I've spend most the morning getting the join piece figured out - I'm getting hung up here.

Any even slight confirmation in the right direction would be greatly appreciated.

1 Answer 1

0

Are you using Advanced Custom Fields?(ACF?).

Relevanssi is a really good plugin which increases the scope of the core WordPress search.

Here's the link: https://wordpress.org/plugins/relevanssi/

It allows users to search for posts via ACF fields attached to them.

Once you install the plugin, you can use the following code in your functions.php file to instruct your search to show posts which match meta values.

function rlv_relationship_content( $content, $post ) {
    // Fetching the post data by the relationship field.
    $relationships = get_post_meta( $post->ID, '_cth_featured_zip_code_1', true );

    if ( ! is_array( $relationships ) ) {
        $relationships = array( $relationships );
    }

    foreach ( $relationships as $related_post ) {
        $content .= ' ' . get_the_title( $related_post );
    }

    return $content;
}
add_filter( 'relevanssi_content_to_index', 'rlv_relationship_content', 10, 2 );
1
  • Good to know! For this install, I'm not using ACF. There is a custom post type specific to the theme and the theme author included the ability to add custom field to this custom post type from within a builder in the theme. I do have several installs where ACF is used, so this bit of knowledge will come in handy. I appreciate your making the time to review and answer! Feb 24, 2020 at 20:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.