Knowledge Base

Index Table – Indexing ACF repeater field titles and contents

in Ajax Search Pro Tutorials Tags: acfindexrepeaterrepeater field

Using this custom code, you can enable indexing of Advanced Custom Fields repeater field post titles and/or contents for the current post. Change the following variables in the code as you need them

  • $field_names -> one or more repeater field names, separated by comma
  • $index_title -> true or false, to index the post titles found in the repeater field
  • $index_content -> true or false, to index the post contents found in the repeater field

Add this custom code to the functions.php in your theme/child theme directory. Before editing, please make sure to have a full site back-up just in case!

add_filter('asp_index_cf_contents_before_tokenize', 'asp_post_content_before_add_acf_relationship', 10, 2);
function asp_post_content_before_add_acf_relationship($content, $post) {
    $field_names = 'field1, field2'; // Comma separated list of field names
    $index_title = true;      // To index the related post title
    $index_content = true;    // To index the related post content
    $run_shortcodes = true;   // To run shortcodes within Flex element contents
    // ----------------------------------------------------------------
    if ( function_exists('get_field') ) {
       $fn_arr = explode(',', $field_names);
       foreach ($fn_arr as $field_name) {
           $field_name = trim($field_name);
           if ( empty($field_name) )
               continue;
          
            $args = array(
              'p'         => $post->ID, // ID of a page, post, or custom type
              'post_type' => 'any'
            );
            $my_query = new WP_Query( $args );
            while ( $my_query->have_posts() ) : $my_query->the_post();
                $items = get_field($field_name);
                if ( empty($items) )
                  continue;
                if ( is_array($items) ) {
                   foreach ($items as $item) {
                      if ( isset($item->ID) ) {
                          if ( $index_title ) {
                              $content .= ' ' . get_the_title($item->ID);
                          }
                          if ( $index_content ) {
                              $content .= ' ' . apply_filters('the_content', get_post_field('post_content', $item->ID));
                          }
                      } else if ( is_array($item) || is_string($item) ) {
                        if ( $run_shortcodes )  
                            $content .= ' ' . do_shortcode( wd_array_to_string($item));
                        else
                            $content .= ' ' . wd_array_to_string($item);
                      }
                   }
                } else if ( is_string($items) ) {
                   $content .= ' ' . $items;
                }
            
            endwhile;
       }
    }
    return $content;
}