您只能在少数模板或特定页面上有条件地回显代码。以下是一个示例:
add_action ( \'wp_head\', \'my_js_variables\' );
function my_js_variables(){
// for specific page templates
$current_template = get_page_template();
// return if there is no page template, or if the page template is other than template-x1.php or template-x2.php
if( !isset($current_template) || ( $current_template != \'template-x1.php\' && $current_template != \'template-x2.php\' ) ){ return; } ?>
<script type="text/javascript">
var ajaxurl = <?php echo json_encode( admin_url( "admin-ajax.php" ) ); ?>;
var ajaxnonce = <?php echo json_encode( wp_create_nonce( "itr_ajax_nonce" ) ); ?>;
var myarray = <?php echo json_encode( array(
\'foo\' => \'bar\',
\'available\' => TRUE,
\'ship\' => array( 1, 2, 3, ),
) ); ?>
</script>
<?php
}