【问题标题】:Saving values in media upload option in WordPress theme settings在 WordPress 主题设置中的媒体上传选项中保存值
【发布时间】:2016-11-06 22:35:35
【问题描述】:

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

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

在尝试了许多解决方案之后,Rushabh Dave 的解决方案 here 效果很好,几乎完美但并不完全...

我的问题是我得到弹出框,选择图像,然后我有该图像的 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>

【问题讨论】:

  • 你在哪里上传这些图片?前端,后端?
  • 这就是我有点困惑的地方。我(愚蠢地)假设用户可以单击“添加媒体”,选择他们的图像,然后将其上传到服务器并保存。然后我可以在前端调用这个来显示它。
  • 但是抱歉,您的意思可能是“添加媒体”选项在哪里。它位于后台后台的“主题设置”部分。
  • 如果您希望用户将图像上传到您的 WordPress,我不建议您使用媒体上传器。他们将能够看到您媒体库 (you could restrict it) 中的所有图像。我会使用简单的文件上传输入并使用media_handle_sideload 加载图像
  • 抱歉,这里有些混乱。我不希望用户上传到我的媒体库。这是他们将使用的主题,而不是我的。我为客户开发主题,但不经常使用主题设置,所以我尝试添加很多选项,以便他们可以自己更新所有选项,这样他们就可以看到自己的媒体库了。

标签: php wordpress themes settings


【解决方案1】:

首先,您只想将脚本排入后端。在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' );
}

现在我不知道您是如何保存这些选项的,因为您还没有指定,但是在保存它们时应该使用某种钩子。只要把它放在那里,它就可以做到。

【讨论】:

  • 您也可以添加一个删除图像按钮,该按钮将删除img 元素并在单击时清除输入字段。我没有对此进行测试,但它应该可以工作。
  • 非常感谢这个 dingo_d,当我点击“上传图片”时,我现在还不在那里,没有任何反应,我没有弹出媒体库。我在 admin.js 中有脚本,该脚本已上传到 /js/admin.js,我现在的代码如下。我确定我在某个地方遗漏了什么。
  • 脚本加载了吗?检查您的页面并查看脚本是否已加载。
  • 不,不是。是否应该更改对 yourthemeslug_ 的所有引用?
  • 好吧,这应该是你的主题。另外请确保$hook 的条件签出;)
【解决方案2】:
     <?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' );
 }
 ?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-30
    • 2011-09-08
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    • 2012-08-13
    • 2014-08-02
    • 2012-07-25
    相关资源
    最近更新 更多