2

I am trying to push post tags to the search index of the WPFTS plugin in order to search my posts by tag names. To achieve this, I have to generate a string with all tags. Here is what I tried:

add_filter('wpfts_index_post', function($index, $post)
{
    global $wpdb;
    $data = get_the_tags($post->ID);
    $index['post_tag'] = implode(' ', $data);
    return $index;
}, 3, 2);

The problem is I see this new search cluster 'post_tag' in the list, but all data there is empty. What did I do wrong?

  • 1
    Are you sure that get_the_tags returns an array of tag names as string? That's a pretty big assumption – Tom J Nowell Dec 11 '19 at 22:05
1

You're using get_the_tags() incorrectly. It does not return an array of tag names. It returns an array of tag objects. Each tag object does contain the tag's name (along with other data), but you can't use implode() on that result.

I used your original code just adding a step to put the tag object's name into an array. Then your code picks up with the implode from there.

add_filter('wpfts_index_post', function($index, $post)
{
    global $wpdb;
    $data = get_the_tags($post->ID);

    $tag_array = array();
    foreach( $data as $tag_object ) {
        $tag_array[] = $tag_object->name;
    }

    $index['post_tag'] = implode(' ', $tag_array);
    return $index;
}, 3, 2);

Always check the documentation for a function to make sure you are getting the expected result (in this case an object instead of an array). See get_the_tags().

  • Thanks, it looks like works, but outputs a warning "$tag_array is not defined" should I initialize it by empty array? – TCat Dec 11 '19 at 23:03
  • Yes - I should have done that as well. I updated the answer to reflect initializing an array to get it started. – butlerblog Dec 11 '19 at 23:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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