programing

WordPress 위젯의 동적 입력 필드

powerit 2023. 3. 4. 15:12
반응형

WordPress 위젯의 동적 입력 필드

작업 중인 테마의 커스텀 위젯에 사전 정의된 라벨 세트에 대한 동적 입력 필드를 작성하려고 합니다.나는 다음과 같은 것을 달성하고 싶다.

CourseName           FieldONE             FieldTWO
-------------------------------------------------------------
Chemistry            Sprint 2015          Summer 2015  ( - )
                     Spring 2016          Summer 2016  ( - )
                                                       ( + )
-------------------------------------------------------------
Biology              Sprint 2015          Summer 2015  ( - )
                     Fall 2015            Winter 2015  ( - )
                     Spring 2016          Summer 2016  ( - )
                                                       ( + )
--------------------------------------------------------------
Math                 Fall 2015            Winter 2015  ( - )
                                                       ( + )
--------------------------------------------------------------
Physics              Fall 2015            Winter 2015  ( - )
                                                       ( + )
--------------------------------------------------------------

어디에CourseName화학, 생물학, 수학 및 물리학(사전 정의된 라벨만, 최대 4개)입니다.FieldONE그리고.FieldTWO각 과정에 대해 다른 용어를 입력할 수 있는 동적 입력입니다.

그래서 클릭을 하면( + ), 2개의 필드FieldOne그리고.FieldTWO이 라벨에 대해 작성됩니다.를 클릭하면( - )두 필드가 모두 삭제됩니다.

메타박스와 유사한 동적 입력을 생성하는 이 Gist를 사용하려고 했는데, 지금까지 다음과 같은 결과가 나왔습니다.

<?php
/*
Plugin Name: Dynamic Fields Widget
Description: Dynamic Fields
Version: 0.0
Author: Rain Man
*/
// Creating the widget
class dynamic_widget extends WP_Widget
{
    public function __construct()
    {
        parent::__construct(
          // Base ID of your widget
          'dynamic_widget',

          // Widget name will appear in UI
          __('Dynamic Widget', 'dynamic_widget_domain'),

          // Widget description
          array('description' => __('Sample Dynamic Widget', 'dynamic_widget_domain'))
        );
    }

// widget
public function widget($args, $instance)
{
    $title = apply_filters('widget_title', $instance['title']);
// This is where you run the code and display the output
echo __('Hello, World!', 'dynamic_widget_domain');
    echo $args['after_widget'];
}

// form
public function form($instance)
{
    if (isset($instance[ 'title' ])) {
        $title = $instance[ 'title' ];
    } else {
        $title = __('New title', 'dynamic_widget_domain');
    }
// Widget admin form

    $repeatable_fields = array();
    $courses = array(
      'Chemistry'    => array(
        'coursecode'   => 'Chemistry 2059',
        'professor' => 'Dr. James Bond',
      ),
      'Biology'   => array(
        'coursecode'   => 'Biology 3029',
        'professor' => 'Dr. James Bond',
      ),
      'Math' => array(
        'coursecode'   => 'Math 2043',
        'professor' => 'Dr. James Bond',
      ),
      'Physics'  => array(
        'coursecode'   => 'Physics 2075',
        'professor' => 'Dr. James Bond',
      )
    );
     ?>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<script type="text/javascript">
jQuery(document).ready(function( $ ){
  $( '#add-row' ).on('click', function() {
    var row = $( '.empty-row.screen-reader-text' ).clone(true);
    row.removeClass( 'empty-row screen-reader-text' );
    row.insertBefore( '#repeatable-fieldset-one tbody>tr:last' );
    return false;
  });

  $( '.remove-row' ).on('click', function() {
    $(this).parents('tr').remove();
    return false;
  });
});
</script>
<?php foreach ($courses as $course_key => $course_info) { ?>
<label><?php echo $course_info['coursecode']; ?></label>
<table id="repeatable-fieldset-one" width="100%">
<thead>
  <tr>
    <th width="40%">Fall Term</th>
    <th width="40%">Winter Term</th>
    <th width="8%"></th>
  </tr>
</thead>
<tbody>
<?php

if ($repeatable_fields) :

foreach ($repeatable_fields as $field) {
    ?>
<tr>
  <td><input type="text" class="widefat" name="name[]" value="<?php if ($field['name'] != '') {
    echo esc_attr($field['name']);
} ?>" /></td>

  <td>
  </td>

  <td><input type="text" class="widefat" name="url[]" value="<?php if ($field['url'] != '') {
    echo esc_attr($field['url']);
} else {
    echo '';
} ?>" /></td>

  <td><a class="button remove-row" href="#">Remove</a></td>
  <td><a id="add-row" class="button" href="#">Add</a></td>

</tr>
<?php

} else :
// show a blank one

?>
<tr>
  <td><input type="text" class="widefat" name="name[]" /></td>


  <td><input type="text" class="widefat" name="url[]" value="" /></td>

  <td><a class="button remove-row" href="#">Remove</a></td>
  <td><a id="add-row" class="button" href="#">Add</a></td>

</tr>
<?php endif; ?>
<? } ?>


<!-- empty hidden one for jQuery -->
<tr class="empty-row screen-reader-text">
  <td><input type="text" class="widefat" name="name[]" /></td>

  <td><input type="text" class="widefat" name="url[]" value="" /></td>

  <td><a class="button remove-row" href="#">Remove</a></td>
  <td><a id="add-row" class="button" href="#">Add</a></td>

</tr>
</tbody>
</table>
</p>
<?php

}

// update
public function update($new_instance, $old_instance)
{
    $instance = array();
    $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';

    return $instance;
}
} // Class dynamic_widget ends here

// Register and load the widget
function wpb_load_widget()
{
    register_widget('dynamic_widget');
}
add_action('widgets_init', 'wpb_load_widget');

다음은 스크린샷입니다.

여기에 이미지 설명 입력

현재 많은 문제가 있습니다.먼저 Javascript "Add" 버튼이 작동하지 않고 나중에 액세스하기 위해 데이터를 저장하는 방법을 잘 모르겠습니다.

라벨의 동적 입력 필드를 만드는 방법을 알고 계십니까?제가 공유한 GIST의 코드와 비슷할 필요는 없지만, 수정한 내용을 사용할 수 있으면 좋겠습니다.

이 코드를 사용해 보세요. 테스트해 봤는데 작동해요.위젯에 없는 바닥글에 js코드를 삽입해야 합니다. 그렇지 않으면 클릭버튼이 두 번 실행됩니다.

함수 위젯()에서는 입력값을 표시하는 루프가 표시됩니다.

    <?php
/*
Plugin Name: Dynamic Fields Widget
Description: Dynamic Fields
Version: 0.0
Author: Rain Man
*/
// Creating the widget
class dynamic_widget extends WP_Widget
{
    public $courses;
    public function __construct()
    {
        parent::__construct(
          // Base ID of your widget
          'dynamic_widget',

          // Widget name will appear in UI
          __('Dynamic Widget', 'dynamic_widget_domain'),

          // Widget description
          array('description' => __('Sample Dynamic Widget', 'dynamic_widget_domain'))
        );
        $this->courses = array(
          'Chemistry'    => array(
            'coursecode'   => 'Chemistry 2059',
            'professor' => 'Dr. James Bond',
          ),
          'Biology'   => array(
            'coursecode'   => 'Biology 3029',
            'professor' => 'Dr. James Bond',
          ),
          'Math' => array(
            'coursecode'   => 'Math 2043',
            'professor' => 'Dr. James Bond',
          ),
          'Physics'  => array(
            'coursecode'   => 'Physics 2075',
            'professor' => 'Dr. James Bond',
          )
        );
        add_action( 'in_admin_footer',array( $this,'jsfooter'));
    }
    public function jsfooter() {
    ?>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

    <script type="text/javascript">
    jQuery(document).ready(function( $ ){
        $(document ).off('click').on('click','div.open .add-row' , function() {

        var row = $(this).closest('tr').clone(true);
        row.find('input').each(function(){
            $(this).val("");
        });
        // row.insertBefore( '#repeatable-fieldset-one tbody>tr:last' );
        $(this).parents('tr').after(row);

        return false;
      });

      $( document).on('click',  'div.open .remove-row',function() {
          if ($(this).parents('tbody').find('tr').length >1) {
            $(this).parents('tr').remove(); 
        }
        return false;
      });
    });
    </script>
    <?php
    }

// widget
public function widget($args, $instance)
{
    $title = apply_filters('widget_title', $instance['title']);
// This is where you run the code and display the output
    foreach ($this->courses as $course_key => $course_info) {
        echo $course_info['coursecode'] .'<br>'; 
        foreach ($instance['repeat'][$course_key ]["fall"] as $k=>$field) {
            echo 'Fall Term ' . $field .' / ';
            echo 'Winter Term ' . $instance['repeat'][$course_key ]["winter"][$k] .'<br>';
        }
    }

    echo $args['after_widget'];
}

// form
public function form($instance)
{
    if (isset($instance[ 'title' ])) {
        $title = $instance[ 'title' ];
    } else {
        $title = __('New title', 'dynamic_widget_domain');
    }
// Widget admin form
    $repeatable_fields= isset ( $instance['repeat'] ) ? $instance['repeat'] : array();
     ?>

<?php foreach ($this->courses as $course_key => $course_info) { ?>
<label><?php echo $course_info['coursecode']; ?></label>
<table id="repeatable-fieldset-one" width="100%">
<thead>
  <tr>
    <th width="40%">Fall Term</th>
    <th width="40%">Winter Term</th>
    <th width="8%"></th>
    <th width="8%"></th>
  </tr>
</thead>
<tbody>
<?php

if ($repeatable_fields[$course_key ]["fall"] || $repeatable_fields[$course_key ]["winter"]) :
foreach ($repeatable_fields[$course_key ]["fall"] as $k=>$field) {
    ?>
<tr>
  <td><input type="text" class="widefat" name="<?php echo $this->get_field_name( 'repeat' )?>[<?php echo $course_key;?>][fall][]" value="<?php echo $field; ?>" /></td>

  <td><input type="text" class="widefat" name="<?php echo $this->get_field_name( 'repeat' )?>[<?php echo $course_key;?>][winter][]" value="<?php echo $repeatable_fields[$course_key ]["winter"][$k]; ?>" /></td>

  <td><a class="button remove-row" href="#">Remove</a></td>
  <td><a class="button add-row" class="button" href="#">Add</a></td>

</tr>
<?php
} else :
// show a blank one

?>
<tr>
  <td><input type="text" class="widefat" name="<?php echo $this->get_field_name( 'repeat' )?>[<?php echo $course_key;?>][fall][]" /></td>


  <td><input type="text" class="widefat" name="<?php echo $this->get_field_name( 'repeat' )?>[<?php echo $course_key;?>][winter][]" value="" /></td>

  <td><a class="button remove-row" href="#">Remove</a></td>
  <td><a class="button add-row" class="button" href="#">Add</a></td>

</tr>
<?php endif; ?>
</tbody>
</table>
<?php } ?>


<!-- empty hidden one for jQuery -->

<?php

}

// update
public function update($new_instance, $old_instance)
{
    $instance = array();
    $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
    $instance['repeat'] = array();

    if ( isset ( $new_instance['repeat'] ) )
    {
        foreach ( $new_instance['repeat'] as $k =>$value )
        {
                $instance['repeat'][$k] = $value;
        }
    }

    return $instance;
}
} // Class dynamic_widget ends here

