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 creating a set of plugins that all use AJAX. Now localizing the admin.php in all the plugins seems to be a bit of an overkill. Is there a way to localize the script only once.\

Now I do not know which plugin would be initialized at first, so I have to place the localize function in all the plugins.

The way I do it now is by the following code.

  if( ! defined( 'AJAX_LOCALIZED' ) ){
    define( 'AJAX_LOCALIZED', 1 );
    wp_localize_script(
        'my-ajax-script',
        'ajax-object',
        array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) )
    );
  }

This works ok, but maybe there is a build in method to do this, maybe more general that compliments with other plugins.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

Good question, and one I've dealt with, but never quite satisfactorily. It would be very nice to figure out a core function that handles this.

In the meantime, though, I would just bypass the whole localize_script function and add an action to wp_head that just defines a global javascript object with the info that all your plugins will need. localize_script seems a little overused for cases like this, and while this solution certainly isn't any more elegant, it seems clearer to me:

add_action( 'wp_head', 'localize_ajax_scripts' );

if ( !function_exists( 'localize_ajax_scripts' ) ) {

function localize_ajax_scripts() {
    $ajaxurl = admin_url( 'admin-ajax.php' );
    echo <<<JS
<script type="javascript">
    var ajax_object = {
        ajaxurl: {$ajaxurl}
    }
</script>
JS;

}

}

Adding the same function twice on one hook doesn't cause it to fire twice, so you don't have to define the constant; you just have to avoid defining the function more than once. (And if you're trying to define the function differently for different plugins to pass additional information, then you're really in trouble.)

share|improve this answer
    
+1 Thanks for your response. I like the small variation of just adding is directly as a functions. One plus is that you can add more to the head than just an object, you can also add some small shared functions. It does cause some code replication in all the plugins, but so did my method. Too bad WP does not have a build in feature for this. –  Saif Bechan Nov 19 '11 at 0:34

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.