B2主題為文章和商品使用同一套標(biāo)簽功能,但是當(dāng)我們點(diǎn)擊標(biāo)簽的時(shí)候,標(biāo)簽的存檔頁(yè)面中只有文章,沒(méi)有相關(guān)的商品。這個(gè)教程就來(lái)實(shí)現(xiàn),讓標(biāo)簽存檔頁(yè)面也顯示相關(guān)的商品,比如訪(fǎng)問(wèn) http://www.ydqwiac.cn/tag/corporate-themes,就可以看到有商品也有文章。

標(biāo)簽存檔顯示相關(guān)商品
要實(shí)現(xiàn)這個(gè)功能,只需要將下面的代碼添加到子主題的 functions.php 即可
/**
* 讓標(biāo)簽存檔頁(yè)面顯示相關(guān)商品
* http://www.ydqwiac.cn/docs/b2/b2-dev/tag-archive-args
*/
function b2child_add_products_to_tag_archive( $args, $data ) {
if( isset($data['post_tag']) && !empty($data['post_tag']) ){
$args['post_type'] = array( 'post', 'shop' ); // 顯示文章post和商品shop
}
return $args;
}
add_action( 'b2_post_loop_args', 'b2child_add_products_to_tag_archive', 20, 2 );
注意看第9行的數(shù)組array( 'post', 'shop' ),設(shè)置了顯示文章和商品,如果你的網(wǎng)站還有其他文章類(lèi)型也使用了標(biāo)簽post_tag,也可以添加進(jìn)來(lái)。
標(biāo)簽存檔顯示相關(guān)商品的商品分類(lèi)
僅僅添加上面的代碼,我們就可以在標(biāo)簽存檔中看到相關(guān)的商品,但是,你會(huì)發(fā)現(xiàn)無(wú)法顯示【商品分類(lèi)】,比如上面圖片中的【W(wǎng)ordPress收費(fèi)主題】,還需要添加下面的代碼:
/**
* 在post文章類(lèi)型增加shop商品的分類(lèi)顯示
* http://www.ydqwiac.cn/docs/b2/b2-dev/tag-archive-args
*/
function b2child_post_meta_filter( $meta, $post_id ) {
$post_type = get_post_type( $post_id );
if( $post_type == 'shop' ) { // 針對(duì)商品shop這個(gè)文章類(lèi)型獲取商品分類(lèi)
$post_cats = get_the_terms( $post_id, 'shoptype' );
$cats_data = array();
foreach($post_cats as $cat){
if(isset($cat->term_id)){
$color = get_term_meta($cat->term_id,'b2_tax_color',true);
$color = $color ? $color : '#607d8b';
$link = get_term_link( $cat->term_id, 'shoptype' );
$cats_data[] = array(
'name'=>$cat->name,
'color'=>$color,
'link'=>$link
);
}
}
unset($post_cats);
$meta['cats'] = $cats_data;
}
return $meta;
}
add_filter('b2_get_post_metas', 'b2child_post_meta_filter', 10, 2);
到這里就可以了。



