Woocommerce插件:Woocommerce类别横幅-添加类别横幅到单个产品


Woocommerce Plug-in: Woocommerce Category Banner - Add Category banner to single product

使用插件Woocommerce Category Banner,我能够在每个woocommerce类别页面上插入横幅图像(尽管插件在后端在woocommerce类别页面上添加了横幅字段)。

我正试图找到一种方法来插入类别横幅图像在单个产品页面(1级以上)。

这是用于显示类别横幅的代码(我已将其包含在/theme/woocommerce.php上):

//Retreives and print the category banner
global $woocommerce;
global $wp_query;
// Make sure this is a product category page
if ( is_product_category() ) {
    $cat_id = $wp_query->queried_object->term_id;
    $term_options = get_option( "taxonomy_term_$cat_id" ); 
    // Ge the banner image id
    if ( $term_options['banner_url_id'] != '' )
        $url = wp_get_attachment_url( $term_options['banner_url_id'] ); 
    // Exit if the image url doesn't exist
    if ( !isset( $url ) or $url == false )
        return;
    // Get the banner link if it exists
    if ( $term_options['banner_link'] != '' )
        $link = $term_options['banner_link'];
    // Print Output
    if ( isset( $link ) )
        echo "<a href='" . $link . "'>"; 
    if ( $url != false ) 
        echo "<img src='" . $url . "' class='category_banner_image' />";
    if ( isset( $link ) )
        echo "</a>";
}

使用我在这里找到的代码,直接在上面的代码之后,我能够在单个产品页面上插入类别缩略图:

elseif ( is_product() ) {
    $terms = get_the_terms( $post->ID, 'product_cat' );
    foreach ( $terms as $term ){
        $category_name = $term->name;
        $category_thumbnail = get_woocommerce_term_meta($term->term_id, 'thumbnail_id', true);
        $image = wp_get_attachment_url($category_thumbnail);
        echo '<img class="category_banner_image" src="'.$image.'">';
}

关于如何修改代码块拉"banner_url_id",woocommerce类别横幅插件添加到每个类别,并插入在单个产品页面上的任何想法?

图像的url存储在wp_option表中,因此需要将其放入content-single-product.php:

$cat_id = $wp_query->queried_object->term_id;
$term_options = get_option( "taxonomy_term_$cat_id" );
$url = wp_get_attachment_url( $term_options['banner_url_id'] );
if ( $url != false ) 
    echo "<img src='" . $url . "' class='category_banner_image' />";
编辑:

如果你想在content_single_product.php中获得横幅,你需要这样思考:每个产品都可以与许多术语相关联(如:红色,蓝色,白色等),所以你需要选择一个随机的图像与每个类别相关联,对吗?

 $termArray =  array();
 $terms = get_the_terms($post->ID, "product_cat");
 //insert id's in to array
 foreach ($terms as $id) {
    $termArray[] = $id->term_id;
 }
//get random id
$randomId = array_rand($termArray);
 //final ID
$cat_id = $termArray[$randomId];
$term_options = get_option( "taxonomy_term_$cat_id" );
$url = wp_get_attachment_url( $term_options['banner_url_id'] );
if ( $url != false ) 
   echo "<img src='" . $url . "' class='category_banner_image' />";