You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Elementor自定义小部件自动加载Opera自定义文章类型分类列表

自动加载Elementor小部件中CPT的分类列表

不需要用JavaScript,直接在PHP注册小部件控制时,通过WordPress原生函数动态获取分类列表即可,新增分类后无需修改代码,刷新编辑器就能自动同步。

实现步骤及代码示例:

  1. 使用get_terms()函数获取与CPT「opera」关联的分类数据
  2. 将分类数据转换为Elementor选择控件需要的选项格式
  3. 替换原手动编写的options数组

完整代码如下:

// 在小部件的_register_controls()方法中添加以下代码
public function _register_controls() {
    // 先调用父类方法
    parent::_register_controls();

    // 获取关联分类列表,替换taxonomy参数为你的分类法slug
    // 若CPT关联默认分类,则taxonomy填'category';若为自定义分类法,填对应slug(比如'opera_category')
    $opera_categories = get_terms( [
        'taxonomy' => 'opera_category',
        'hide_empty' => false, // 是否隐藏无文章的分类,按需调整
        'orderby' => 'name', // 按分类名称排序
        'order' => 'ASC',
    ] );

    // 构建选择控件的选项数组,默认添加「全部分类」选项
    $category_options = [ '' => __( 'All Categories', 'mydomain' ) ];
    if ( ! empty( $opera_categories ) && ! is_wp_error( $opera_categories ) ) {
        foreach ( $opera_categories as $category ) {
            $category_options[ $category->term_id ] = $category->name;
        }
    }

    // 添加分类选择控件
    $this->add_control(
        'opera_category',
        [
            'label' => __( 'Opera category', 'mydomain' ),
            'type' => \Elementor\Controls_Manager::SELECT,
            'options' => $category_options,
            'default' => '',
        ]
    );
}

关键说明:

  • 分类法slug确认:如果你的CPT「opera」关联的是自定义分类法,需确认注册分类法时的slug参数,替换代码中的taxonomy值。比如注册自定义分类法的代码是register_taxonomy( 'opera_category', 'opera', $args ),则taxonomy填'opera_category'。
  • 空分类控制:hide_empty设为true时,仅显示包含文章的分类;设为false则显示所有分类。
  • 排序设置:通过orderby和order参数可以调整分类显示的顺序,默认按名称升序排列。

这样每次新增或删除分类,Elementor编辑器中的选择列表都会自动更新,无需手动修改小部件代码。

内容的提问来源于stack exchange,提问作者Simone Conti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 16:10:24