wooocommerce 添加自定义HTML字段,并设置为类别页面副标题。

我们在编辑产品的时候,想尽量展示更多的产品优势,但是woocomemrce 并不支持在产品列表页面添加自定义内容,所以我们可以通过PHP代码的形式为woocommerce 的产品类别页面每个产品添加副标题或者HTML内容。

我们通过wp-content/themes/主题/functions.php文件添加一下PHP代码就能实现这类功能

/*产品列表副标题页*/

function woocommerce_product_custom_fields()
{
  $args = array(
    	'id' => 'woocommerce_custom_fields',
    	'label' => __('Product list', 'cwoa'),
  );
  woocommerce_wp_textarea_input($args);
}
 
add_action('woocommerce_product_options_general_product_data', 'woocommerce_product_custom_fields');

function save_woocommerce_product_custom_fields($post_id)
{
    $product = wc_get_product($post_id);
    $custom_fields_woocommerce_title = isset($_POST['woocommerce_custom_fields']) ? $_POST['woocommerce_custom_fields'] : '';
    $product->update_meta_data('woocommerce_custom_fields', sanitize_text_field($custom_fields_woocommerce_title));
    $product->save();
}
add_action('woocommerce_process_product_meta', 'save_woocommerce_product_custom_fields');


function woocommerce_custom_fields_display()
{
  global $post;
  $product = wc_get_product($post->ID);
    $custom_fields_woocommerce_title = $product->get_meta('woocommerce_custom_fields');
  if ($custom_fields_woocommerce_title) {
        echo '<div class="productlist">'.($custom_fields_woocommerce_title).'</div>';
  }
}
add_action('woocommerce_after_shop_loop_item_title', 'woocommerce_custom_fields_display');

// 产品副标题支持HTML
if( ! empty( $_POST['woocommerce_custom_fields1'] ) )
    update_post_meta( $post_id, 'woocommerce_custom_fields1', wp_kses_post( $_POST['woocommerce_custom_fields1'] ) );

我们到后台的产品编辑页面,产品数据选项中会发现多出来一个字段框,我们就可以自定义添加自己的副标题或者html显示在产品类别页面上了

wooocommerce 添加自定义HTML字段,并设置为类别页面副标题。

最终我们将得到的效果便是在产品类别页面,每个产品都可自定义添加副标题的效果

wooocommerce 添加自定义HTML字段,并设置为类别页面副标题。

注意:如果想将标题更改为其他位置的话,请参考woocommerce 类别hook的钩子

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索
error: 警告:内容选择已禁用!