Я считаю, что мой первый ответ по-прежнему будет полезен для некоторых, но поскольку вы не можете использовать расширенные настраиваемые поля или другой плагин, вместо этого вы можете добавить следующий код в свой файл functions.php
.
Обратите внимание, что я принял и немного изменил код от this Stack Overflow post, чтобы ограничить его одним изображением, а не группой изображений, и я использовал более современный медиа-загрузчик.
Кроме того, это добавит настраиваемое поле только к вашему типу post
, а не к вашим страницам, пользовательским типам сообщений и т. Д. Просмотрите код, и я уверен, что вы можете выяснить, как это изменить, если это необходимо ,
add_action('admin_init', 'add_post_image_so_30337102');
add_action('admin_head-post.php', 'print_scripts_so_30337102');
add_action('admin_head-post-new.php', 'print_scripts_so_30337102');
add_action('save_post', 'update_post_image_so_30337102', 10, 2);
/**
* Add custom Meta Box to Posts post type
*/
function add_post_image_so_30337102()
{
wp_enqueue_media();
add_meta_box(
'post_image',
'Custom Uploader',
'post_image_options_so_30337102',
'post',
'normal',
'core'
);
}
/**
* Print the Meta Box content
*/
function post_image_options_so_30337102()
{
global $post;
$image_data = get_post_meta($post->ID, 'image_data', true);
// Use nonce for verification
wp_nonce_field(plugin_basename(__FILE__), 'noncename_so_30337102');
?>
<div id="dynamic_form">
<div id="field_wrap">
<div class="field_row">
<div class="field_left">
<div class="form_field">
<label>Image URL</label>
<input type="text"
class="meta_image_url"
name="image[image_url]"
value="<?php esc_html_e(isset($image_data['image_url']) ? $image_data['image_url'] : ''); ?>"
/>
</div>
<div class="form_field">
<label>Description</label>
<input type="text"
class="meta_image_desc"
name="image[image_desc]"
value="<?php esc_html_e(isset($image_data['image_desc']) ? $image_data['image_desc'] : ''); ?>"
/>
</div>
</div>
<div class="field_right image_wrap">
<img src="<?php esc_html_e($image_data['image_url']); ?>" height="48" width="48" />
</div>
<div class="field_right">
<input class="button" type="button" value="Choose File" onclick="add_image(this)" /><br />
</div>
<div class="clear" /></div>
</div>
</div>
</div>
<?php
}
/**
* Print styles and scripts
*/
function print_scripts_so_30337102()
{
// Check for correct post_type
global $post;
if('post' != $post->post_type)
return;
?>
<style type="text/css">
.field_left {
float:left;
}
.field_right {
float:left;
margin-left:10px;
}
.clear {
clear:both;
}
#dynamic_form {
width:580px;
}
#dynamic_form input[type=text] {
width:300px;
}
#dynamic_form .field_row {
border:1px solid #999;
margin-bottom:10px;
padding:10px;
}
#dynamic_form label {
padding:0 6px;
}
</style>
<!-- New script taken from here: http://brinidesigner.com/use-wordpress-3-5-new-media-uploader-for-your-plugin-and-theme-options-panel-development/ -->
<script type="text/javascript">
function add_image(obj) {
var parent=jQuery(obj).parent().parent('div.field_row');
var inputField = jQuery(parent).find("input.meta_image_url");
var image = wp.media({
title: 'Upload Image',
// mutiple: true if you want to upload multiple files at once
multiple: false
}).open()
.on('select', function(e){
// This will return the selected image from the Media Uploader, the result is an object
var uploaded_image = image.state().get('selection').first();
// We convert uploaded_image to a JSON object to make accessing it easier
// Output to the console uploaded_image
//console.log(uploaded_image);
var image_url = uploaded_image.toJSON().url;
// Let's assign the url value to the input field
inputField.val(image_url);
jQuery(parent)
.find("div.image_wrap")
.html('<img src="'+image_url+'" height="48" width="48" />');
});
return false;
}
</script>
<?php
}
/**
* Save post action, process fields
*/
function update_post_image_so_30337102($post_id, $post_object)
{
// Doing revision, exit earlier **can be removed**
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return;
// Doing revision, exit earlier
if ('revision' == $post_object->post_type)
return;
// Verify authenticity
if (!wp_verify_nonce($_POST['noncename_so_30337102'], plugin_basename(__FILE__)))
return;
// Correct post type
if ('post' != $_POST['post_type'])
return;
if ($_POST['image'])
{
// Build array for saving post meta
$image_data = array();
if ('' != $_POST['image']['image_url'])
{
$image_data['image_url'] = $_POST['image']['image_url'];
$image_data['image_desc'] = $_POST['image']['image_desc'];
}
if ($image_data)
update_post_meta($post_id, 'image_data', $image_data);
else
delete_post_meta($post_id, 'image_data');
}
// Nothing received, all fields are empty, delete option
else
{
delete_post_meta($post_id, 'image_data');
}
}
Теперь вы можете получить URL изображения (и описание) внутри вашего the_post()
петли шаблона, как это:
$image_data = get_post_meta($post->ID, 'image_data', true);
А потом эхо изображение, как это. Вы можете повторно использовать CSS из моего первого ответа.
<div class="hentry" style="background-image:url(<?php echo $image_data['image_url']; ?>)"></div>
спасибо за подробный ответ брата, но проблема в том, что мой клиент не хочет ничего подобного выше. Его просто интересует пользовательское кодирование и ничего другого :(..... так, я должен найти это решение только по его сценарию ... кстати, действительно спасибо за вашу помощь и время ... оставайтесь счастливыми. –
Нет проблем.Я добавил второй ответ, который может быть более полезным для вас. Для этого не требуется сторонний плагин. Дайте мне знать, если это вам полезно. – Jonathan