【问题标题】:How to make an image link to an archive page with php/woocommerce如何使用 php/woocommerce 将图像链接到存档页面
【发布时间】:2018-03-13 14:36:23
【问题描述】:

我创建了一个自定义字段,用于向 woocommerce 中的产品添加品牌徽标图像。在前端,徽标显示在产品摘要的开头 - 带有以下代码的产品标题上方:

/**Add MFG Logo Above Short Description*/

add_action( 'woocommerce_single_product_summary', 'brands');

function brands() {
global $post;
global $product;


$mfglogo= get_post_meta($post->ID, 'brand_logo', true);

echo '<div>'; 
echo '<img src="' . $mfglogo.'"></a>';
echo'</div>';

} 

我想让这张图片可以链接到相应的品牌存档页面。我还为品牌创建了一个全局属性,因此我可以按品牌过滤产品页面。

我了解到您可以在前端将您的属性制作成一个列表,并且可以使用以下代码将它们点击到他们的属性存档页面:

/**Add Brand Link to META List*/

function list_attributes( $product ) {

global $product;
global $post;

$attributes = $product->get_attributes();

if ( ! $attributes ) {

    return;

}

foreach ( $attributes as $attribute ) {

    // Get the taxonomy.
    $terms = wp_get_post_terms( $product->id, $attribute[ 'name' ], 'all' );
    $taxonomy = $terms[ 0 ]->taxonomy;

    // Get the taxonomy object.
    $taxonomy_object = get_taxonomy( $taxonomy );

    // Get the attribute label.
    $attribute_label = $taxonomy_object->labels->name;

    // Display the label followed by a clickable list of terms.
    echo get_the_term_list( $post->ID, $attribute[ 'name' ] , '<div class="attributes">' . $attribute_label . ': ' , ', ', '</div>' );
    break;

}

}

add_action( 'woocommerce_product_meta_end', 'list_attributes' );

。我怎样才能使用这个想法使徽标图像可链接???

【问题讨论】:

  • 专业调试提示:使用var_dump( $attriubute );查看数组的内容,了解结构,这样你就可以“归零”你需要的部分......
  • 感谢您的提示,我正在使用它来打印有帮助的信息。不过,我仍然不确定在调试之外使用哪个值/语法...

标签: php woocommerce attributes


【解决方案1】:

你可以替换这个:

echo '<div>'; 
echo '<a href="' . $attribute. '"><img src="' . $download4 .'"></a>';
echo'</div>';

以下内容:

foreach ( $attribute as $attr) {

    echo '<div>'; 
    echo '<a href="#' . $attr->get_name(). '"><img src="' . $download4 .'"></a>';
    echo'</div>';

    // Uncomment the follwing line if you want to display the first attribute only (makes sense since you only have one logo image)
    // break;
}

【讨论】:

  • 感谢 sn-p。不幸的是,它会产生一个可捕获的致命错误。 '类的对象不能转换为字符串......
  • 请在循环中使用 'var_dump($attr)' 并告诉我它返回什么
  • object(WC_Product_Attribute)#2019 (1) { ["data":protected]=> array(6) { ["id"]=> int(10) ["name"]=> string(8) "pa_brand" ["options"]=> array(1) { [0]=> int(184) } ["position"]=> int(0) ["visible"]=> bool(false ) ["variation"]=> bool(false) } } 可捕获的致命错误:WC_Product_Attribute 类的对象无法转换为字符串
  • 第一部分是 var_dump 输出。
  • 我编辑了代码以将属性名称反映为链接。请注意,您没有提供有关所需输出或您打算做什么的足够信息,因此这可能不适合您。
猜你喜欢
  • 2015-11-27
  • 2016-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-14
  • 1970-01-01
  • 2017-11-18
  • 1970-01-01
相关资源
最近更新 更多