我已经阅读了有关基于帖子标签分配类别的其他答案。但这可以基于postmeta来完成吗?
我假设可以,并且我一直在尝试更改以下代码段(在另一个答案中引用)以实现此目的。但是我没有运气调整它以引用 postmeta meta_key(delivery_option)和 meta_value(pick-up、postal、post & parcel),然后自动分配一个类别(pick-up、postal 或 post & parcel)。
如果相关,上面的 postmeta 键和值已由另一个插件添加。
function auto_add_category ($product_id = 0) {
if (!$product_id) return;
// because we use save_post action, let's check post type here
$post_type = get_post_type($post_id);
if ( "product" != $post_type ) return;
$tag_categories = array (
'ring' => 'Jewellery'
'necklace' => 'Jewellery',
'dress' => 'Clothing',
);
// get_terms returns ALL terms, so we have to add object_ids param to get terms to a specific product
$product_tags = get_terms( array( 'taxonomy' => 'product_tag', 'object_ids' => $product_id ) );
foreach ($product_tags as $term) {
if ($tag_categories[$term->slug] ) {
$cat = get_term_by( 'name', $tag_categories[$term->slug], 'product_cat' );
$cat_id = $cat->term_id;
if ($cat_id) {
$result = wp_set_post_terms( $product_id, $cat_id, 'product_cat', true );
}
}
}
}
add_action('save_post','auto_add_category');
披露:我正在建立一个 WordPress 网站并边走边学。这可能是一个显而易见的问题,但请放心,经过数小时的研究以尝试回答我自己(这一切都很好,我在研究时学到了其他东西......只是不是正确的东西!)。非常感谢您提供任何精通见解。