How to localize admin.php only once

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