2
votes

I have a custom endpoint created following the official guide and in it, I'm simply fetching the post by slug (name) as follows:

if ( $posts = get_posts( array(
    'name' => $slug,
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => 1
) ) ) $post = $posts[0];

if ( empty( $post ) ) {
    return null;
}

Preparing the response as adding more data about the author, preparing some custom fields etc.

The problem I'm facing is we have Yoast SEO plugin added and in the standard WP REST API yoast_head is included but in the custom endpoint, it's not.

I found this article where it lists that the SEO data is included in the standard REST API and that there is a custom endpoint for fetching the SEO data

Example: https://example/wp-json/yoast/v1/get_head?url=https://example.com/hello-world/

That would mean I would be required to make an additional request just to fetch the SEO data.

I also tried activating WP REST Yoast Meta plugin without success as it throws an error while fetching the regular WP REST and it had no effect on the custom one

Is there a way to get yoast_head in the custom endpoint?

2
The source code for generating this is very complex and nested, your best bet would be to just use the get_head endpoint within your function and use a php get request to append the data - shazyriver
I don't have time to write up a full testable answer, but you can just use Yoast's API's natively in your own code. Unfortunately Yoast is going/went through a rewrite so their code might not be obvious if you don't know how they did DI, however they still have a legacy version in their deprecated section that should get you the code that you need to use. Obviously, all warnings about using code explicitly marked as deprecated apply. - Chris Haas

2 Answers

0
votes

Here is what you need, I faced the same issue and someone coded this for this exact purpose:

https://wordpress.org/plugins/wp-rest-yoast-meta/

Keep me posted!

0
votes

i had the same problem and this worked for me, i hope it helps you. The Meta_Surface class provides a helper for access the head of any post or page.

  if (function_exists('YoastSEO')) {
        $meta_helper = YoastSEO()->classes->get(Yoast\WP\SEO\Surfaces\Meta_Surface::class);
        $meta = $meta_helper->for_post($pid);
        $query->post->yoast_head = $meta->get_head();
    }