我刚刚找到了一种更干净的方法。。。感谢WPSE的另一个问题How do I add a php statement to a jQuery string.
我从来没有听说过wp_localize_script() 直到读到这个问题的答案(我喜欢WPSE:-)。
PHP
add_action (\'wp_enqueue_scripts\', \'localize_js\') ;
function
localize_js ()
{
global $post ;
$args = array(
\'post_type\' => \'page\',
\'posts_per_page\' => -1,
\'post_parent\' => $post->ID,
\'order\' => \'ASC\',
\'orderby\' => \'menu_order\'
);
$subservice = new WP_Query( $args );
$slugs = array () ;
while ( $subservice->have_posts() ) {
$subservice->the_post();
$slugs[] = $post->post_name ;
}
wp_reset_postdata () ;
wp_enqueue_script (\'my_script\', plugins_url (\'js/my_script.js\', __FILE__), array (), false, true) ;
// wp_localize_script() will handle the outputing of the relevant JS global decl
wp_localize_script (\'my_script\', \'my_slugs\', array (\'slugs\' => $slugs)) ;
return ;
}
JS,my\\u脚本。js公司
$(\'#pagepiling\').pagepiling({
sectionSelector: \'.box\',
anchors: my_slugs.slugs,
menu: \'#menu\'
)};