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 當前頁面是否是指定的頁面

 

效果圖:
 
參考:

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM