0

I have created Dynamic Add/Remove Custom Fields (Repeater Fields) in my custom Post types. It is working perfectly. I want to add a new JQuery Date Picker field. I tried hard to create code and also searched the web but found no luck.

Plz Help me.

Following is my code.

function project_rewards_select_options() {
    $options = array (
        'Option 1' => 'Option 1',
        'Option 2' => 'Option 2',
        'Option 3' => 'Option 3',
    );

    return $options;
}

function project_reward_callback( $post ) {
    wp_nonce_field( 'project_reward_nonce', 'project_reward_nonce' );
    $reward_value = get_post_meta( get_the_ID(), '_project_rewards', true );
    $options = project_rewards_select_options();

?>

    <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>

    <table id="repeatable-fieldset-one" width="100%">

    <thead>
        <tr>
            <th width="15%">Reward Amount</th>
            <th width="25%">Reward Title</th>
            <th width="10%">Shipping</th>       
            <th width="45%">Reward Description</th>
            <th width="5%"></th>                    
        </tr>
    </thead>

    <tbody>

<?php

    ( $reward_value );

    foreach ( $reward_value as $field ) {

?>

    <tr>
        <td><input type="text" class="widefat" name="reward[]" value="<?php if ( isset ( $field['reward'] ) ) echo esc_attr( $field['reward'] ); ?>" pattern="[1-9]\d*" /></td>

        <td><input type="text" class="widefat" name="reward_title[]" value="<?php if ( isset ( $field['reward_title'] ) ) echo esc_attr( $field['reward_title'] ); ?>" /></td>

        <td>
            <select class="widefat" name="reward_shipping[]">
            <?php foreach ( $options as $label => $value ) : ?>
            <option value="<?php echo $value; ?>"<?php selected( $field['reward_shipping'], $value ); ?>><?php echo $label; ?></option>
            <?php endforeach; ?>
            </select>
        </td>

        <td><textarea class="widefat" name="reward_description[]"><?php if ( isset ( $field['reward_description'] ) ) echo esc_attr( $field['reward_description'] ); ?></textarea></td>

        <td><input type="image" class="remove-row" src="<?php bloginfo('template_directory'); ?>/assets/images/remove-icon.png" alt="Submit"  width="35" height="35"></td>
    </tr>

<?php } ?>

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

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

        <td>
            <select class="widefat" name="reward_shipping[]">
            <?php foreach ( $options as $label => $value ) : ?>
            <option value="<?php echo $value; ?>"><?php echo $label; ?></option>
            <?php endforeach; ?>
            </select>
        </td>   

        <td><textarea class="widefat" name="reward_description[]" ></textarea></td>

        <td><input type="image" class="remove-row" src="<?php bloginfo('template_directory'); ?>/assets/images/remove-icon.png" alt="Submit"  width="35" height="35"></td>
    </tr>

    </tbody>

    </table>

    <p><a id="add-row" class="button" href="#">Add Reward</a></p>

<?php   

}

function save_project_reward( $post_id ) {

    // Check if our nonce is set.
    if ( ! isset( $_POST['project_reward_nonce'] ) ) {
        return;
    }

    // Verify that the nonce is valid.
    if ( ! wp_verify_nonce( $_POST['project_reward_nonce'], 'project_reward_nonce' ) ) {
        return;
    }

    // If this is an autosave, our form has not been submitted, so we don't want to do anything.
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }

    // Check the user's permissions.
    if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {

        if ( ! current_user_can( 'edit_page', $post_id ) ) {
            return;
        }

    }
    else {

        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }
    }

    $reward_data = array();
    $options = project_rewards_select_options();

    $rewards = $_POST['reward'];
    $reward_titles = $_POST['reward_title'];
    $reward_shippings = $_POST['reward_shipping'];
    $reward_descriptions = $_POST['reward_description'];

    $count = count( $rewards );
    for ( $i = 0; $i < $count; $i++ ) {

        if ( $rewards[$i] != '' ) :
            $reward_data[$i]['reward'] = stripslashes( strip_tags( $rewards[$i] ) );

        if ( in_array( $reward_shippings[$i], $options ) )
            $reward_data[$i]['reward_shipping'] = stripslashes( strip_tags( $reward_shippings[$i] ) );
                else
            $reward_data[$i]['reward_shipping'] = '';
endif;

        if ( $reward_titles[$i] != '' ) :
            $reward_data[$i]['reward_title'] = stripslashes( strip_tags( $reward_titles[$i] ) );
endif;

        if ( $reward_descriptions[$i] != '' ) :
            $reward_data[$i]['reward_description'] = stripslashes( $reward_descriptions[$i] );
endif;              

    }

    update_post_meta( $post_id, '_project_rewards', $reward_data );

}