// Register and load the widget
function wpb_load_widget()
{
    register_widget('dynamic_widget');
}
add_action('widgets_init', 'wpb_load_widget');

데이터는 $instance['repeat']에 이와 같은 배열로 저장됩니다(루프를 어떻게 만들었는지를 이해하기 위해).

    array (size=4)
  'Chemistry' => 
    array (size=2)
      'fall' => 
        array (size=1)
          0 => string 'AAA' (length=3)
      'winter' => 
        array (size=1)
          0 => string 'BBBBBBB' (length=7)
  'Biology' => 
    array (size=2)
      'fall' => 
        array (size=2)
          0 => string 'CCCCCC' (length=6)
          1 => string 'EEEEEEE' (length=7)
      'winter' => 
        array (size=2)
          0 => string 'DDDD' (length=4)
          1 => string 'FFFFFFFF' (length=8)
  'Math' => 
    array (size=2)
      'fall' => 
        array (size=1)
          0 => string 'GGGGGGG' (length=7)
      'winter' => 
        array (size=1)
          0 => string 'HHHHHH' (length=6)
  'Physics' => 
    array (size=2)
      'fall' => 
        array (size=1)
          0 => string 'IIIIIIIII' (length=9)
      'winter' => 
        array (size=1)
          0 => string 'JJJJJJJJ' (length=8)

이 플러그인을 커스터마이즈하는 것은 다음 목적에 도움이 될 수 있다고 생각합니다.https://wordpress.org/plugins/advanced-custom-fields-table-field/installation/

