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插件中的主要类别,但上述内容似乎没有起到作用。
有人能帮我吗?
向你问好,Dylan Smit
SO网友:Sergey Harchevnikov
改为尝试
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
SO网友:Chris
你需要改变product
到product_cat
和_yoast_wpseo_primary_category
到_yoast_wpseo_primary_product_cat
让它发挥作用。在保存或更新产品时,它将抓住最深的product_id
并将其设置为product_id
在wp_postmeta
桌子
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;
}