有没有办法在PHP和WooCommerce中以编程方式创建产品类别并指定缩略图?

时间:2017-08-06 作者:dimitrisr

我想创建类别并为其指定缩略图。

wp\\U insert\\U术语不能用于我所问的问题,我想知道人类是否还有其他已知的方法。

我已经看到了关于社区的另一个问题,但当你实际使用它时,它似乎不起作用。我不知道为什么它被标记为正确。

1 个回复
SO网友:Ben HartLenn

wp_insert_term() 对这类事情很管用。

您没有给出任何上下文,但这里有一个我制作的快速示例,在每次页面加载时,都会从MY 媒体库(更改$existing_image_ids 到您自己的ID,以使其工作)。

// page load creates a random product category, and an associated image
add_action( \'init\', \'rand_product_cat_w_rand_image\' );
function rand_product_cat_w_rand_image() {

    $test_product_cats = [
        \'Test Category 1\',
        \'Test Category 2\',
        \'Test Category 3\',
        \'Test Category 4\',
        \'Test Category 5\'
    ];

    $existing_image_ids = [
        \'144\',
        \'143\',
        \'142\',
        \'141\',
        \'140\'
    ];

    $rand_cat = rand( 0, 4 );
    $rand_img = rand( 0, 4 );

    $new_cat_title = $test_product_cats[$rand_cat]; // title of product category
    $new_img_id = $existing_image_ids[$rand_img]; // id of image you want to use from your media library

    $new_cat_added = wp_insert_term( $new_cat_title, \'product_cat\' ); // \'product_cat\' is woocommerce product category taxonomy, and were adding a new category with title

    if(is_wp_error( $new_cat_added )) {
        return; // there was an error adding new product category, usually because it already exists with only 5 available test categories
    }
    else {
        add_term_meta( $new_cat_added[\'term_id\'], \'thumbnail_id\', $new_img_id, true ); // add image to new product category, etc.
    }    
}

// This bit is just copied from WooCommerce docs for showing product category image:
// REF: https://docs.woocommerce.com/document/woocommerce-display-category-image-on-category-archive/
add_action( \'woocommerce_archive_description\', \'woocommerce_category_image\', 2 );
function woocommerce_category_image() {
    if ( is_product_category() ){
        global $wp_query;
        $cat = $wp_query->get_queried_object();
        $thumbnail_id = get_woocommerce_term_meta( $cat->term_id, \'thumbnail_id\', true );
        $image = wp_get_attachment_url( $thumbnail_id );
        if ( $image ) {
            echo \'<img src="\' . $image . \'" alt="\' . $cat->name . \'" />\';
        }
    }
}
已测试并正常工作。

结束

相关推荐