我尚未对此进行测试,但您可能会了解其要点:
add_action(\'wp_enqueue_scripts\', \'send_image_source_to_js\');
function send_image_source_to_js() {
global $post;
// Does this post have a featured image? If yes, fetch the link / source
$has_image = $source = false;
if($thumb_id = get_post_thumbnail_id($post->ID)) {
$has_image = true;
$source_array = wp_get_attachment_image_src($thumb_id, array(300,300));
$source = $source_array[0];
}
// Build an array with what we\'ve found about the post
$image_params = array(
\'has_image\' => $has_image ? 1 : 0,
\'source\' => $source ? $source : 0
);
// Register, localize and enqueue the script
wp_register_script(\'my_script\', \'path/to/my_script.js\');
wp_localize_script(\'my_script\', \'image_params\', $image_params);
wp_enqueue_style(\'my_script\');
}
wp\\u localize\\u script所做的是创建一个Javascript对象,该对象将打印在页面的html中,然后您可以在JS代码中使用它,如下所示(我很懒惰,所以我添加了一个不敏感的jQuery示例):
$(\'#my_image\').attr(\'src\', image_params.source);
让我们知道进展如何!