Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am using ajax on my template to load a file called counter.php. When I click a button, it is supposed to increase the counter. But when I click the button I get this error "Fatal error: Call to undefined function get_option()".

This is what I have on counter.php

$post_ID = $_POST['ID'];
$opn_name = 'fb_counter'.$post_ID;
$counter_value = get_option($opn_name);
if($counter_value==NULL){
$counter_value = 0;
}
update_option($opn_name, $counter_value+1);

echo get_option($opn_name);

I am not sure what is wrong. Do I have to include any wordpress files on this php file ?

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

Basically, if you're going to be making calls to WordPress functions, then you should be in the WordPress environment, which means that you should not be calling your own files to begin with, but should implement your AJAX call within a WordPress hook.

Read up on this: http://codex.wordpress.org/AJAX_in_Plugins

That article describes how to implement AJAX requests within WordPress plugins, but it works equally well in themes or in any other code that WP loads.

Essentially, you hook a function to wp_ajax_* or wp_ajax_nopriv_* and then make your request through the the admin-ajax.php file instead of directly to your own file.

Side note: Implementing a counter like you're trying to do won't work particularly well, because you have a race-condition there. More than one person can be visiting your site at the exact same time. Storing counter data in the DB like that isn't going to scale to a very large site with lots of requests, although it will work fine for smaller sites.

share|improve this answer
    
Thanks man you are a life saver. I will look into the these worpdpress functions. But how can this race condition be avoided or dealt with. I want to create a counter that counts how many times a button is pressed. I am expecting 20,000 to 30,000 visitors p/m. –  Lafanter Sep 19 '12 at 4:37
    
I doubt you'll have a problem with only that many visitors. –  Otto Sep 19 '12 at 19:50
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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