WordPress 后台上传自定义网站Logo

需求:

众所周知一般网站的logo都是固定的所以我在做网站时也是使用的静态logo文件,但最近用wp给一个客户做的网站时,因为网站现在的logo可能会需要重新设计,所以客户提出了需要在后台可以自己修改网站logo,接收需求后就在网络上找如何解决,但找了一圈都没有找到想要的效果(都是如何修改wp的登录logo),还好找到两篇相关的文章,最后根据这两篇文章自己Codeing最终实现了功能代码:
 
1.在主题function中添加以下代码
  1. <?php
    /**在function中添加以下代码
    *WordPress添加额外选项字段到常规设置页面
    * http://www.wpdaxue.com/add-field-to-general-settings-page.html
    */
    $new_general_setting = new new_general_setting();
    class new_general_setting {
    function new_general_setting(){
    add_filter('admin_init', array(&$this ,'register_logo'));
    }
    function register_logo(){
    //需要'js/uploader.js组件
    wp_enqueue_script('fli-upload-js', $this->url .'js/uploader.js', array('jquery','media-upload','thickbox'));
    wp_enqueue_style('thickbox');
    wp_enqueue_style('fli-upload-css', $this->url .'css/uploader.css');
    register_setting('general','logo','esc_attr');
    add_settings_field('logo','<label for="logo">'.__('网站Logo').'</label>', array(&$this,'logo_fields_html'),'general');
    }
    function logo_fields_html(){
    $value = get_option('logo','');
    echo '<input type="text" class="regular-text ltr" id="logo" name="logo" maxlength="200" value="'. $value .'" readonly/> <input type="button" id="general_logo" class="button insert-media add_media" value="上传">';
    }
    }
    //自定义后台Css和Js
    add_action('admin_enqueue_scripts','myAdminScripts');
    function myAdminScripts(){
    //主题下加载admin.js
    wp_register_script('default', get_template_directory_uri().'/admin.js', array(),'','all');
    wp_enqueue_script('default');
    wp_register_style('default', get_template_directory_uri().'/admin.css', array(),'','all');
    wp_enqueue_style('default');
    }
    ?>
    

2.在主题admin.js中添加代码

options_general();
//在常规选项页面添加自定义信息
function options_general (){
if(!Islocatl_pathname('options-general.php'))return;
//点击上传按钮或input元素时打开上传窗口
jQuery('#general_logo,#logo').click(function(){
//打开上传窗口需要js/uploader.js组件
tb_show('','media-upload.php?type=image&TB_iframe=true');
returnfalse;
});
//图片上传页面回传
//html:为选择的图片元素
window.send_to_editor =function(html){
imgurl = jQuery(html).attr('src');
// 保存值并写入optuions表
jQuery('#logo').val(imgurl);
//删除图片上传窗口
tb_remove();
returnfalse;
}//end send_to_editor
}
//当前页面是否是指定的页面
functionIslocatl_pathname(pathname){
return location.pathname.indexOf(pathname)>=0;
}//end 当前页面是否是指定的页面

 

效果图:
 
参考:

 



posted @ 2015-02-01 19:53  HTL  阅读(9900)  评论(0编辑  收藏  举报
htl