我在wordpress后端有自己的选项页面,在那里我列出了一个特定帖子类型的帖子。另外,我可以选择更改帖子的精选图片。
使用以下代码我打开媒体库并选择图像。
<div class="logoBox">
<?php
$upload_link = esc_url( get_upload_iframe_src( 'image', $item->ID ) );
$supplier_img_id = get_post_meta( $item->ID, '_thumbnail_id', true );
$supplier_img_src = wp_get_attachment_image_src( $supplier_img_id, 'full' );
$img_success = is_array( $supplier_img_src );
?>
<a class="changeSupplierImage <?php if ( $img_success ) { echo 'hidden'; } ?>" href="<?php echo $upload_link ?>">
<?php if ( $img_success ) : ?>
<img src="<?php echo $supplier_img_src[0] ?>" alt="<?php echo $item->post_title; ?>" />
<?php endif; ?>
</a>
<input class="custom-img-id" name="custom-img-id" type="hidden" value="<?php echo esc_attr( $supplier_img_id ); ?>" />
</div>
jQuery(".changeSupplierImage").each(function(){
jQuery(this).click(function(event){
event.preventDefault();
var frame,
imgContainer = jQuery(this),
imgIdInput = jQuery(this).parent().find( '.custom-img-id' );
if ( frame ) {
frame.open();
return;
}
frame = wp.media({
title: 'Select or Upload Media Of the Supplier',
button: {
text: 'Use this media'
},
multiple: false
});
frame.on( 'select', function() {
var attachment = frame.state().get('selection').first().toJSON();
imgContainer.html( '<img src="'+attachment.url+'" alt="" />' );
imgIdInput.val( attachment.id );
var ajaxurl = "/wp-admin/admin-ajax.php";
var attachmentUrl = attachment.url;
var postId = jQuery(this).parent().parent().parent().parent().find(".currentSuppPostId").val();
$.ajax({
type: 'POST',
url: ajaxurl,
data: {
action: 'update_featured_image',
attachmentUrl: attachmentUrl,
postId: postId
},
success: function (data) {
}
});
});
frame.open();
});
});
而且,您如何看待,为了更新精选图片,我添加了ajax调用&#34; update_featured_image&#34;正在做的功能如下:
function update_featured_image(){
$postId = $_POST['postId'];
$attachmentUrl = $_POST['attachmentUrl'];
update_post_meta($postId, '_thumbnail_id', $attachmentUrl);
}
add_action('wp_ajax_nopriv_update_featured_image', 'update_featured_image');
add_action('wp_ajax_update_featured_image', 'update_featured_image');
但这不是更新我的精选图片,而是空的。有什么想法吗?