我有一个函数,可以在WooCommerce的Archive页面上返回产品类别缩略图。这个功能很好用,但我想做的是,在查看子类目时,能够返回父类目缩略图。
我想做的是,当查看子分类时,能够返回父分类缩略图。
这是我目前的代码。
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文件的活动的子主题(或活动主题)。经过测试和工作。
只要改变 $cat->term_id
由 $cat->parent
获取父缩略图ID。
最终代码。
function woocommerce_category_image() {
if ( is_product_category() ){
global $wp_query;
$cat = $wp_query->get_queried_object();
$thumbnail_id = get_term_meta( $cat->parent, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
if ( $image ) {
echo '<img src="' . $image . '" alt="' . $cat->name . '" />';
}
}
希望能帮到你