Integrations / Platforms / WordPress / Serializing Content
Jun. 27, 2019

Serializing Content

In the previous section, we defined a new filter called post_to_record. We’ll use this filter to define how a post is converted to an array before being sent to Algolia.

You want to send to Algolia two types of information:

  • Searchable content (title, post content, category name)
  • Content to display in your result page (thumbnail, permalinks)

There is an easy way to make the second type non-searchable to keep the best relevance.

To define how we want to serialize our post, we could do it in the plugin, but because there are some content depending on your theme (thumbnail size for instance), we believe it’s best to add this feature to your theme.

This is also best because most themes with custom post types, embed the feature in the theme, not in a separate plugin.

It’s highly recommended to create a child theme instead of modifying the main theme directly. It will allow you to keep updating the theme you installed.

Converting WP_Post to an Algolia record

In your theme functions.php file, define a new function and add it to our new WordPress filter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function algolia_post_to_record(WP_Post $post) {
    $tags = array_map(function (WP_Term $term) {
        return $term->name;
    }, wp_get_post_terms( $post->ID, 'post_tag' ));

    return [
        'objectID' => implode('#', [$post->post_type, $post->ID]),
        'title' => $post->post_title,
        'author' => [
            'id' => $post->post_author,
            'name' => get_user_by( 'ID', $post->post_author )->display_name,
        ],
        'excerpt' => $post->post_excerpt,
        'content' => strip_tags($post->post_content),
        'tags' => $tags,
        'url' => get_post_permalink($post->ID),
        'custom_field' => get_post_meta($post->id, 'custom_field_name'),
    ];
}
add_filter('post_to_record', 'algolia_post_to_record');

In this example, I want to highlight how to get the author’s name, the permalink, or the list of tags. We can reuse this list of tags to create a facet, for instance.

Bear in mind this code is working and is easy to understand but will make a lot of SQL queries. This won’t be an issue in most cases but could be if you have thousands of posts.

Handling long articles

In case your articles are really long, you might hit the limit allowed per record in Algolia. This limit exists to keep the results very relevant and fast.

If you get an error about your record being to big, please refer to the advanced sections to understand how to split your records.

Did you find this page helpful?