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
评论列表(0条)