问题描述
我已成功将自定义MetaBox添加到管理产品页面。上面的代码在管理区域中生成一个输入类型的文本,我可以在其中插入城市名称:
add_action( 'save_post_product','set_post_Metas_city',10,3 );
function set_post_Metas_city( $post_id,$post,$update ) {
if(isset($_POST['city']))
update_post_Meta($post_id,'city',esc_attr($_POST['city']));
}
add_action( 'add_Meta_Boxes','Metas_Boxes_city',50 );
function Metas_Boxes_city(){
add_Meta_Box( "options-city","City Name",'edit_form_after_title_cidade','product','normal' );
}
function edit_form_after_title_city($post) { ?>
<div id="mdiv">
<input type="text" style="width: 100%" name="city" value="<?PHP echo($post ? get_post_meta($post->ID,true) : ''); ?>" id="city" spellcheck="true" autocomplete="off" placeholder="<?PHP _e('Insert the city'); ?>">
</div>
<?PHP
}
现在,我使用以下挂钩函数,尝试在“商店页面”上显示自定义字段值(城市名称),如下所示:
// define the woocommerce_after_shop_loop_item callback
function action_woocommerce_after_shop_loop_item( ) {
// make action magic happen here...
echo($post ? get_post_meta($post->ID,true) : '');
};
// add the action
add_action( 'woocommerce_after_shop_loop_item','action_woocommerce_after_shop_loop_item',0 );
所以我试图得到类似的东西:
[Product Picture]
**City**
Category
Cake Ananas
$4,00
[BUY BUTTON]
如果我在回显中使用静态内容,则会在商店页面上获得所需的显示:
// define the woocommerce_after_shop_loop_item callback
function action_woocommerce_after_shop_loop_item( ) {
// make action magic happen here...
echo "Statictest";
};
但是缺少正确的变量。
// run the action
do_action( 'woocommerce_after_shop_loop_item' );
请问我在做什么错?有人可以帮忙吗?
解决方法
主要问题在于您上次使用$post->ID
的功能。从WooCommerce 3开始,钩子也比save_post_product
更好。请尝试以下重新访问的代码:
// Add custom product meta box
add_action( 'add_meta_boxes','add_product_metas_box_city',50 );
function add_product_metas_box_city(){
add_meta_box( "options-city",__("City Name"),'product_metas_box_city_content_callback','product','normal','high' );
}
// custom product meta box
function product_metas_box_city_content_callback( $post ) {
$value = get_post_meta( $post->ID,'city',true );
echo '<div id="mdiv">
<input type="text" style="width: 100%" name="city" value="'. $value .'" id="city" spellcheck="true" autocomplete="off" placeholder="'. __('Insert the city') .'">
</div>';
}
// Save city custom field value
add_action( 'woocommerce_admin_process_product_object','save_product_city_meta_value' );
function save_product_city_meta_value( $product ) {
if( isset($_POST['city']) ) {
$product->update_meta_data( 'city',sanitize_text_field( $_POST['city'] ) );
}
}
// Display city value on frontend products loop
add_action( 'woocommerce_after_shop_loop_item','action_woocommerce_after_shop_loop_item',10,0 );
function action_woocommerce_after_shop_loop_item() {
global $product;
$city = $product->get_meta('city');
if ( $city ) {
echo '<p class="city">'. $city .'</p>';
}
}
代码进入活动子主题(或活动主题)的functions.php文件中。经过测试,可以正常工作。