WordPress设置页面上传徽标

时间:2014-08-10 03:03:07

标签: php wordpress api upload settings

在过去的几个小时里,我一直在努力解决这个问题。 我试图创建自己的主题设置页面,然后进入徽标上传字段 现在我被卡住了......我查看了这里和谷歌的帖子,但我仍然遗漏了一些东西而无法完成任务......

我添加到我的主题functions.php -

    register_setting( 'empathy-settings', 'empathy-setting-logo' );
add_settings_section( 'section-three', '', 'section_three_callback', 'empathy-design' );
add_settings_field( 'logo-image', 'Website Logo', 'field_logo_callback', 'empathy-design', 'section-three' );

function admin_scripts_upload() {
   wp_enqueue_script('media-upload');
   wp_enqueue_script('thickbox');
   wp_register_script('empathy-logo-upload', get_bloginfo( 'stylesheet_directory' ) . '/js/uploader.js', 
   array('jquery','media-upload','thickbox'));
   wp_enqueue_script('empathy-logo-upload');
}
function admin_styles_upload() {
    wp_enqueue_style('thickbox');
}

function section_three_callback() { }

function field_logo_callback() {
    $setting = esc_attr( get_option( 'empathy-setting-logo' ) );

    echo '<img src="" id="thenewlogo" />';
    echo '<div style="width:100%; float:left;">';

        echo '<input type="text" name="empathy-setting-logo" id="empathy-setting-logo" style="width:200px;" />';
        echo '<br /><a id="empathy-setting-logo-button">Upload</a>';

    echo '</div>';
}

add_action('admin_print_scripts', 'admin_scripts_upload');
add_action('admin_print_styles', 'admin_styles_upload');

我使用代码

创建了uploader.js
jQuery(document).ready(function() {

jQuery('#empathy-setting-logo-button').click(function() {
     targetfield = jQuery('#empathy-setting-logo');
     tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');
     return false;
});

window.send_to_editor = function(html) {
     imgurl = jQuery('img',html).attr('src');
     jQuery(targetfield).val(imgurl);
     tb_remove();
}

});

媒体库显示正在上传文件,但我无法插入文章&#34; 所以我无法保存图片网址。

我怎么能完成它呢?

1 个答案:

答案 0 :(得分:1)

我就这样做了:

<input type="text" name="new_img" id="new_img" value="<?php echo esc_attr( get_option( 'empathy-setting-logo' ) ); ?>">
<a class="button" onclick="upload_image('new_img');">Upload Favicon</a> 

这里是JS-Function:

var uploader;
function upload_image(id) {

  //Extend the wp.media object
  uploader = wp.media.frames.file_frame = wp.media({
    title: 'Choose Image',
    button: {
      text: 'Choose Image'
    },
    multiple: false
  });

  //When a file is selected, grab the URL and set it as the text field's value
  uploader.on('select', function() {
    attachment = uploader.state().get('selection').first().toJSON();
    var url = attachment['url'];
    jQuery('#'+id).val(url);
  });

  //Open the uploader dialog
  uploader.open();
}
</script>

确保将以下内容添加到functions.php

add_action( 'admin_enqueue_scripts', 'wp_enqueue_media' );