我在woocommerce产品>常规选项卡中添加了自定义字段。但我没有使用以下链接获取这些自定义字段的值:-http://yoursite.com/wp-json/wc/v2/products/
我的代码:-
//Display Fields
add_action( \'woocommerce_product_options_general_product_data\', \'woo_add_custom_general_fields\' );
//Save Fields
add_action( \'woocommerce_process_product_meta\', \'woo_add_custom_general_fields_save\' );
function woo_add_custom_general_fields() {
global $woocommerce, $post;
echo \'<div class="options_group">\' ;
//Purchasing Cost
woocommerce_wp_text_input(
array(
\'id\' => \'purchasing_cost\',
\'placeholder\' => \'Purchasing Cost\',
\'label\' => __(\'Purchasing Cost\', \'woocommerce\'),
\'type\' => \'text\',
\'show_in_rest\' => true,
\'rest_base\' => \'products\',
\'rest_controller_class\' => \'WP_REST_Products_Controller\',
)
);
//OverHead
woocommerce_wp_text_input(
array(
\'id\' => \'overhead\',
\'placeholder\' => \'Overhead\',
\'label\' => __(\'Overhead\', \'woocommerce\'),
\'type\' => \'text\',
\'show_in_rest\' => true,
\'rest_base\' => \'products\',
\'rest_controller_class\' => \'WP_REST_Products_Controller\',
)
);
echo \'</div>\';
}
//To Save data
function woo_add_custom_general_fields_save($post_id) {
//Purchasing Cost
$woocommerce_purchasing_cost_field = $_POST[\'purchasing_cost\'];
if (!empty($woocommerce_purchasing_cost_field))
update_post_meta($post_id, \'purchasing_cost\', esc_attr($woocommerce_purchasing_cost_field));
//OverHead
$woocommerce_overhead_field = $_POST[\'overhead\'];
if (!empty($woocommerce_overhead_field))
update_post_meta($post_id, \'overhead\', esc_attr($woocommerce_overhead_field));
}
提前谢谢。
SO网友:MAYANK SONKAR
回答我的问题
add_action( \'rest_api_init\', \'slug_register_purchasing\' );
function slug_register_purchasing() {
register_rest_field( \'product\',
\'purchasing_cost\',
array(
\'get_callback\' => \'slug_get_purchasing_cost\',
\'update_callback\' => null,
\'schema\' => null,
)
);
}
function slug_get_purchasing_cost( $object, $field_name, $request ) {
return get_post_meta( $object[ \'id\' ], $field_name, true );
}
add_action( \'rest_api_init\', \'slug_register_overhead\' );
function slug_register_overhead() {
register_rest_field( \'product\',
\'overhead\',
array(
\'get_callback\' => \'slug_get_overhead\',
\'update_callback\' => null,
\'schema\' => null,
)
);
}
function slug_get_overhead( $object, $field_name, $request ) {
return get_post_meta( $object[ \'id\' ], $field_name, true );
}
有关详细说明
http://v2.wp-api.org/extending/modifying/