I have a directory wordpress website that is using a custom taxonomy. The hierarchy is setup as follows: country > state > city. When I put the custom taxonomy into Yoast for the SEO title and meta description it’s pulling in the city only. I’m looking to pull in the state also by creating a new Yoast variable snippet that will grab the parent(being the state) of current URL the user is on.
This is what I have so far in my functions.php file, but it’s bringing in the country. So it’s currently bringing in the top level parent. How can I get immediate parent, which would be the state?
function get_state() {
$myterms = get_terms( array( 'taxonomy' => 'w2dc-location', 'parent' => 0 ) );
foreach($myterms as $term) {
return $term->name;
}
}
function register_custom_yoast_variables() {
wpseo_register_var_replacement( '%%state%%', 'get_state', 'advanced', 'some help text' );
}
add_action('wpseo_register_extra_replacements', 'register_custom_yoast_variables');
website link: https://www.helpingmehear.com/find-an-expert/hearing-aids/united-states/colorado/castle-rock/accent-on-hearing/
2
Answers
This is a solution that will return City and State, given that you’ve only chosen one taxonomy (city) and that state is the direct parent of city. I think that instead of
get_terms()
you want to useget_the_terms()
Usage in Yoast Title box…
%%category%% %%state%%
If you use
custom post taxonomy
you can use this code to get theparent category
very easily forwpseo_register_var_replacement
custom function:Usage in Yoast SEO boxes as
custom_variable
: