1

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.

1 Answer 1

1

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.)

1
  • +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. Nov 19, 2011 at 0:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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