我有一个函数可以在 WooCommerce 的存档页面上返回产品类别缩略图。这很好用。
我想做的是在查看子类别时能够返回父类别缩略图。
这是我目前得到的代码:
function woocommerce_category_image() {
if ( is_product_category() ){
global $wp_query;
$cat = $wp_query->get_queried_object();
$thumbnail_id = get_term_meta( $cat->term_id, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
if ( $image ) {
echo '<img src="' . $image . '" alt="' . $cat->name . '" />';
}
}
}
任何人都可以帮助修改查询,以便它显示父类别图像。
理想情况下,如果有子缩略图,则显示子缩略图更好,如果没有,则返回父缩略图并显示。
最佳答案
要避免顶级类别上出现空图像,请使用以下内容:
function woocommerce_category_image() {
if ( is_product_category() ){
$term = get_queried_object(); // get the WP_Term Object
$term_id = $term->parent > 0 ? $term->parent : $term->term_id; // Avoid an empty image on the top level category
$image_src = wp_get_attachment_url( get_term_meta( $term_id, 'thumbnail_id', true ) ); // Get image Url
if ( ! empty($image_src) ) {
echo '<img src="' . $image_src . '" alt="' . $term->name . '" />';
}
}
}
代码进入事件子主题(或事件主题)的 functions.php 文件。经过测试并有效。
更新(与您的评论相关)
此处如果查询的产品类别没有为其设置图片,则将显示父产品类别图片。
function woocommerce_category_image() {
if ( is_product_category() ){
$term = get_queried_object(); // get the WP_Term Object
$image_id = get_term_meta( $term->term_id, 'thumbnail_id', true );
if( empty( $image_id ) && $term->parent > 0 ) {
$image_id = get_term_meta( $term->parent, 'thumbnail_id', true );
}
$image_src = wp_get_attachment_url( $image_id ); // Get the image Url
if ( ! empty($image_src) ) {
echo '<img src="' . $image_src . '" alt="' . $term->name . '" />';
}
}
}
代码进入事件子主题(或事件主题)的 functions.php 文件。经过测试并有效。
关于php - 查看子类别时显示 WooCommerce 父类别缩略图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62430846/