1
votes

I'm doing a headless wordpress, so using wordpress API.

Using Yoast for SEO, I've added yoast SEO data to my post types API endpoints like this:

function wp_api_encode_yoast($data, $post, $context) {
    $yoastMeta = array(
        'yoast_wpseo_focuskw' => get_post_meta($post->ID, '_yoast_wpseo_focuskw', true),
        'yoast_wpseo_title' => wpseo_replace_vars(get_post_meta($post->ID, '_yoast_wpseo_title', true), $post),
        'yoast_wpseo_metadesc' => wpseo_replace_vars(get_post_meta($post->ID, '_yoast_wpseo_metadesc', true), $post),
        'yoast_wpseo_linkdex' => get_post_meta($post->ID, '_yoast_wpseo_linkdex', true),
        'yoast_wpseo_metakeywords' => get_post_meta($post->ID, '_yoast_wpseo_metakeywords', true),
        'yoast_wpseo_meta_robots_noindex' => get_post_meta($post->ID, '_yoast_wpseo_meta-robots-noindex', true),
        'yoast_wpseo_meta_robots_nofollow' => get_post_meta($post->ID, '_yoast_wpseo_meta-robots-nofollow', true),
        'yoast_wpseo_meta_robots_adv' => get_post_meta($post->ID, '_yoast_wpseo_meta-robots-adv', true),
        'yoast_wpseo_canonical' => get_post_meta($post->ID, '_yoast_wpseo_canonical', true),
        'yoast_wpseo_redirect' => get_post_meta($post->ID, '_yoast_wpseo_redirect', true),
        'yoast_wpseo_opengraph_title' => get_post_meta($post->ID, '_yoast_wpseo_opengraph-title', true),
        'yoast_wpseo_opengraph_description' => get_post_meta($post->ID, '_yoast_wpseo_opengraph-description', true),
        'yoast_wpseo_opengraph_image' => get_post_meta($post->ID, '_yoast_wpseo_opengraph-image', true),
        'yoast_wpseo_twitter_title' => get_post_meta($post->ID, '_yoast_wpseo_twitter-title', true),
        'yoast_wpseo_twitter_description' => get_post_meta($post->ID, '_yoast_wpseo_twitter-description', true),
        'yoast_wpseo_twitter_image' => get_post_meta($post->ID, '_yoast_wpseo_twitter-image', true)
    );

    $data->data['yoast_meta'] = (array) $yoastMeta;
    return $data;
}
add_filter('rest_prepare_post', 'wp_api_encode_yoast', 10, 3);
add_filter('rest_prepare_category', 'wp_api_encode_yoast', 10, 3);
add_filter('rest_prepare_page', 'wp_api_encode_yoast', 10, 3);

This works for posts, categories, pages and any other post types. But I don't see how I can add this to tags, and documentation seems to be lacking. I don't believe register_rest_field is an option since it registers a field for a particular post type... and I don't think a tag is treated as a post type. At least, rest_prepare_tag filter does not work.

Need some pointers on how to add a rest field to tags.

1

1 Answers

2
votes

OK finally found the solution.

After looking in wp_term_taxonomy table, I noticed that taxonomy column describes the taxonomy term for tags - which is actually post_tag, not just 'tag'.

So, this works:

add_filter('rest_prepare_post_tag', 'wp_api_encode_yoast', 10, 3);

Hopefully someone will be helped by this.