I am trying to include a plugin from github (https://github.com/rendro/countdown) the right way on my wordpress site. After hours of research in the codex and here on stack I still cannot find a way to make it work.
If I use the default method:
1) Adding these lines to the <head> of my header.php file:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="/path/to/jquery.countdown.js"></script>
2) Initializing the plugin with my desired configuration in between </head> and <body> in my header.php file, in this case:
<script>
$(function() {
var endDate = "November 30, 2015 10:00:00";
$('.countdown.styled').countdown({
date: endDate,
render: function(data) {
$(this.el).html("<div>" + this.leadingZeros(data.days, 2) + " <span>days</span></div><div>" + this.leadingZeros(data.hours, 2) + " <span>hours</span></div><div>" + this.leadingZeros(data.min, 2) + " <span>minutes</span></div><div>" + this.leadingZeros(data.sec, 2) + " <span>seconds</span></div>");
}
});
});
</script>
3) And then calling the plugin in my html file:
<?php if(is_front_page() ) { ?>
<div id="cdtoevent" class="countcont">
<div class="countdown styled"></div>
</div>
<?php } ?>
It works perfectly !
If, however, I try doing it the right way
(If I understand well, wordpress ships with jQuery by default, by using the default method I'm making the user download jquery twice which augments my loading time as well, right ?)
Which means enqueuing jquery and then my script in my functions.php file like so:
wp_enqueue_script('jquery');
function add_cdtoevent() {
wp_enqueue_script('countdown', get_template_directory_uri() . 'countdown.js', array('jquery'), true );
}
add_action( 'wp_enqueue_scripts', 'add_cdtoevent' );
And then repeat step 2) and 3) of the default method, it simply does not work ! I tried wrapping my jquery code in step 2) just like this:
jQuery(document).ready(function( $ ) {
// $ Works! You can test it with next line if you like
// console.log($);
});
But it still does not work.
If anybody could help, it would truly be greatly appreciated !
What I currently have in my header.php:
<?php if(is_front_page() ) { ?>
<div id="cdtoevent" class="countcont">
<div class="countdown styled"></div>
</div>
<?php } ?>
What I currently have in my footer.php:
<script type="text/javascript">
$(function() {
var endDate = "November 14, 2015 10:00:00";
$('.countdown.styled').countdown({
date: endDate,
render: function(data) {
$(this.el).html("<div>" + this.leadingZeros(data.days, 2) + " <span>days</span></div><div>" + this.leadingZeros(data.hours, 2) + " <span>hours</span></div><div>" + this.leadingZeros(data.min, 2) + " <span>minutes</span></div><div>" + this.leadingZeros(data.sec, 2) + " <span>seconds</span></div>");
}
});
});
</script>
What I currently have in my functions.php :
// Loads JavaScript file with functionality specific to LCQC.
wp_enqueue_script('jquery');
function add_cdtoevent() {
wp_enqueue_script('countdown', get_template_directory_uri() . 'countdown.js', array('jquery'), true );
}
add_action( 'wp_enqueue_scripts', 'add_cdtoevent' );
The jquery plugin (.js)
It's a good idea to use a function to enqueue your script. However: where do you call this function? You need to call it to enqueue your script. The best way to do this is by attach it to the right action (wp_enqueue_scripts): add_action('wp_enqueue_scripts', 'add_cdtoevent');.
I wrote a guide about including scripts in WordPress if you want more information about this function. It's useful to know how it works, as you can then discover that enqueuing jQuery manually is useless: you indicated that it's a dependency, so WordPress will automatically add it if needed.
I finally got it to work !
First, I had misplaced this as it was within another function in my functions.php file..
// Loads JavaScript file with functionality specific to LCQC.
wp_enqueue_script('jquery');
function add_cdtoevent() {
wp_enqueue_script('countdown', get_template_directory_uri() . 'countdown.js', array('jquery'), true );
}
add_action( 'wp_enqueue_scripts', 'add_cdtoevent' );
Afterward, I made sure my script was declared this way (due to the noConflict() variable wordpress uses) right before my closing body tag:
<script type="text/javascript">
jQuery(document).ready(function($) {
$(function() {
var endDate = "November 14, 2015 10:00:00";
$('.countdown.styled').countdown({
date: endDate,
render: function(data) {
$(this.el).html("<div>" + this.leadingZeros(data.days, 2) + " <span>days</span></div><div>" + this.leadingZeros(data.hours, 2) + " <span>hours</span></div><div>" + this.leadingZeros(data.min, 2) + " <span>minutes</span></div><div>" + this.leadingZeros(data.sec, 2) + " <span>seconds</span></div>");
}
});
});
});
</script>
And finally, I modified the following lines in jquery.countdown.js:
jQuery.fn.countdown = function(options) {
return $.each(this, function(i, el) {
var $el = $(el);
if (!$el.data(NAME)) {
// allow setting the date via the data-date attribute
if ($el.data(DATA_ATTR)) {
options.date = $el.data(DATA_ATTR);
}
$el.data(NAME, new Countdown(el, options));
}
});
};
to:
jQuery(document).ready(function($) {
jQuery.fn.countdown = function(options) {
return $.each(this, function(i, el) {
var $el = $(el);
if (!$el.data(NAME)) {
// allow setting the date via the data-date attribute
if ($el.data(DATA_ATTR)) {
options.date = $el.data(DATA_ATTR);
}
$el.data(NAME, new Countdown(el, options));
}
});
};
});
Thank you all for your help !
Related
I am attempting to apply a coupon code to the basket on a button press.
I have the following code:-
coupon = jQuery(this).data('coupon');
data = {coupon_code : coupon};
jQuery.post( "?wc-ajax=apply-coupon", { coupon_code: coupon }).done(function( data ) {
alert( "Data Loaded: " + data );
});
I can see the following data is being parsed to the server:-
coupon_code: 10percentdiscount
The 10percentdiscount exists.
The Server is not sending back a response once I have sent the request.
Am I correctly making this request or is there another way?
Thank you in advance.
You don't need to add custom code in your functions.php. Woocommerce supports adding coupons via AJAX natively (see how below).
Errors in your code:
You forgot to send the nonce (security parameter);
It is apply_coupon not apply-coupon (underscore vs dash);
Your URL should start with a slash "/?wc-ajax=apply_coupon";
Correct version:
var data = {
coupon_code: jQuery(this).data('coupon'),
security: '<?php echo wp_create_nonce("apply-coupon") ?>'
};
jQuery.post('/?wc-ajax=apply_coupon', data).done(function(data) {
alert("Data Loaded: " + data);
});
I would do so:
Define ajax url in header.php or in page would you add coupon
<script type="text/javascript" language="javascript">
var ajax_url = "<?php bloginfo('url'); ?>/wp-admin/admin-ajax.php";
</script>
In function.php you must define ajax call
function implement_ajax() {
include(TEMPLATEPATH . '/ajax_return.php');
}
add_action('wp_ajax_my_special_action', 'implement_ajax');
add_action('wp_ajax_nopriv_my_special_action', 'implement_ajax');
In ajax_return.php you past code that add coupon to woocommerce:
if (isset($_POST['couponcode']))
{ apply_coupon($_POST['couponcode']); };
function apply_coupon($couponcode) {
global $woocommerce; WC()->cart->remove_coupons();
$ret = WC()->cart->add_discount( $couponcode );
$array = array('return' => $ret); print_r($array);
}
exit;
Your jQuery.post will became this:
<script type="text/javascript">
jQuery(function(){
coupon = jQuery(this).data('coupon');
jQuery.post(ajax_url, {action : 'my_special_action', couponcode : coupon}, return_function, 'JSON');
});
function return_function(data)
{
console.log(data.return); //contains true if coupon was applied
}
</script>
If you need, call return_function to manage response.
Straight from WP Codex: http://codex.wordpress.org/AJAX_in_Plugins
I have this in my functions.php:
add_action( 'admin_footer', 'my_action_javascript' );
function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'whatever': 1234
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
</script>
<?php
}
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}
And I don't get a response. I do get an alert saying 'Got this from the server: ', but no response. What gives?
Running your code on two separate wordpress installs from within a plugin file (plugin-name.php) and from within functions.php in my theme, it returns the proper value both times. There do not seem to be any errors in your code either.
Is this the only javascript you're including in the admin area?
OK,
so I've got this weird situation. I'm trying to include Paul Underwood's simple smooth scroll script (http://www.paulund.co.uk/smooth-scroll-to-internal-links-with-jquery) in a Wordpress one-pager running on Wordpress 3.8.1.
However, the smooth scroll ain't working.
The script works perfectly on JFiddle, I've checked it for errors, but it's a simple copy-paste from the source, so that shouldn't be the problem. I'm pretty sure I've enqueued it properly in functions.php (yes, I also registerd jQuery). And it should work in noConflict.
So what am I missing here? It won't surprise me if it's a stupid little mistake...
Anyway, thanks in advance everyone :)
The HTML:
<img class="arrow" src="<?php bloginfo('stylesheet_directory'); ?>/images/arrow-down.png" alt="scroll down">
The script:
jQuery(document).ready(function($) {
$(document).ready(function() {
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
});
the functions.php
function my_scripts() {
wp_enqueue_script('jquery');
wp_enqueue_style( 'my-style', get_stylesheet_uri() );
wp_register_script( 'my-script', get_template_directory_uri().'/js/my-script.js', array('jquery'), '1.0', true );
wp_enqueue_script( 'my-script' );
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );
As your code says that you have two doc ready handlers and you can remove the inner doc ready first line is better:
jQuery(document).ready(function($) { // keep it, its better.
$(document).ready(function() { //<---remove this line and its closing
so final code should be:
jQuery(document).ready(function($) {
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
}); // end of animate
}); // end of click
}); // end of doc ready
Wordpress uses jQuery instead of $ by default. Try to replace all your $'s to jQuery.
jQuery(document).ready(function() {
jQuery('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash,
$target = jQuery(target);
jQuery('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
}); // end of animate
}); // end of click
}); // end of doc ready
Try this one.
EDIT: Oh, I've just seen that you are giving the $ as a parameter of the function. My fault.
But have you checked if you probably include jQuery twice?
OK, so I figured it out, guys.
As I predicted, it was some stupid little thing.
There was a relic
body{overflow-x: hidden}
in my stylesheet.
This is what's been trolling me - removed the line, and now everything works fine.
Thanks for the help, though :-)
This issue is resolved. My friend helped me here is the working code:
<script type="text/javascript">
setInterval(jQuery.get("<?php
$url = plugin_dir_url( $file );
echo plugins_url( 'update.php' , __FILE__ ); ?>", function(responseData) {
jQuery("#cur_pos").html(responseData);
}), 1000 * 300);
</script>
<div id="cur_pos">
</div>
I want to reload a php file every so often to update a widget im making for wordpress.
My code thus for ive hacked together doesn't seem to work. it will work when i use the simple include but wont refresh of course. What am I missing?
<script type="Javascript">
// reload php
if(!jQuery && $) {
var jQuery = $;
}
function updatePos(){
UpdateInSeconds = 30;
jQuery('#cur_pos').load('<?php
$url = plugin_dir_url( $file );
echo plugins_url( 'update.php' , __FILE__ ); ?>');
setTimeout("updatePos();",UpdateInSeconds*1000) ;
}
jQuery(document).ready(function(){
updatePos();
});
</script>
<div id="cur_pos">
</div>
This is the output:
<script type="Javascript">
// reload php
if(!jQuery && $) {
var jQuery = $;
}
function updatePos(){
UpdateInSeconds = 30;
jQuery('#cur_pos').load('http://www.thepuzzycat.com/wp-content/plugins/ArduinoStats/update.php');
setTimeout("updatePos();",UpdateInSeconds*1000) ;
}
jQuery(document).ready(function(){
updatePos();
});
</script>
<div id="cur_pos">
</div>
setInterval(jQuery.get("http://www.thepuzzycat.com/wp-content/plugins/ArduinoStats/update.php", function(responseData) {
jQuery("#cur_pos").html(responseData);
}), 1000 * 300);
It's not the best solution for performance and other aspects, but it does work and it's better than using a recursive function.
I have a little problem with calling a file in a WordPress plugin using ajax.I have this script:
<script type="text/javascript">
function setVal()
{
var val = jQuery('#custom_text_message').val()
alert('Setting the value to "' + val + '"')
jQuery.post('session.php', {value: val})
alert('Finished setting the value')
}
jQuery(document).ready(function() {
jQuery('#custom_text_message').blur(function() {setVal()});
//setTimeout('setVal()', 3000);
});
</script>
But when this function gets called, it shows an error in the console file not found. I want to know if this is the correct way to use ajax in WordPress. If not, how can I call a file which is in the root folder of site name session.php? I'm pretty new to WordPress.
I have solve my problem on my own.First i have define ajaxurl in my themes function.php like below:
<?php
add_action('wp_head','pluginname_ajaxurl');
function pluginname_ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<? }
?>
And I put the below script on the top of my plugin file.
<script type="text/javascript">
function setVal()
{
var val = jQuery('#custom_text_message').val()
var data = {
action: 'my_action',
value: val,
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
}
jQuery(document).ready(function() {
jQuery('#custom_text_message').blur(function() {setVal()});
//setTimeout('setVal()', 3000);
});
</script>
and here's the field, for which i am trying to do in my plugin.
<textarea name="custom_text_message" id="custom_text_message"></textarea>
and then I put my action which i m calling to my script in function.php.
add_action('wp_ajax_my_action', 'my_action_session');
function my_action_session() {
global $wpdb; // this is how you get access to the database
session_start();
$_SESSION['cus_msg'] = $_POST['value'];
die(); // this is required to return a proper result
}
and then call my session value in to my function.That's all i do and work for me and i hope this will helps someone else.
Note:
The wp_ajax_your_action action is for admin if you need to use it on the front end the action would be wp_ajax_nopriv_your_action.
In WordPress, Ajax requests should be made to http://your-wordpress-site/wp-admin/admin-ajax.php - which can be obtained using admin_url( 'admin-ajax.php' ) - and you should use action parameter to specify which function to call. You can pass the admin-ajax path to your javascript file via localization.
Add to your plugin PHP file after you enqueue your script:
wp_localize_script( 'your-script', 'js_obj', array('ajax_url' => admin_url( 'admin-ajax.php' ) );
In your javascript:
jQuery.post(js_obj.ajax_url, {value: val, action: 'run-my-ajax'})
Function to process the ajax in your plugin PHP file:
function call_my_ajax(){
// do stuff
exit;
}
add_action('wp_ajax_run-my-ajax', 'call_my_ajax');
add_action('wp_ajax_nopriv_run-my-ajax', 'call_my_ajax');
Read more: https://codex.wordpress.org/AJAX_in_Plugins
<script type="text/javascript">
function setVal()
{
jQuery.ajax({url:"<?php bloginfo('url');?>/wp-content/plugins/plugin_folder_name/session.php",success:function(result){alert(result);}}
}
</script>
WordPress works on absolute paths, use a complete URL instead of the relative URL:
jQuery.post('session.php', {value: val})
Use something like:
jQuery.post('<?php bloginfo('url');?>/wp-content/plugins/plugin_folder_name/session.php', {value: val})