갱신되었습니다.

        <?php
        /*
        Plugin Name: Dynamic Fields Widget
        Description: Dynamic Fields
        Version: 0.0
        Author: Rain Man
        */
        // Creating the widget
        class dynamic_widget extends WP_Widget
        {
            public function __construct()
            {
                parent::__construct(
                  'dynamic_widget', __('Dynamic Widget', 'dynamic_widget_domain'),
                  array('description' => __('Sample Dynamic Widget', 'dynamic_widget_domain'))
                );
            }

        // widget
        public function widget($args, $instance)
        {
            $title = apply_filters('widget_title', $instance['title']);
            // This is where you run the code and display the output
            echo __('Hello, World!', 'dynamic_widget_domain');
            echo $args['after_widget'];
        }

        // form
        public function form($instance)
        {
            if (isset($instance[ 'title' ])) {
                $title = $instance[ 'title' ];
            } else {
                $title = __('New title', 'dynamic_widget_domain');
            }
        // Widget admin form

            $repeatable_fields = array();
            $courses = array(
              'Chemistry'    => array(
                'coursecode'   => 'Chemistry 2059',
                'professor' => 'Dr. James Bond',
                'id' => 'test1',
              ),
              'Biology'   => array(
                'coursecode'   => 'Biology 3029',
                'professor' => 'Dr. James Bond',
                    'id' => 'test2',
              ),
              'Math' => array(
                'coursecode'   => 'Math 2043',
                    'id' => 'test3',
              ),
              'Physics'  => array(
                'coursecode'   => 'Physics 2075',
                'id' => 'test4',
              )
            );

        $Inc=1;
        foreach ($courses as $course_key => $course_info) { 
            echo $Inc;
            ?>
        <label><?php echo $course_info['coursecode']; ?></label>
        <table id="repeatable-fieldset-<?php echo $course_info['id']; ?>" width="100%" class="tableclass">
        <thead>
          <tr>
            <th width="40%">Fall Term</th>
            <th width="40%">Winter Term</th>
            <th width="8%"></th>
          </tr>
        </thead>
        <tbody>
        <?php


          if ($repeatable_fields):

                foreach ($repeatable_fields as $field) {        ?>
                    <tr>
                      <td><input type="text" class="widefat" name="name[]" value="<?php if ($field['name'] != '') { echo esc_attr($field['name']);} ?>" /></td>
                      <td></td>
                      <td><input type="text" class="widefat" name="url[]" value="<?php if ($field['url'] != '') {   echo esc_attr($field['url']); } else { echo ''; } ?>" /></td>
                      <td><a class="button remove-row" href="#">Remove</a></td>
                      <td><a id="add-row" class="button addrowbtn" href="#">Add</a></td>
                    </tr>
                <?php   } 

        else:
        // show a blank one

        ?>
        <tr>
          <td><input type="text" class="widefat" name="name[]" /></td>
          <td><input type="text" class="widefat" name="url[]" value="" /></td>
          <td><a class="button remove-row" href="#">Remove</a></td>
          <td><a id="add-row" class="button addrowbtn" href="#">Add</a></td>
        </tr>
        <tr class="tablerowclone">
          <td><input type="text" class="widefat" name="name[]" /></td>
          <td><input type="text" class="widefat" name="url[]" value="" /></td>
          <td><a class="button remove-row" href="#">Remove</a></td>
          <td><a id="add-row" class="button addrowbtn" href="#">Add</a></td>
        </tr>

        <?php endif; } ?>
        <?  $Inc++; } ?>


        </tbody>
        </table>
        <style>
            .tablerowclone{display:none;}
            </style>

        </p>


        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

        <script type="text/javascript">
        jQuery(document).ready(function( $ ){
          jQuery(document).off().on('click',' .addrowbtn', function(event) {
               event.preventDefault();
            var row = jQuery(this).closest(".tableclass").find("tr:last").clone();

            row.removeClass( 'tablerowclone' );
            //row.insertBefore( '#repeatable-fieldset-one tbody>tr:last' );
            row.insertBefore(jQuery(this).closest(".tableclass").find("tbody tr.tablerowclone"));
            return false;
          });

          jQuery(document).on('click', '.remove-row' , function() {
            var RowLenth  = jQuery(this).closest("tbody").children().length;

                if(RowLenth>2){
                    jQuery(this).parents('tr').remove();                        
                }
            return false;
          });
        });
        </script>

        <?php
        }



    public function update($new_instance, $old_instance){
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';

        return $instance;
    }
 } 

function wpb_load_widget()
 {
  register_widget('dynamic_widget');
 }
