When a post, page, Content Template or Layout contains a View, you don’t have the ability to grab information from the results of that View to use in Yoast SEO’s configurations for the post where the View is displayed. For example, let’s say you want to use the excerpt of the first result of the View as the Facebook description field. It’s not possible because there isn’t a snippet variable that allows you to access that View’s content.
This is where Yoast SEO’s custom snippet variables can be used effectively. This feature gives you the ability to create your own custom snippets for use in the Yoast SEO panel. In the PHP callback for each custom variable, you have the ability to use the Views API to fetch query results and return information from those results.
// define the custom snippet replacement callback // use the Views API to get the first result of the View // return the excerpt of that post function get_first_result_excerpt() { global $post, $current_user; $args = array( 'limit' => 1 ); $articles = get_view_query_results( 12345, $post->ID, $current_user->ID, $args); $excerpt = isset($articles[0]) ? get_the_excerpt($articles[0]) : ''; return $excerpt; } // define the action for registering yoast_variable replacments // add multiple lines here to create multiple snippet variables function register_custom_yoast_variables() { wpseo_register_var_replacement( '%%firstarticleexcerpt%%', 'get_first_result_excerpt', 'basic', 'First Article Excerpt' ); } // Add the hook to register the variables add_action('wpseo_register_extra_replacements', 'register_custom_yoast_variables');
Replace 12345 with the numeric ID of the View. Now you can place the custom snippet variable %%firstarticleexcerpt%%
in the Facebook description field. Custom snippet variables will not be decoded in the wp-admin Yoast interface, but will be parsed as expected on the front-end of the site. You can inspect the og:description
meta tag in the page source to confirm this is working as expected.