更进一步:使用localize从php和js中访问进行处理access & modify 您的跟踪列表直接从php文件中获取。这个additional benefit 从这个解决方案中,您现在可以使用jQuery.ajax functions 1)。
function load_init_tracks()
{
$args = array
(
\'post_type\' => \'attachment\',
\'post_mime_type\' => \'audio\',
\'numberposts\' => -1
);
$audiofiles = get_posts($args);
$result = array();
foreach ( $audiofiles as $file )
{
$result[\'mp3\'] = wp_get_attachment_url( $file->ID ); // url
$result[\'title\'] = $file->post_title //title
$result[\'artist\'] = $file->post_content // description
}
// $result now contains all tracks as multi dimensional array
return $result;
}
function load_track_scripts()
{
// register your script, enqueue it and then add localize the result to access it inside your js file:
wp_register_script( \'mp3tracks\', get_stylesheet_directory().\'js/your_js_filename.js\', array( \'jquery\' ), 0, true );
wp_enqueue_script( \'mp3tracks\' );
wp_localize_script(
\'mp3tracks\',
\'track_list_object\',
array(
\'ajaxurl\' => admin_url( \'admin-ajax.php\' )
,\'nonce\' => wp_create_nonce( \'mp3_nonce_value\' )
,\'action\' => "mp3tracks"
,\'tracks\' => load_init_tracks()
);
// Hook it to some ajax callback (for public and logged in users):
add_action( \'wp_ajax_nopriv_mp3tracks\', \'mp3tracks_cb\' );
add_action( \'wp_ajax_nopriv_mp3tracks\', \'mp3tracks_cb\' );
}
add_action( \'init\', \'load_track_scripts\' );
// Now call the function that processes the
function mp3tracks_cb()
{
check_ajax_referer( \'mp3_nonce_value\', \'nonce\' );
// This is what the data you can process with the ajax response
$data = $_POST;
# @todo validate your input: esc_attr(), strip_tags(), etc.
$response = json_encode( array(
\'tracks\' => $data
) );
header( "Content-Type: application/json" );
echo $response;
exit;
}
然后,您可以从访问javascript文件中的结果
track_list_object.data
. 这↑ 还允许您在函数中通过ajax处理内容。
只需在以下过程中处理您的东西:
// Inside theme_root/js/your_js_filename.js
jQuery( document ).on(
"pageinit"
,function( e, data )
{
// do stuff... take a look at your "console"-tab in the chrome/IE dev bar or with FF Firebug
console.log( track_list_object );
}
);
您不必这样做,但它很简单,允许您在需要动态修改播放列表时使用ajax