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

Saving values in media upload option in WordPress theme settings

我正在制作一个新主题,我确实需要 3 个图片上传选项来触发弹出式媒体上传框。

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

在尝试了许多解决方案后,Rushabh Dave 的解决方案 here 奏效了,近乎完美,但还不完全...

我的问题是我得到弹出框,select 图像,然后我有该图像的 URL 但是当我点击保存时,页面刷新但我的图像没有保存,URL 消失了,所以我无法在前端拾取它。

我不确定自己做错了什么。

在functions.php

<?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>

首先,您只想在后端排队您的脚本。在 functions.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 ( '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 的输入字段是否已设置,是否为空,然后您可以将其保存到您的选项中(我会包括安全措施的随机数检查)

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' );
 }
 ?>