我需要创建一个短代码,根据产品所属的类别在 Woocommerce 产品上显示特定的 WordPress 菜单。类别和菜单都是通过 ID 标识的,但我似乎无法使其工作。
这是我的代码:
function view_color_menu( $category ) {
$catarray = get_the_category( $post->ID );
foreach ($catarray as $cat) {
$catid = $cat->term_id;
if ($catid == 31) {
wp_nav_menu( array( 'menu_id' => '16' ) );
}
if ($catid == 35) {
wp_nav_menu( array( 'menu_id' => '17' ) );
}
if ($catid == 42) {
wp_nav_menu( array( 'menu_id' => '21' ) );
}
}
}
add_shortcode('get_color_menu', 'view_color_menu');
您的代码有多个错误:
get_the_category()
仅适用于 WordPress 博客文章类别,不适用于产品类别 (这是自定义分类法),wp_nav_menu()
函数默认是echoed,但在短代码中,应该始终返回它。get_the_ID()
,global $post;
与 $post->ID
。假设
wp_nav_menu()
函数具有正确的参数设置,请尝试以下修改后的代码:
add_shortcode('color_menu', 'color_menu_shortcode');
function color_menu_shortcode( $atts ) {
extract( shortcode_atts( array(
'product_id' => get_the_ID()
), $atts, 'color_menu' ) );
// Array of associated term ID with Menu ID pairs
$data_term_menu = array(
'31' => '16',
'35' => '17',
'42' => '21',
);
ob_start(); // start buffering the content
// Loop through associated Term ID(s) Key / Menu ID(s) value
foreach ( $data_term_menu as $term_id => $menu_id ) {
// Check if the current term ID is set in the product
if ( has_term( intval($term_id), 'product_cat', $product_id ) ) {
return wp_nav_menu( array( 'menu_id' => $menu_id ) );
}
}
return ob_get_clean(); // Return the buffered content
}
短代码使用
[color_menu]
[color_menu product_id="18"]