WooCommerce产品关联分类及cross-sell分类YITH自定义列实现问题
实现方案
你不需要直接写SQL查询,使用WooCommerce和WordPress内置的函数即可实现需求,同时能避免表前缀不匹配、数据未过滤等问题,修改后的完整代码如下:
// Add Column Names if( !function_exists('yith_wcbep_add_columns') ) { function yith_wcbep_add_columns( $columns ) { $columns['new_column'] = 'Related...'; $columns['new_column2'] = 'Also See...'; return $columns; } add_filter( 'yith_wcbep_default_columns', 'yith_wcbep_add_columns', 99 ); } // Add Column content to Column Names if( !function_exists('yith_wcbep_manage_custom_columns_add_columns_to_new_column') ) { function yith_wcbep_manage_custom_columns_add_columns_to_new_column( $value, $column_name, $post ) { // 先获取当前产品对象 $product = wc_get_product( $post->ID ); if( !$product ) return $value; if ( 'new_column' == $column_name ) { // 拉取产品所属的产品分类列表 $product_cats = wp_get_post_terms( $post->ID, 'product_cat', array( 'fields' => 'names' ) ); if( !is_wp_error( $product_cats ) && !empty( $product_cats ) ) { $value = implode( ', ', $product_cats ); } else { $value = '无关联分类'; } } if ( 'new_column2' == $column_name ) { // 拉取产品cross-sell分类列表:此处适配你存储在termmeta的crosssell标识逻辑 $cross_sell_cats = array(); // 先获取产品所属分类ID $cat_ids = wp_get_post_terms( $post->ID, 'product_cat', array( 'fields' => 'ids' ) ); if( !is_wp_error( $cat_ids ) && !empty( $cat_ids ) ) { foreach( $cat_ids as $cat_id ) { $is_crosssell = get_term_meta( $cat_id, 'crosssell', true ); if( $is_crosssell ) { $cross_sell_cats[] = get_term( $cat_id )->name; } } } // 如果你需要的是cross-sell产品对应的分类,替换上面逻辑为下方代码即可 /* $cross_sell_ids = $product->get_cross_sell_ids(); $cross_sell_cats = array(); if( !empty( $cross_sell_ids ) ) { foreach( $cross_sell_ids as $cs_id ) { $cs_cats = wp_get_post_terms( $cs_id, 'product_cat', array( 'fields' => 'names' ) ); if( !is_wp_error( $cs_cats ) && !empty( $cs_cats ) ) { $cross_sell_cats = array_merge( $cross_sell_cats, $cs_cats ); } } $cross_sell_cats = array_unique( $cross_sell_cats ); } */ if( !empty( $cross_sell_cats ) ) { $value = implode( ', ', $cross_sell_cats ); } else { $value = '无cross-sell分类'; } } return $value; } add_filter( 'yith_wcbep_manage_custom_columns', 'yith_wcbep_manage_custom_columns_add_columns_to_new_column', 10, 3 ); }
注意事项
- 代码中针对cross-sell分类提供了两种逻辑:第一种适配你之前查询termmeta中
crosssell标识的需求,第二种是读取产品绑定的cross-sell产品对应的分类,你可以根据实际需求注释掉不需要的部分即可。 - 之前SQL查询返回空的主要原因是:硬编码了表前缀
wp_,部分站点的表前缀不是默认的wp_,同时$id变量没有正确赋值,使用内置get_term_meta函数可以自动适配表前缀和数据过滤。
内容的提问来源于stack exchange,提问作者Morne
相关产品推荐
相关产品推荐

