php - Auto-Select Parent Category as Primary

I am using Yoast SEO Premium to handle the selection of Primary Categories. I am currently working with a Listing (listi

I am using Yoast SEO Premium to handle the selection of Primary Categories. I am currently working with a Listing (listing) custom post type with a hierarchal taxonomy of Listing Category (listing_cat). I need the topmost parent to be auto-selected as the Primary Category on Publish or Edit.

The code I have tried is below. It auto-selects the parent item as a category when its child category is selected, but I need to take it a step further. I feel I am close, but missing something.

/* Auto Select Listing Parent Category on Child Category Select */

add_action('save_post', 'am_assign_listing_parent_terms', 10, 2);

function am_assign_listing_parent_terms($post_id, $post){

    if($post->post_type != 'listing')
        return $post_id;

    // get all assigned terms   
    $terms = wp_get_post_terms($post_id, 'listing_cat' );
    foreach($terms as $term){
        while($term->parent != 0 && !has_term( $term->parent, 'listing_cat', $post )){
            // move upward until we get to 0 level terms
            wp_set_post_terms($post_id, array($term->parent), 'listing_cat', true);
            $term = get_term($term->parent, 'listing_cat');
            // Update Yoast SEO Post Meta with Primary Category
            update_post_meta($post_id,'_yoast_wpseo_primary_listing_cat',$term);
        }
    }
}

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 have referenced this article: Set Primary category using the Yoast SEO plugin - but I need the exact opposite of what it does.

Any help is appreciated.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745036998a4607581.html

相关推荐

  • php - Auto-Select Parent Category as Primary

    I am using Yoast SEO Premium to handle the selection of Primary Categories. I am currently working with a Listing (listi

    10小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信