[英]WordPress get_terms() function not display custom taxonomy categories for woocommerce
[英]WordPress: Why Can't get_terms() See Custom Taxonomy Registered inside Class?
我在类中注册了自定义帖子类型和自定义分类法。 在WP管理员内部,我既看到了职位类型,又看到了分类法。
class Custom_Post_Type {
function __construct($init_data) {
if ( is_admin() ) {
add_action( 'init', array( $this, 'create_ctp' ) );
add_action( 'admin_head', array( $this, 'create_ctp_icons' ) );
add_action( 'save_post', array( $this, 'save_ctp_custom_metadata' ), 1, 2 );
}
}
function create_ctp_taxonomy() {
register_taxonomy(
$post_type.'_type',
$post_type,
array(
'labels' => array(
'name' => $taxonomy_label,
'add_new_item' => 'Add New '.$taxonomy_label
),
'public' => true,
'show_ui' => true,
'show_tagcloud' => true,
'hierarchical' => true,
'show_in_nav_menus' => true,
'show_admin_column' => true
)
);
register_post_type($post_type_slug,
array(
'labels' => array(),
'public' => true,
'has_archive' => false,
'supports' => $this->supports,
'register_meta_box_cb' => array( $this, 'create_ctp_custom_metaboxes' ),
'taxonomies' => array( $taxonomy_slug ),
)
);
}
}
同样,这在管理区域内有效。 我可以添加帖子,也可以看到分类法并添加条款。
在前端, get_taxonomies()
没有看到新的自定义分类法,而get_terms()
没有看到其中的术语。
我尝试了register_taxonomy
几个示例,当我在类之外使用它时,它出现在前端。 但是,当我将示例移到内部create_ctp_taxonomy函数中时,它们对于get_taxonomies
突然不可见。
任何想法为什么会这样?
我一直在玩各种不同的事情,我认为这里的问题是init
动作的时机。 当我从__construct
函数调用安装函数方向时,而不是添加操作,事情就开始起作用了。 例:
class Custom_Post_Type {
function __construct($init_data) {
if ( is_admin() ) {
//add_action( 'init', array( $this, 'create_ctp' ) );
add_action( 'admin_head', array( $this, 'create_ctp_icons' ) );
add_action( 'save_post', array( $this, 'save_ctp_custom_metadata' ), 1, 2 );
}
$this->create_cpt();
}
}
通过这样做,我完全跳过了使用init
的过程。 但是,这似乎违反了标准做法。 任何人都知道这样做有不利之处吗?
将分类法注册到自定义帖子类型时,需要注意几件事。
register_post_type
函数的taxonomies参数将分类法注册为帖子类型。 例如。
register_post_type('cpt_name',array(
'taxonomies'=>array(
'taxomony_name1',
'taxomony_name2')
,other_arguments...)
);
来自文档
注册帖子类型时,请始终使用taxonomies参数注册您的分类法。 如果不这样做,则在使用诸如parse_query或pre_get_posts之类的过滤器时,分类法和帖子类型将不会被识别为已连接。 这可能会导致意外结果和故障
1.)问题不是比赛条件。
直接从functions.php
运行时,诸如is_admin()
类的条件仍然有效。 这与网络上的某些信息相矛盾,但是从WordPress 4.4开始,这些信息确实起作用。
2.)从add_action()
而不是直接从__construct()
调用注册
直接切换到调用注册的更改为零。 需要明确的是,两者之间没有区别:
$this->create_ctp()
add_action('init', array( $this, 'create_ctp' ) );
3.)分类法与CTP的注册顺序
当我将分类法注册移到CTP之前时,其行为更改为零。
我正在使用is_admin()
的条件检查,这是我在添加admin破折号时先前添加的要包装的内容。 这就是为什么我的CTP出现在后端而不是前端的原因。
我已经从简化的示例中删除了它,因此无法通过查看我发布的代码来分辨。
因此,我要做的就是删除is_admin()
检查。 事实证明这是一个愚蠢的错误,但对于查找实际上不是问题的信息很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.