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 );
我试图保存最深的子类作为主要类别在Yoast SEO插件,但上述似乎没有做的工作。
有人能帮我解决这个问题吗?
我向你问好,迪伦·斯米特
发布于 2019-01-17 04:35:22
试一试
update_post_meta($post->ID,'_yoast_wpseo_primary_category',$childid);
使用以下功能:
function wpseoPrimaryTerm($taxonomy, $postID, $term){
if ( class_exists('WPSEO_Primary_Term') ) {
// Set primary term.
$primaryTermObject = new WPSEO_Primary_Term($taxonomy, $postID);
$primaryTermObject->set_primary_term($term);
// Save primary term.
$primaryTermObjectAdmin = new WPSEO_Primary_Term_Admin();
$primaryTermObjectAdmin->save_primary_terms($postID);
}else{
echo 'Class WPSEO does not exit';
}
}
其中$taxonomy - taxonomy name, $PostID - $post->ID, $term - $childid
发布于 2019-07-24 16:50:49
您需要将product
更改为product_cat
,将_yoast_wpseo_primary_category
更改为_yoast_wpseo_primary_product_cat
以使其正常工作。在保存或更新产品时,它将获取最深的product_id
,并将其设置为wp_postmeta
表中的product_id
。
function set_primary_on_publish ($post_ID) {
global $post;
$categories = get_the_terms( $post->ID, 'product_cat' );
// 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' => 'product_cat', 'parent' => $category->term_id ));
if ( count($children) == 0 ) {
$childid = $category->term_id;
update_post_meta($post->ID,'_yoast_wpseo_primary_product_cat',$childid);
}
endforeach;
endif;
}
https://wordpress.stackexchange.com/questions/314633
复制相似问题