【问题标题】:Woocommerce create_product_cat hook has no thumbnail_id / image information attached for product categoriesWoocommerce create_product_cat 钩子没有附加产品类别的 thumbnail_id / 图像信息
【发布时间】:2022-01-04 15:13:26
【问题描述】:

我已经编写了代码来挂钩在 Woocommerce 上创建一个类别。这段代码让我得到了除“displayType”和“thumbnail_id”之外的所有信息。当连接到“edited_product_cat”时,这些字段会出现。

我的问题是,是否有一种方法/代码也可以在创建时获取 thumbnail_id,或者是否有不同的钩子可以实现这一点?

当前代码如下所示:

function loader() {
        add_action('create_product_cat', [$this, 'onCategoryCreated'], 10, 2);
        add_action('edited_product_cat', [$this, 'onCategoryCreated'], 10, 2);
}

function onCategoryCreated ($categoryId){
        $cat = get_term_by( 'id', $categoryId, 'product_cat', 'ARRAY_A' );
        $catMeta = get_term_meta( $cat["term_id"] );
        $thumbnailId = get_term_meta( $cat["term_id"], 'thumbnail_id', true );
        $imageUrl = wp_get_attachment_url( $thumbnailId );

        error_log(json_encode($cat));
        error_log(json_encode($catMeta));
        error_log($thumbnailId);
        error_log($imageUrl);
}

为创建打印出以下内容:

-> {"term_id":52,"name":"create","slug":"create","term_group":0,"term_taxonomy_id":52,"taxonomy":"product_cat","description":"create desc","parent":0,"count":0,"filter":"raw"} 
-> {"order":["0"]}
-> 
-> 

以及以下更新:

-> {"term_id":35,"name":"update","slug":"update","term_group":0,"term_taxonomy_id":35,"taxonomy":"product_cat","description":"update desc","parent":0,"count":0,"filter":"raw"}
-> {"order":["0"],"display_type":[""],"thumbnail_id":["7"]}
-> 7
-> http://localhost:8888/myWebsite/wp-content/uploads/2021/11/6ac25e82-9d4c-3f59-ad83-a06f7966a0fd.jpg

【问题讨论】:

  • 使用 created_product_cat 代替 create_product_cat :)

标签: php wordpress woocommerce hook categories


【解决方案1】:

使用 created_product_cat 代替 create_product_cat

function loader() {
        add_action('created_product_cat', [$this, 'onCategoryCreated'], 10, 2);
        add_action('edited_product_cat', [$this, 'onCategoryCreated'], 10, 2);
}

function onCategoryCreated ($categoryId){
        $cat = get_term_by( 'id', $categoryId, 'product_cat', 'ARRAY_A' );
        $catMeta = get_term_meta( $cat["term_id"] );
        $thumbnailId = get_term_meta( $cat["term_id"], 'thumbnail_id', true );
        $imageUrl = wp_get_attachment_url( $thumbnailId );

        error_log(json_encode($cat));
        error_log(json_encode($catMeta));
        error_log($thumbnailId);
        error_log($imageUrl);
}

【讨论】:

  • 这确实解决了它,愚蠢的错误。谢谢!
猜你喜欢
  • 2019-11-15
  • 2018-10-17
  • 1970-01-01
  • 2019-12-13
  • 1970-01-01
  • 2015-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多