使用JavaScript为WordPress定制器创建自定义控件

时间:2020-05-12 作者:xs-dev

我跟踪了这个link 了解如何在Wordpress中为customizer创建自定义控件。根据他们的文档,我用这个代码做了一个控件

wp.customize.control.add(new wp.customize.DateTimeControl(\'birthdate\', {
        label: \'Birthdate\',
        description: "Someone was born on this day.",
        section: \'my_custom_section\',
        includeTime: false,
        setting: new wp.customize.Value(\'2000-01-02\')
    }));
没关系,但是DateTimeControl 是Wordpress的默认控件。我想制作自己的自定义控件表单PHP。这是我在php中的自定义控件


<?php

/**
 * Customize for textarea, extend the WP customizer
 *
 * @package    WordPress
 * @subpackage Documentation
 * @since      10/16/2012
 */

if ( ! class_exists( \'WP_Customize_Control\' ) )
    return NULL;

class TestControl extends \\WP_Customize_Control {

    /**
     * @access public
     * @var    string
     */
    public $type = \'test-control\';

    /**
     * @access public
     * @var    array
     */
    public $statuses;

    /**
     * Constructor.
     *
     * If $args[\'settings\'] is not defined, use the $id as the setting ID.
     *
     * @since   10/16/2012
     * @uses    WP_Customize_Control::__construct()
     * @param   WP_Customize_Manager $manager
     * @param   string $id
     * @param   array $args
     * @return  void
     */
    public function __construct( $manager, $id, $args = array() ) {

        $this->statuses = array( \'\' => __( \'Default\' ) );
        parent::__construct( $manager, $id, $args );
    }



    public function content_template(){
        ?>
        <div>
        <label>
            <span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
            <textarea class="large-text" cols="20" rows="5" <?php $this->link(); ?>>
                <?php echo esc_textarea( $this->value() ); ?>
            </textarea>
        </label>
        </div>
        <?php
    }



}
基本上,我想从用PHP编写的现有控件中用Javascript在Wordpress Customizer中创建控件。对不起,我的英语不好,希望你明白我的意思。

1 个回复
最合适的回答,由SO网友:Behzad G. 整理而成

添加自定义控件类后,需要注册控件,如下面的代码所示,然后可以通过JS调用控件

function prefix_customize_register( $wp_customize ) {
    $wp_customize->register_control_type( \'TestControl\' );
}
add_action( \'customize_register\', \'prefix_customize_register\' );
然后通过JS,如下所示:

api.control.add(
    new api.Control( \'birthdate\', {
      type: \'test-control\',
      label: \'Birthdate\',
      description: "Someone was born on this day.",
      section: \'my_custom_section\',
      includeTime: false,
      setting: new api.Value(\'2000-01-02\')
    })
);

相关推荐