在WordPress主题设置的媒体上传选项中保存值


Saving values in media upload option in WordPress theme settings

我有一个新的主题,我正在工作,我真的需要3个图像上传选项,触发弹出媒体上传框。

我知道现在推荐使用定制器,但对我来说只有在样式中使用它才有意义。颜色和字体),仍然有一个主题设置部分,这是我所做的。

在尝试了许多解决方案之后,Rushabh Dave的解决方案在这里奏效了,近乎完美,但不完全…

我的问题是我得到弹出框,选择图像,然后我有该图像的URL,但当我点击保存时,页面刷新,但我的图像没有保存,URL消失,因此我不能在前端拾取它。

我不确定我做错了什么。

在显然也

<?php
// jQuery
wp_enqueue_script('jquery');
// This will enqueue the Media Uploader script  
wp_enqueue_media();
?>
<div>
<label for="image_url">Image</label>
<input type="text" name="image_url" id="image_url" class="regular-text" />
<input type="button" name="upload-btn" id="upload-btn" class="button-secondary" value="Upload Image">
</div>
<script type="text/javascript">
jQuery(document).ready(function($){
$('#upload-btn').click(function(e) {
    e.preventDefault();
    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
        $('#image_url').val(image_url);
    });
});
});
</script>

前端

<div><img src="<?php echo $options['image_url']; ?>" /></div>

首先,您希望仅在后端对脚本进行排队。In functions.php add

add_action( 'after_setup_theme', 'yourthemeslug_theme_setup' );
if ( ! function_exists( 'yourthemeslug_theme_setup' ) ) {
    /**
     * Sets up theme defaults and registers support for various WordPress features.
     *
     * Note that this function is hooked into the after_setup_theme hook, which
     * runs before the init hook. The init hook is too late for some features, such
     * as indicating support for post thumbnails.
     *
     * @since  1.0.0
     */
    function yourthemeslug_theme_setup() {
        add_action( 'admin_enqueue_scripts', 'yourthemeslug_backend_scripts' );
    }
}
if ( ! function_exists( 'yourthemeslug_backend_scripts' ) ) {
    /**
     * Enqueue back end scripts and styles.
     *
     * @param  string $hook Hook string to check the page, so that not all scripts are loaded
     *                      unnecessarily on every page.
     * @since 1.0.0
     */
    function yourthemeslug_backend_scripts( $hook ) {
        if ( 'your_subpage_slug' === $hook ) {
            wp_enqueue_media();
            wp_enqueue_script( 'yourthemeslug_image_upload', get_template_directory_uri(). '/js/admin.js', array('jquery') );
        }
    }
}

或者直接添加到现有的after_setup_theme钩子,以及钩子到admin_enqueue_scripts的函数。

yourthemeslug_backend_scripts函数中的your_subpage_slug必须替换为描述自定义构建子页面的字符串。查看它是什么最好的方法是在if条件之前执行print_r($hook);,看看字符串将是什么(在检查器中,它应该在body标签下面)。

在你的页面你应该有

<div>
    <label for="image_url">Image</label>
    <div class="image"><img src="<?php echo esc_url( $image ); ?>" /></div>
    <input type="text" name="image_url" id="image_url" class="regular-text" />
    <input type="button" name="upload-btn" id="upload-btn" class="button-secondary" value="Upload Image">
</div>

其中$image

$image = ( isset( $options['image_url'] ) && '' !== $options['image_url'] ) ? $options['image_url'] : '';

需要从数据库中获取的值。

因此,当点击#upload-btn时,媒体上传器必须打开。

admin.js文件中添加

jQuery( document ).ready(function( $) {
    "use strict";
    $(document).on('click', '#upload-btn', upload_image_button);
    function upload_image_button(e) {
        e.preventDefault();
        var $input_field = $('#image_url');
        var $image = $('.image');
        var custom_uploader = wp.media.frames.file_frame = wp.media({
            title: 'Add Image',
            button: {
                text: 'Add Image'
            },
            multiple: false
        });
        custom_uploader.on('select', function() {
            var attachment = custom_uploader.state().get('selection').first().toJSON();
            $input_field.val(attachment.url);
            $image.html('').html('<img width="254" src="'+attachment.url+'" />');
        });
        custom_uploader.open();
    }
});

触发媒体上传。但你还是要保存它。

在保存选项的页面中,您需要检查图像url的输入字段是否设置,是否为空,然后您可以将其保存到您的选项中(我将包括nonce检查以确保安全)

if ( isset($_POST['image_url'] ) && '' !== $_POST['image_url'] ) {
    update_option( $_POST['image_url'], 'image_url' );
}

现在我不知道你是如何保存这些选项的,因为你没有指定,但是在保存它们时应该使用某种钩子。把这个放到这里,它就会起作用了

     <?php
 add_action( 'after_setup_theme', 'yourthemeslug_theme_setup' );
 if ( ! function_exists( 'yourthemeslug_theme_setup' ) ) {
 /**
 * Sets up theme defaults and registers support for various WordPress features.
 *
 * Note that this function is hooked into the after_setup_theme hook, which
 * runs before the init hook. The init hook is too late for some features, such
 * as indicating support for post thumbnails.
 *
 * @since  1.0.0
 */
 function yourthemeslug_theme_setup() {
    add_action( 'admin_enqueue_scripts', 'yourthemeslug_backend_scripts' );
 }
 }
 if ( ! function_exists( 'yourthemeslug_backend_scripts' ) ) {
 /**
 * Enqueue back end scripts and styles.
 *
 * @param  string $hook Hook string to check the page, so that not all scripts are loaded
 *                      unnecessarily on every page.
 * @since 1.0.0
 */
 function yourthemeslug_backend_scripts( $hook ) {
    if ( 'theme_settings' === $hook ) {
        wp_enqueue_media();
        wp_enqueue_script( 'yourthemeslug_image_upload', UTTER_TEMPPATH . '/js/admin.js', array('jquery') );
    }
 }
 }
 ?>
 <div>
 <label for="image_url">Image</label>
 <div class="image"><img src="<?php echo esc_url( $image ); ?>" /></div>
 <input type="text" name="image_url" id="image_url" class="regular-text" />
 <input type="button" name="upload-btn" id="upload-btn" class="button-secondary" value="Upload Image">
 </div>
 <?php
 if ( isset($_POST['image_url'] ) && '' !== $_POST['image_url'] ) {
 update_option( $_POST['image_url'], 'image_url' );
 }
 ?>