I have got the following code in a javascript(jquery) file called custom.js:
blabla = new Date(2014, 06 - 1, 2);
$('.days').countdown({
until: blabla,
layout: '{dn} {dl}',
1.Now i want a user to be able to change the above date. I have created a theme options page called theme-options.php
2.I am using <?php require_once('theme-options.php'); ?>
in the functions.php to link to theme-options.php.
3.This is theme-options.php:
<?php
add_action('admin_menu', 'director_create_menu');
function director_create_menu() {
add_submenu_page( 'themes.php', ' Theme Options',
'Theme Options', 'administrator', __FILE__,
'director_settings_page');
add_action( 'admin_init', 'director_register_settings' );
}
function director_register_settings() {
register_setting( 'director-settings-group', 'director_date' );
}
div class="wrap">
<h2>Theme Settings</h2>
<form id="landingOptions" method="post" action="options.php">
<?php settings_fields( 'director-settings-group' ); ?>
<table class="form-table">
<tr valign="top">
<th scope="row">Date:</th>
<td>
<input type="text" placeholder="2014, 06 - 1, 2" name="director_date"
value="<?php print get_option('director_date');
?>" />
</td>
</tr>
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
</p>
</form>
</div>
<?php } ?>
Basically what is happening is that there is a theme options page.A user gives a date inside it. Now i want to use that date inside the javascript file.
If I had to use it inside index.php it would’ve been
<?php $date = get_option('director_date'); ?>
<?php if( $date ) : ?> <?php echo $date; ?><?php endif; ?>);
. However this is javascript. How do i implement such an action here?
An alternative path but still doesn’t work.Rename custom.js to custom.php and add:
gapinvite = new Date(<?php $date = get_option('director_date'); ?>
<?php if( $date ) : ?> <?php echo $date; ?><?php endif; ?>);
$('.days').countdown({
until: gapinvite,
layout: '{dn} {dl}',
And in functions.php:
<?php require_once('js/custom.php'); ?>
Take a look at
wp_localize_script
. Although ostensibly for translation, it lets you pass PHP values to JS. Here’s a fairly good walkthrough on how to use it.EDIT:
First, ensure that you are loading your JS using
wp_enqueue_script
, as you will need to refer to the handle. In yourfunctions.php
you’d have:wp_localize_script
takes three arguments:wp_enqueue_script
$date
variable we declared earlier, but you can obviously pass whatever you want.Then in
my-script.js
, you’d access this object very simply:In
index.php
, you can do something like:Just make sure you do this before you include the JavaScript where you want to reference the
generated_date
variable you just created.