add_action('widgets_init', 'wpb_load_widget');
        <?php
        /*
        Plugin Name: Dynamic Fields Widget
        Description: Dynamic Fields
        Version: 0.0
        Author: Rain Man
        */
        // Creating the widget
        class dynamic_widget extends WP_Widget
        {
            public function __construct()
            {
                parent::__construct(
                  'dynamic_widget', __('Dynamic Widget', 'dynamic_widget_domain'),
                  array('description' => __('Sample Dynamic Widget', 'dynamic_widget_domain'))
                );
            }

        // widget
        public function widget($args, $instance)
        {
            $title = apply_filters('widget_title', $instance['title']);
            // This is where you run the code and display the output
            echo __('Hello, World!', 'dynamic_widget_domain');
            echo $args['after_widget'];
        }

        // form
        public function form($instance)
        {
            if (isset($instance[ 'title' ])) {
                $title = $instance[ 'title' ];
            } else {
                $title = __('New title', 'dynamic_widget_domain');
            }
        // Widget admin form

            $repeatable_fields = array();
            $courses = array(
              'Chemistry'    => array(
                'coursecode'   => 'Chemistry 2059',
                'professor' => 'Dr. James Bond',
                'id' => 'test1',
              ),
              'Biology'   => array(
                'coursecode'   => 'Biology 3029',
                'professor' => 'Dr. James Bond',
                    'id' => 'test2',
              ),
              'Math' => array(
                'coursecode'   => 'Math 2043',
                    'id' => 'test3',
              ),
              'Physics'  => array(
                'coursecode'   => 'Physics 2075',
                'id' => 'test4',
              )
            );

        $Inc=1;
        foreach ($courses as $course_key => $course_info) { 
            echo $Inc;
            ?>
        <label><?php echo $course_info['coursecode']; ?></label>
        <table id="repeatable-fieldset-<?php echo $course_info['id']; ?>" width="100%" class="tableclass">
        <thead>
          <tr>
            <th width="40%">Fall Term</th>
            <th width="40%">Winter Term</th>
            <th width="8%"></th>
          </tr>
        </thead>
        <tbody>
        <?php


          if ($repeatable_fields):

                foreach ($repeatable_fields as $field) {        ?>
                    <tr>
                      <td><input type="text" class="widefat" name="name[]" value="<?php if ($field['name'] != '') { echo esc_attr($field['name']);} ?>" /></td>
                      <td></td>
                      <td><input type="text" class="widefat" name="url[]" value="<?php if ($field['url'] != '') {   echo esc_attr($field['url']); } else { echo ''; } ?>" /></td>
                      <td><a class="button remove-row" href="#">Remove</a></td>
                      <td><a id="add-row" class="button addrowbtn" href="#">Add</a></td>
                    </tr>
                <?php   } 

        else:
        // show a blank one

        ?>
        <tr>
          <td><input type="text" class="widefat" name="name[]" /></td>
          <td><input type="text" class="widefat" name="url[]" value="" /></td>
          <td><a class="button remove-row" href="#">Remove</a></td>
          <td><a id="add-row" class="button addrowbtn" href="#">Add</a></td>
        </tr>
        <tr class="tablerowclone">
          <td><input type="text" class="widefat" name="name[]" /></td>
          <td><input type="text" class="widefat" name="url[]" value="" /></td>
          <td><a class="button remove-row" href="#">Remove</a></td>
          <td><a id="add-row" class="button addrowbtn" href="#">Add</a></td>
        </tr>

        <?php endif; } ?>
        <?  $Inc++; } ?>


        </tbody>
        </table>
        <style>
            .tablerowclone{display:none;}
            </style>

        </p>


        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

        <script type="text/javascript">
        jQuery(document).ready(function( $ ){
          jQuery(document).off().on('click',' .addrowbtn', function(event) {
               event.preventDefault();
            var row = jQuery(this).closest(".tableclass").find("tr:last").clone();

            row.removeClass( 'tablerowclone' );
            //row.insertBefore( '#repeatable-fieldset-one tbody>tr:last' );
            row.insertBefore(jQuery(this).closest(".tableclass").find("tbody tr.tablerowclone"));
            return false;
          });

          jQuery(document).on('click', '.remove-row' , function() {
            var RowLenth  = jQuery(this).closest("tbody").children().length;

                if(RowLenth>2){
                    jQuery(this).parents('tr').remove();                        
                }
            return false;
          });
        });
        </script>

        <?php
        }



    public function update($new_instance, $old_instance){
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';

        return $instance;
    }
 } 

function wpb_load_widget()
 {
  register_widget('dynamic_widget');
 }
add_action('widgets_init', 'wpb_load_widget');

갱신필

정상적으로 동작하고 있는 것 같습니다.

제가 개인적으로 접한 주요 문제는 를 사용할 수 없다는 것입니다.$this->get_field_name( '{{field}}' )js를 사용하여 행을 동적으로 작성할 때.이 문제에 대한 나의 해결책은 다음과 같습니다.

function getFieldName(field){
    var pattern = '<?=$this->get_field_name( "{{field}}" )?>';
    return pattern.replace('{{field}}', field);
}

이게 네 질문이 아니란 건 알지만 그래도 도움이 될 수 있을 거야

언급URL : https://stackoverflow.com/questions/41091561/dynamic-input-fields-in-wordpress-widgets

반응형