【发布时间】:2016-10-06 23:15:13
【问题描述】:
我无法让这个 Jquery 脚本在我的 function.php wordpress 文件中用于自定义主题。有人能帮我吗。问题是当我在我的 wordpress 管理员中转到自定义帖子类型时,当我单击浏览按钮插入它不允许我插入的图像时,它根本什么都不做。
这是代码(是的,有一个打开的 php 标记,只是没有显示。)
function show_your_images_meta_box() {
global $post;
$meta = get_post_meta( $post->ID, 'your_images', true ); ?>
<input type="hidden" name="your_meta_box_nonce" value="<?php echo wp_create_nonce( basename(__FILE__) ); ?>">
<p>
<label for="your_images[image]">Upload Poster Image</label>
<br>
<input type="text" name="your_images[image]" id="your_images[image]" class="meta-image regular-text" value="<?php echo $meta['image']; ?>">
<input type="button" class="button image-upload" value="Browse">
</p>
<div class="image-preview"><img src="<?php echo $meta['image']; ?>" style="max-width: 250px;"></div>
<script> jQuery(document).ready(function($) {
// Instantiates the variable that holds the media library frame.
var meta_image_frame;
// Runs when the image button is clicked.
$('.image-upload').click(function(e) {
// Prevents the default action from occuring.
e.preventDefault();
var meta_image = $(this).parent().children('.meta-image');
// If the frame already exists, re-open it.
if (meta_image_frame) {
meta_image_frame.open();
return;
}
// Sets up the media library frame
meta_image_frame = wp.media.frames.meta_image_frame = wp.media({
title: meta_image.title,
button: {
text: meta_image.button
}
});
// Runs when an image is selected.
meta_image_frame.on('select', function() {
// Grabs the attachment selection and creates a JSON representation of the model.
var media_attachment = meta_image_frame.state().get('selection').first().toJSON();
// Sends the attachment URL to our custom image input field.
meta_image.val(media_attachment.url);
//var image_url = meta_image.val();
//$(selected).closest('div').find('.image-preview').children('img').attr('src', image_url);
});
// Opens the media library frame.
meta_image_frame.open();
});
});
</script>
<?php }
【问题讨论】:
-
尝试在浏览器控制台中查看错误?你能粘贴生成的可能更容易调试的 javascript 吗?
-
最好使用admin_enqueue_scripts() 将您的脚本排入管理区域。您可以事件检查钩子、自定义帖子类型等并仅在该页面上加载您的脚本,而不是在其他页面上(发生冲突的可能性较小)。
标签: javascript jquery wordpress wordpress-theming