Site icon Hip-Hop Website Design and Development

Set Primary category using the Yoast SEO plugin

function set_primary_on_publish ($post_id) {
    global $post; 

    $categories = get_the_terms( $post->ID, 'category' ); 
    // wrapper to hide any errors from top level categories or products without category
    if ( $categories && ! is_wp_error( $category ) ) : 

        // loop through each cat
        foreach($categories as $category) :
          // get the children (if any) of the current cat
          $children = get_categories( array ('taxonomy' => 'category', 'parent' => $category->term_id ));

          if ( count($children) == 0 ) {

                $childid = $category->term_id;
                update_post_meta($post->ID,'_yoast_wpseo_primary_category',$childid);

          }
        endforeach;

    endif;

    }
add_action( 'save_post', 'set_primary_on_publish', 10, 2 );
add_action( 'edit', 'set_primary_on_publish', 10, 2 );
add_action( 'wp_insert_post', 'set_primary_on_publish', 10, 2 );

I’m trying to save the deepest child category as the primary category in the Yoast SEO plugin however the above doesn’t seem to do the job.

Anyone who can help me out on this?

Best regards,
Dylan Smit