add_action( 'save_post', 'save_project_reward' ); 
  • Why are you trying to add your own JQuery Date Picker if ACF already has this field? – Cesar Henrique Damascena Jul 6 '17 at 14:47
  • I don't want to use ACF – Minu Jul 6 '17 at 15:05
  • Oh Sorry my bad, I understood that you were using it – Cesar Henrique Damascena Jul 6 '17 at 15:23
1

Wordpress has the jQuery datepicker already included. So you can enqueue the default WP script. However, as far as I know, WP doesnt include the necessary styling for the datepicker!
So try to enqueue the WP script, and for example, styles from external source:

function my_datepicker_enqueue() {
            wp_enqueue_script( 'jquery-ui-datepicker' ); // enqueue datepicker from WP
            wp_enqueue_style( 'jquery-ui-style', '//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/base/jquery-ui.css', true);
}
add_action( 'admin_enqueue_scripts', 'my_datepicker_enqueue' );

Create a new HTML input field with atleast with a class and a name. HTML of the input field: (you already have some input fields defined, so jump to the script)

<input type="text" name="_custom_datepicker[]" id="_custom_datepicker[]" class="my-custom-datepicker-field" value="<?php echo $your_saved_value; ?>" />

Than add a script to init the datepicker for our new element. Script: (make sure that you target the right input element, we are looking at the defined class here, cause we want to use multiple instances.)

jQuery(document).ready(function($){
    $('.my-custom-datepicker-field').datepicker({
        dateFormat: 'dd-mm-yy', //maybe you want something like this
        showButtonPanel: true
    });
});

Update:
I had some problems reading your code at first, and you also have several errors in your code. First I could see the same strange behaviour. I have now setup a testplugin on a dev site, and there it is now working.

1: You set up your save function so that you cannot just enter a date and save. You will have to either add a amount, title or description also, to be able to save. I think this is intended by you?

2: In the save function you have the following code:

if ( $reward_descriptions[$i] != '' ) :
    $reward_data[$i]['reward_date'] = stripslashes( $reward_dates[$i] );
endif;

So only when the description field is not empty the date will get saved?! Seems this was a typo because the other fields look good. Change to:

if ( $reward_data[$i] != '' ) :
    $reward_data[$i]['reward_date'] = stripslashes( $reward_dates[$i] );
endif;

3: In your callback code you have these fields as datepicker fields:

<td><input type="text" name="_custom_datepicker[]" id="_custom_datepicker[]" class="my-custom-datepicker-field" value="<?php echo esc_attr( $field['reward_date'] ); ?>" /></td>

and

<td><input type="text" class="my-custom-datepicker-field" name="_custom_datepicker[]" /></td>

Both named _custom_datepicker[]. But in your save function you try to save fields called reward_date instead.

Also the id should be unique. But you add the same id to all datefields. You could just remove the id from these fields, its not needed anyway.

4. If you add fields dynamically like you want to, you need to change the datepicker JS function. And instead of loading the JS code inline (and multiple times like you did), I recommend enqueuing one JS file. So try to replace your JS code with something like this:

jQuery(document).ready(function($){

    // your default code
    $( '#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;
    });

    //changed to be used on dynamic field which gets added and removed from DOM
    //if the element with the class .my-custom-datepicker-field gets focus, add datepicker
    $(document).on('focus', '.my-custom-datepicker-field', function(){
        $(this).datepicker({
            dateFormat: 'dd-mm-yy', //maybe you want something like this
            showButtonPanel: true
        });
    });

});

After I fixed these things and enqueued the JS file with the code like WordPress wants it to, it is now working.

-1

@LWS-Mo, Thanks for helping. I have added the codes accordingly but the datepicker is working weirdly. The date selected in first field get reflected in subsiquent field. Not working properly.

Plz tell me where I am getting wrong. Following is the code.

function project_rewards_select_options() {
    $options = array (
        'Option 1' => 'Option 1',
        'Option 2' => 'Option 2',
        'Option 3' => 'Option 3',
    );

    return $options;
}

