如果我的某些产品出现在特定类别中,我想为它们显示不同的缩略图。
我已从特定类别中删除了当前缩略图,并且我正在使用自定义字段为要替换的产品提取新缩略图,效果很好。但是,当我尝试调用其余产品的普通缩略图时,它不起作用 - 有什么想法吗?
add_action( 'woocommerce_before_main_content', 'remove_test_category_thumbnails', 10 );
function remove_test_category_thumbnails() {
if (is_product_category('test-category')) {
remove_action('woocommerce_before_shop_loop_item_title' , 'woocommerce_template_loop_product_thumbnail' , 10);
}
}
add_action( 'woocommerce_before_shop_loop_item_title', 'add_test_category_thumbnails', 10 );
function add_test_category_thumbnails() {
global $post;
$testCatThumb = get_post_meta( $post->ID, 'step_dad_mug', true);
if (is_product_category('test-category') && (isset($testCatThumb)) ) {
echo wp_get_attachment_image( $testCatThumb );
}
else
echo woocommerce_get_product_thumbnail();
}
}
答案 0 :(得分:1)
您需要echo
woocommerce_get_product_thumbnail
。检查下面的代码。
add_action( 'woocommerce_before_main_content', 'remove_test_category_thumbnails', 10 );
function remove_test_category_thumbnails() {
if (is_product_category('test-category')) {
remove_action('woocommerce_before_shop_loop_item_title' , 'woocommerce_template_loop_product_thumbnail' , 10);
}
}
add_action( 'woocommerce_before_shop_loop_item_title', 'add_test_category_thumbnails', 10 );
function add_test_category_thumbnails() {
global $post;
$testCatThumb = get_post_meta( $post->ID, 'step_dad_mug', true);
if( is_product_category( 'test-category' ) && ( isset( $testCatThumb ) ) ) {
echo wp_get_attachment_image( $testCatThumb );
}else{
echo woocommerce_get_product_thumbnail();
}
}
答案 1 :(得分:0)
以下函数需要一个 post id,这是你传递的吗?
wp_get_attachment_image();
作为 if 条件的一部分,您可以检查值是否为正确的值类型:
is_numeric($testCatThumb);
我倾向于创建可读的变量,而不是每次阅读时都必须用大脑解析可怕的条件:
function add_test_category_thumbnails() {
global $post;
$testCatThumb = get_post_meta( $post->ID, 'step_dad_mug', true);
$isPostId = !empty($testCatThumb) && is_numeric($testCatThumb);
$isValidAttachmentId = is_product_category('test-category') && $isPostId;
$image = $isValidAttachmentId ? wp_get_attachment_image($testCatThumb) : '';
// display custom image, or fallback to woocommerce thumbnail
echo !empty($image) ? $image : woocommerce_get_product_thumbnail();
}