Home Forums ACF PRO Fix: Include ACF fields content in WP Search Reply To: Fix: Include ACF fields content in WP Search

  • @sixtyseven : One big problem with this way is that, if you have numerous fields, the query can becomme reaaaallly complex. So i took it another way :

    • i created one more field (let’s call it searchable)
    • you can also create a blacklist to ignore some fields
    • this field is populated on post_save : you get all the fields you want, clean it, and then use update_field
    • you can then use a single meta field in your search query (which is more or less the same one as you)

    Pros :

    • simple searchable meta, usable whatever the structure of the post type is
    • simple sql query
    • customizable for any post type via a blacklist loated in one place for any post type

    Cons :

    • clearly duplicated databse content, but we’re talking about sanitized text, and i really think that’s worth the price
    function save_searchable_content_meta($post_id, $post, $update) {
        $fields = get_fields($post->ID);
        if (array_key_exists("searchable_content", $fields)) {
    	    array_unshift($fields, $post->post_title, $post->post_content);
    	    $str = sanitize_text_field(array_to_str($fields));
    	    update_field("searchable_content", $str, $post_id);
    add_action('save_post', 'save_searchable_content_meta', 10, 3);