我使用以下代码将面板添加到管理菜单屏幕,以便用户能够将购物车链接添加到他们的菜单:
function my_add_meta_box() {
add_meta_box( \'custom-meta-box\', __( \'Cart\' ), \'my_nav_menu_item_link_meta_box\', \'nav-menus\', \'side\', \'default\' );
}
add_action( \'admin_init\', \'my_add_meta_box\' );
function my_nav_menu_item_link_meta_box() {
global $_nav_menu_placeholder, $nav_menu_selected_id;
$_nav_menu_placeholder = 0 > $_nav_menu_placeholder ? $_nav_menu_placeholder - 1 : -1;
?>
<div id="posttype-cart" class="posttypediv">
<div id="tabs-panel-cart" class="tabs-panel tabs-panel-active">
<ul id="cart-checklist" class="categorychecklist form-no-clear">
<li>
<label class="menu-item-title">
<input type="checkbox" class="menu-item-checkbox" name="menu-item[<?php echo (int) $_nav_menu_placeholder; ?>][menu-item-object-id]" value="-1"> <?php esc_html_e( \'Cart\' ); ?>
</label>
<input type="hidden" class="menu-item-type" name="menu-item[<?php echo (int) $_nav_menu_placeholder; ?>][menu-item-type]" value="post_type">
<input type="hidden" class="menu-item-object" name="menu-item[<?php echo (int) $_nav_menu_placeholder; ?>][menu-item-object]" value="page">
<input type="hidden" class="menu-item-object-id" name="menu-item[<?php echo (int) $_nav_menu_placeholder; ?>][menu-item-object-id]" value="<?php echo get_option( \'woocommerce_cart_page_id\' ); ?>">
<input type="hidden" class="menu-item-title" name="menu-item[<?php echo (int) $_nav_menu_placeholder; ?>][menu-item-title]" value="<?php esc_html_e( \'Cart\' ); ?>">
</li>
</ul>
</div>
<p class="button-controls">
<span class="add-to-menu">
<input type="submit" <?php disabled( $nav_menu_selected_id, 0 ); ?> class="button-secondary submit-add-to-menu right" value="<?php esc_attr_e( \'Add to Menu\' ); ?>" name="add-post-type-menu-item" id="submit-posttype-cart">
<span class="spinner"></span>
</span>
</p>
</div>
<?php
}
我的问题是,是否可以在前端的购物车菜单项标签旁边动态添加一个计数器,显示购物车中的项目数?如果是,如何?我认为
wp_get_nav_menu_items
过滤器对此可能很有用,但如何识别其中的购物车菜单项,以便能够在前端动态修改其标签?
function my_get_nav_menu_items( $items ) {
foreach ( $items as $item ) {
if ( is_cart_menu_item( $item ) ) {
// add a counter beside the Cart menu item label
}
}
return $items;
}
add_filter( \'wp_get_nav_menu_items\', \'my_get_nav_menu_items\', 20 );