[英]Woocommerce: How to use get_term_by in functions.php : Lookup Product Category ID
When I run the standard Woocommerce Product Import当我运行标准的 Woocommerce 产品导入时
My Category Name: Not for Web Sale我的类别名称:非网络销售
My Category Slug: not_for_web_sale我的类别 Slug: not_for_web_sale
So I am calling this in functions.php所以我在functions.php中调用它
if($cat_term_object = get_term_by('slug','not_for_web_sale','product_cat')) {
$cat_term_id = $cat_term_object->term_id;
}
PROBLEM问题
I am not getting any return value我没有得到任何返回值
WHAT I HAVE FOUND我发现了什么
This post tells me that:这篇文章告诉我:
This is probably happening because the taxonomy you're trying to query is registered yet.
这可能是因为您尝试查询的分类法尚未注册。 Eg.
例如。 The WordPress environment is loaded when a theme's functions.php file loads, but many plugins/themes/core functions don't register taxonomies until later.
WordPress 环境在主题的functions.php 文件加载时加载,但许多插件/主题/核心功能直到稍后才注册分类法。
And it suggests:它表明:
Try hooking into init with a really high priority number and running the get_term_by function.
尝试使用非常高的优先级编号挂接到 init 并运行 get_term_by 函数。 Like so:
像这样:
<?php
add_action( 'init', 'wpse27111_tester', 999 );
function wpse27111_tester()
{
$term = get_term_by('slug', 'some-term', 'some-taxonomy');
var_dump($term);
}
WHERE I AM STUCK我被困在哪里
Although I basically understand the explanation of the problem wrt the Woocommerce taxonomy ... ... I am not grasping how to apply that to my needs.虽然我基本上理解了 Woocommerce 分类法对问题的解释……我不明白如何将其应用于我的需求。
Advice or guidance would be most welcome.建议或指导将是最受欢迎的。
( Unfortunately my rep on that particular stackexchange is too low to comment ) (不幸的是,我在该特定 stackexchange 上的代表太低,无法发表评论)
Solved.解决了。
So what I needed to do in functions.php was所以我需要在functions.php中做的是
add_action( 'init', 'get_not_for_sale_category_id', 10 );
function get_not_for_sale_category_id() {
if ( $cat_term_object = get_term_by('slug','not_for_web_sale','product_cat') ) {
$cat_term_id_value = $cat_term_object->term_id;
} else {
$cat_term_id_value = 1010101;
}
return $cat_term_id_value;
Then in my import function, I call like this然后在我的导入函数中,我这样调用
$cat_term_id = get_not_for_sale_category_id();
EDIT编辑
I've hooked it into a more appropriate place.我已经把它挂到了一个更合适的地方。
add_action( 'woocommerce_product_import_before_import', 'get_not_for_sale_category_id', 10 );
It's only called now on Import by an admin and not every page load by every user.它现在只在导入时由管理员调用,而不是每个用户加载的每个页面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.