我不知道为什么get_term() 可以在其他页面上使用,但无法在中使用functions.php. 使用get_term() 在里面functions.php 导致WordPress报告错误分类无效。
我的function.php 它是ajax处理程序,已经为ajax注册
public function load_destination()
{
global $wpdb;
$termId = $_POST[\'termid\'];
$term = get_term($termid,\'package_state\');
$args = array(
\'post_type\' => \'package\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'package_state\',
\'field\' => \'id\',
\'terms\' => $termId
)
)
);
$query = new WP_Query( $args );
$collection=[];
$count =1;
while($query->have_posts()) : $query->the_post();
$collection[\'data\'][] = // i need to set term data here $term;
$count++;
endwhile;
wp_send_json($collection);
}
SO网友:Dave Romsey
听起来你正在使用get_term() 用于自定义分类法。如果您正在使用get_term() 在…内functions.php 在挂钩函数之外,当functions.php 已加载。此时尚未注册自定义分类法,因为这发生在init 钩
您的代码在页面模板内工作,因为WordPress在此时加载了自定义分类法。
如果你想试试$term = get_term( \'2\', \'category\' ); (其中2 是中的有效术语ID)functions.php, 这实际上是可行的,因为WordPress在wp-settings.php (这在加载过程的早期)是出于向后兼容性的原因。WordPress还在上注册默认分类法init, 顺便说一句文档块中对此进行了说明create_initial_taxonomies() 在里面/wp-includes/taxonomy.php.
不管怎样,跑步get_term() 在钩住函数的外部functions.php 不是正确的方法,需要更多的代码来进一步帮助您。