Set Primary category using the Yoast SEO plugin

Question
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

0
, , , Dylan Smit 5 years 2018-09-19T10:26:48-05:00 0 Answers 179 views 0

Leave an answer

Browse
Browse