Woocommerce 自定义SEO

WordPress + Woocommerce 是世界上用得最多的电商开发工具,但是设置上总是不能满足我们多样的需求,接下来,我将从订制的角度来阐述如何如何给产品增加meta标签,并用meta标签实现给Google喂数据,从而满足Google对产品搜索要求。

1、在woocommerce后台增加SEO选项卡

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// 在后台增加一个选项卡,显示的名字是SEO,这个选项卡的值是seo_product_data
add_filter( 'woocommerce_product_data_tabs', 'bd_product_settings_tabs' );
function bd_product_settings_tabs( $tabs ){

//unset( $tabs[ 'shipping' ] );

$tabs[ 'SEO' ] = array(
'label' => 'SEO',
'target' => 'seo_product_data',
'class' => array( 'show_if_virtual' ),
'priority' => 21,
);
return $tabs;

}
// 在SEO选项卡(seo_product_data)里面增加输入框,让用户能输入自己想要的内容
add_action( 'woocommerce_product_data_panels', 'seo_product_panels' );
function seo_product_panels(){

echo '<div id="seo_product_data" class="panel woocommerce_options_panel hidden">';

woocommerce_wp_text_input(
array(
'id' => 'bd_keyword',
'value' => 'Default Value', //直接写的默认值
'label' => 'KeyWord', //输入框前面的提示
'description' => 'In put keyword', //输入框后面的备注
)
);

woocommerce_wp_textarea_input(
array(
'id' => 'bd_description',
'value' => get_post_meta(get_the_ID(), 'bd_description', true), // 从数据库中读取的值当作默认值
'label' => 'Description',
'desc_tip' => true,
'description' => 'In put Description',
)
);

woocommerce_wp_text_input(
array(
'id' => 'bd_value',
'value' => 22, //默认值22
'label' => 'Value',
'description' => 'In put value',
)
);


echo '</div>';

}

// 将输入框中的数据存储到数据库中,方便在其他地方调用
add_action( 'woocommerce_process_product_meta', 'bd_save_fields' );
function bd_save_fields( $id ){

update_post_meta( $id, 'bd_keyword', sanitize_text_field( $_POST[ 'bd_keyword' ] ) ); //把bd_keyword的值存入自定义的bd_Keyword中

update_post_meta( $id, 'bd_description', sanitize_textarea_field( $_POST[ 'bd_description' ] ) );

update_post_meta( $id, '_wc_average_rating', sanitize_text_field( $_POST[ 'bd_value' ] ) ); //把bd_value的值存入系统默认的average_rating中

}

注意:
1、输入框的类型除了例子中的woocommerce_wp_text_input、woocommerce_wp_textarea_input还有woocommerce_wp_checkbox、woocommerce_wp_select
2、输入框类型要后后面的sanitize_text_field相对应,除了sanitize_textarea_field外还有absint、sanitize_email、sanitize_title、wp_kses、esc_url_raw
3、bd_save_fields中的$id为post即product的ID

2、Meta的应用

可以在任何位置用如下方式获取到当前产品的自定义的值:

1
"key" => get_post_meta(get_the_ID(), 'bd_keyword', true),
1
$key = get_post_meta(get_the_ID(), 'bd_value', true);
1
2
$product = wc_get_product();					//经过试验,用默认函数时必须要加此行
$reviewcount = $product->get_review_count(); //系统中默认有的函数可以用函数直接读取

3、Google对商品类Meta的要求

Google对商品类的Meta要求是要包含:Product、Review、Offer三个。
Product类下如果有Offer,那么必须要在Prodcut类下包含review、aggregateRating中的一个或全部,否则会提示非致命错误。
详细的修改方法,咱们下期见!

Author

MelonCloud

Posted on

2024-11-04

Updated on

2024-11-05

Licensed under

Comments