wordpressfunctionparent-childtaxonomyyoast

Get parent of custom taxonomy in Yoast variable snippet


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/


Solution

  • 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 use get_the_terms()

    function get_state() {
        global $post;
        // Get the terms for the current post in your tax
        $myterms = get_the_terms( $post->ID, 'w2dc-location' );
        // Check if parent exists
        if ($myterms[0]->parent !== 0){
            // Get the term object
            $parent = get_term_by('id', $myterms[0]->parent, 'w2dc-location');
            return $parent->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');
    

    Usage in Yoast Title box...

    %%category%% %%state%%