我正在尝试根据产品类别将没有图像的产品的默认图像占位符更改为图像。
我正在使用:
add_filter( 'woocommerce_placeholder_img_src', 'my_custom_woocommerce_placeholder', 10 );
// Function to return new placeholder image URL.
function my_custom_woocommerce_placeholder( $image_url )
{
if ($product_category == 'category1') {
$image_url = 'http://website.com/imageforCategory.png';
}
elseif ($product_category == 'category2') {
$image_url = 'http://website.com/imageforCategory.png';
}
else
{
$image_url = 'http://website.com/defaultImage.png';
}
return $image_url;
}
我一直无法在
$product_category
中检测到产品类别 ( functions.php
)我的主题文件。在
content-single-product.php
我只是定义的页面global $product
然后只是使用$product->get_categories();
获取产品类别。我该怎么做
functions.php
我的主题?
最佳答案
您可以使用 has_term() - 检查当前帖子是否有任何给定的条款。
所以你得到:
// Single product page
function filter_woocommerce_placeholder_img_src( $src ) {
// Get the global product object
global $product;
// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
// Has term (product category)
if ( has_term( 'categorie-1', 'product_cat', $product->get_id() ) ) {
$src = 'http://website.com/imageforCategory1.png';
} elseif ( has_term( array('categorie-2', 'categorie-3'), 'product_cat', $product->get_id() ) ) {
$src = 'http://website.com/imageforCategory2.png';
}
}
return $src;
}
add_filter( 'woocommerce_placeholder_img_src', 'filter_woocommerce_placeholder_img_src', 10, 1 );
// Archive/Shop page
function filter_woocommerce_placeholder_img ( $image_html, $size, $dimensions ) {
$dimensions = wc_get_image_size( $size );
$default_attr = array(
'class' => 'woocommerce-placeholder wp-post-image',
'alt' => __( 'Placeholder', 'woocommerce' ),
);
$attr = wp_parse_args( '', $default_attr );
$image = wc_placeholder_img_src( $size );
$hwstring = image_hwstring( $dimensions['width'], $dimensions['height'] );
$attributes = array();
foreach ( $attr as $name => $value ) {
$attribute[] = esc_attr( $name ) . '="' . esc_attr( $value ) . '"';
}
$image_html = '<img src="' . esc_url( $image ) . '" ' . $hwstring . implode( ' ', $attribute ) . '/>';
return $image_html;
}
add_filter( 'woocommerce_placeholder_img', 'filter_woocommerce_placeholder_img', 10, 3 );
注:
woocommerce_placeholder_img
钩子(Hook),用于存档/商店页面返回 $image_html
.该字符串可以根据您的需要进行调整。比如图片src、class、alt、size等..
关于php - 根据产品类别替换 WooCommerce 占位符图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65991942/