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;



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

  • If it doesn't do what you want, what's the erroneous/actual behaviour of this code? – Tom J Nowell Sep 19 '18 at 16:09

Try instead


Use below function:

function wpseoPrimaryTerm($taxonomy, $postID, $term){

  if ( class_exists('WPSEO_Primary_Term') ) {
  // Set primary term.
  $primaryTermObject = new WPSEO_Primary_Term($taxonomy, $postID);

  // Save primary term.
  $primaryTermObjectAdmin = new WPSEO_Primary_Term_Admin();
    echo 'Class WPSEO does not exit';

Where $taxonomy - taxonomy name, $PostID - $post->ID, $term - $childid


You can easily get Primary Category using Yoast plugin

Let check here How to Get Primary Category on WordPress Using Yoast Plugin

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.