skip to Main Content

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


  1. 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%%

    Login or Signup to reply.
  2. If you use custom post taxonomy you can use this code to get the parent category very easily for wpseo_register_var_replacement custom function:

    // Return custom post taxonomy name by ID
    function get_game_cat() {
        return get_the_term_list(get_the_ID(), 'game_category');
    }
    function register_custom_yoast_variables() {
     wpseo_register_var_replacement('game_cat', 'get_game_cat', 'advanced', 'Current Game Category');
    }
    add_action('wpseo_register_extra_replacements', 'register_custom_yoast_variables');
    

    Usage in Yoast SEO boxes as custom_variable:

    %%game_cat%%
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search