function crazicle_project_reward_callback( $post ) {
    wp_nonce_field( 'project_reward_nonce', 'project_reward_nonce' );
    $reward_value = get_post_meta( get_the_ID(), '_project_rewards', true );
    $options = project_rewards_select_options();

?>

    <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>

    <table id="repeatable-fieldset-one" width="100%">

    <thead>
        <tr>
            <th width="15%">Reward Amount</th>
            <th width="25%">Reward Title</th>
            <th width="10%">Shipping</th>
            <th width="20%">date</th>                  
            <th width="25%">Reward Description</th>
            <th width="5%"></th>                    
        </tr>
    </thead>

    <tbody>

<?php

    ( $reward_value );

    foreach ( $reward_value as $field ) {

?>

    <tr>
        <td><input type="text" class="widefat" name="reward[]" value="<?php if ( isset ( $field['reward'] ) ) echo esc_attr( $field['reward'] ); ?>" pattern="[1-9]\d*" /></td>

        <td><input type="text" class="widefat" name="reward_title[]" value="<?php if ( isset ( $field['reward_title'] ) ) echo esc_attr( $field['reward_title'] ); ?>" /></td>

        <td>
            <select class="widefat" name="reward_shipping[]">
            <?php foreach ( $options as $label => $value ) : ?>
            <option value="<?php echo $value; ?>"<?php selected( $field['reward_shipping'], $value ); ?>><?php echo $label; ?></option>
            <?php endforeach; ?>
            </select>
        </td>

        <script type="text/javascript">
            jQuery(document).ready(function($){
    $('.my-custom-datepicker-field').datepicker({
        dateFormat: 'dd-mm-yy', //maybe you want something like this
        showButtonPanel: true
    });
});
        </script>

        <td><input type="text" name="_custom_datepicker[]" id="_custom_datepicker[]" class="my-custom-datepicker-field" value="<?php echo esc_attr( $field['reward_date'] ); ?>" /></td>

        <td><textarea class="widefat" name="reward_description[]"><?php if ( isset ( $field['reward_description'] ) ) echo esc_attr( $field['reward_description'] ); ?></textarea></td>

        <td><input type="image" class="remove-row" src="<?php bloginfo('template_directory'); ?>/assets/images/remove-icon.png" alt="Submit"  width="35" height="35"></td>
    </tr>

<?php } ?>

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

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

        <td>
            <select class="widefat" name="reward_shipping[]">
            <?php foreach ( $options as $label => $value ) : ?>
            <option value="<?php echo $value; ?>"><?php echo $label; ?></option>
            <?php endforeach; ?>
            </select>
        </td>

        <script type="text/javascript">
            jQuery(document).ready(function($){
    $('.my-custom-datepicker-field').datepicker({
        dateFormat: 'dd-mm-yy', //maybe you want something like this
        showButtonPanel: true
    });
});
        </script>        

        <td><input type="text" class="my-custom-datepicker-field" name="_custom_datepicker[]" /></td>          

        <td><textarea class="widefat" name="reward_description[]" ></textarea></td>

        <td><input type="image" class="remove-row" src="<?php bloginfo('template_directory'); ?>/assets/images/remove-icon.png" alt="Submit"  width="35" height="35"></td>
    </tr>

    </tbody>

    </table>

    <p><a id="add-row" class="button" href="#">Add Reward</a></p>

<?php   

}

function save_project_reward( $post_id ) {

    // Check if our nonce is set.
    if ( ! isset( $_POST['project_reward_nonce'] ) ) {
        return;
    }

    // Verify that the nonce is valid.
    if ( ! wp_verify_nonce( $_POST['project_reward_nonce'], 'project_reward_nonce' ) ) {
        return;
    }

    // If this is an autosave, our form has not been submitted, so we don't want to do anything.
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }

    // Check the user's permissions.
    if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {

        if ( ! current_user_can( 'edit_page', $post_id ) ) {
            return;
        }

    }
    else {

        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }
    }

    $reward_data = array();
    $options = project_rewards_select_options();

    $rewards = $_POST['reward'];
    $reward_titles = $_POST['reward_title'];
    $reward_shippings = $_POST['reward_shipping'];
    $reward_dates = $_POST['reward_date'];    
    $reward_descriptions = $_POST['reward_description'];

    $count = count( $rewards );
    for ( $i = 0; $i < $count; $i++ ) {

        if ( $rewards[$i] != '' ) :
            $reward_data[$i]['reward'] = stripslashes( strip_tags( $rewards[$i] ) );

        if ( in_array( $reward_shippings[$i], $options ) )
            $reward_data[$i]['reward_shipping'] = stripslashes( strip_tags( $reward_shippings[$i] ) );
                else
            $reward_data[$i]['reward_shipping'] = '';
endif;

        if ( $reward_titles[$i] != '' ) :
            $reward_data[$i]['reward_title'] = stripslashes( strip_tags( $reward_titles[$i] ) );
endif;

        if ( $reward_descriptions[$i] != '' ) :
            $reward_data[$i]['reward_description'] = stripslashes( $reward_descriptions[$i] );
endif;

        if ( $reward_descriptions[$i] != '' ) :
            $reward_data[$i]['reward_date'] = stripslashes( $reward_dates[$i] );
endif;            

    }

    update_post_meta( $post_id, '_project_rewards', $reward_data );

}

add_action( 'save_post', 'save_project_reward' );
  • Sorry, I didnt get notified, I just now saw that you tried to reach me. I will update my answer asap. – LWS-Mo Oct 13 '17 at 14:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.