提问者:小点点

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


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

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

这是用于显示类别横幅的代码(我已将其包含在/主题/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.'">';
}

关于如何修改代码块以提取woocommerce类别横幅插件添加到每个类别并插入到单个产品页面上的“横幅url\u id”,您有什么想法吗?


共1个答案

匿名用户

图像的url存储在wp_选项表中,因此您需要将其放入单个产品的内容中。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' />";