How to localize admin.php only once

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.

Read More

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.

Related posts

Leave a Reply

1 comment

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