代码之家  ›  专栏  ›  技术社区  ›  Subrata Sarkar

WordPress:无法访问回调函数内的callback\u args键值

  •  0
  • Subrata Sarkar  · 技术社区  · 7 年前

    我正在开发一个简单的基于插件的自定义帖子类型。该职位类型注册良好。现在我想创建一些元框,并通过回调参数传递一些属性值。这就是我尝试的:

    function wpcd_add_dealer_meta_boxes() {
            add_meta_box(
                'dealer_first_name',
                'First Name',
                array($this, 'wpcd_meta_box_first_name_markup'),
                'dealers',
                'normal',
                'default',
                array(
                    'id' => 'first_name',
                    'name' => 'first_name',
                    'type' => 'text',
                    'placeholder' => 'Enter first name',
                    'maxlength' => '30',
                    'spellcheck' => 'true',
                    'autocomplete' => 'off'
                )
            );
        }
    

    这是我的回调函数和一个参数:

    function wpcd_meta_box_first_name_markup($args) {
            $html = '<input ';
            $html.= 'type="' . $args->type . '" ';
            $html.= 'id="' .$args->id . '" ';
            $html.= 'name="' .$args->name . '" ';
            if( isset($args->required) && ($args->required == 'true' || $args->required == '1' ) ) {
                $html.= 'required ';
            }
    
            if( isset($args->placeholder) && $args->placeholder != '' ) {
                $html.= 'placeholder="' . esc_attr( $args->placeholder ) . '" ';
            }
    
            if( isset($args->maxlength) ) {
                $html.= 'maxlength="' . $args->maxlength . '" ';
            }
    
            if( isset($args->spellcheck) && ($args->spellcheck == 'true' ) ) {
                $html.= 'spellcheck="' . $args->spellcheck . '" ';
            }
    
            if( isset($args->autocomplete) && ($args->autocomplete == 'on' ) ) {
                $html.= 'autocomplete="' . $args->autocomplete . '" ';
            }
    
            $html.= '/>';
    
            echo $html;
        }
    

    但我不能得到这样的值 $args->id, $args->name 函数内部的等。准确地说,所有的值都是空的,我没有检查 if(isset(...))

    使用上述代码,我希望输出以下标记:

    <input type="text" id="first_name" name="last_name" required placeholder="Enter firstname" maxlength="30" autocomplete="off" spellcheck="true" />
    

    而实际输出为

    <input type="" id="" name="" />
    

    type , id name 未包装在 if(isset()) 块,以便生成它们(使用空值)和包装在其中的任何内容 if(isset())

    我错过了什么或做错了什么? 任何建议都可以挽救我的生命。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Matt Gibson    7 年前

    如果你检查 documentation for add_meta_box() 仔细看,你会发现:

    ($callback\u args(array)(可选)应设置为 第二 已传递参数 回拨)。

    这个 第一 传递给回调的参数是 WP_Post 对象这个 是您的参数数组。所以,试试:

    function wpcd_meta_box_first_name_markup($post, $args) { ...
    

    然后按预期访问您的论点:

    $args['type']