Reputation: 2506
In post.php page of wp-admin I like to populate a post meta while the page is loading. For that I tried the following
add_action('load-post.php', 'show_buy_ticket_date');
function show_buy_ticket_date() {
$screen = get_current_screen();
if ($screen->post_type === 'ai1ec_event') {
$post_id = filter_input(INPUT_GET, 'post');
$buy_ticket_date_unix_timestamp = get_post_meta($post_id,
'buy_ticket_date', TRUE);
}
}
Here I fetched the post's meta value. But How can I populate it in one of the field in the form once edit page is loaded / before loading.
For e.g. the field looks like this
<input class="ai1ec-date-input ai1ec-form-control datepicker hasDatepicker" name="ai1ec_admin_buy_ticket-date-input" id="ai1ec_admin_buy_ticket-date-input" type="date">
Upvotes: 0
Views: 650
Reputation: 2820
You need to convert the timestamp to a date value suitable for input
taking into account that, provided that the timestamp is in UTC time, you probably want to align it with your current timezone.
Finally, you pass the date value to input
with the value
attribute:
date_default_timezone_set( 'Europe/Helsinki' );
$buy_ticket_date = date( 'Y-n-j', intval( $buy_ticket_date_unix_timestamp ));
<input
class="ai1ec-date-input ai1ec-form-control datepicker hasDatepicker"
name="ai1ec_admin_buy_ticket-date-input"
id="ai1ec_admin_buy_ticket-date-input"
type="date" ,
value="<?php echo $buy_ticket_date; ?>
>
UPDATE:
Given the limitation that input
is in some third-party code, I would update the field via JavaScript:
Pass $buy_ticket_date
with localized JavaScript, PHP:
add_action( 'wp_enqueue_scripts', 'my_scripts' ) );
function my_scripts() {
// ... get $buy_ticket_date_unix_timestamp based on post ID
date_default_timezone_set( 'Europe/Helsinki' );
$buy_ticket_date = date( 'Y-n-j', intval( $buy_ticket_date_unix_timestamp ));
wp_register_script( 'my_script', MY_PLUGIN_URL . 'js/script.js', array( 'jquery' ) );
wp_localize_script( 'my_script', 'buy_ticket_date', $buy_ticket_date );
wp_enqueue_script( 'my_script' );
}
and JavaScript (script.js
):
/*global document, jQuery */
(function ($) {
'use strict';
$(document).ready(function () {
$('#ai1ec_admin_buy_ticket-date-input').val(buy_ticket_date);
});
}(jQuery));
Upvotes: 1