WordPress教程

WordPress 建站主题开发常用功能函数

阿里云
  1. <?php
  2. //通过这段代码,对语言包进行翻译,需要将语言包的代码添加到调用主题选项代码的前面
  3. //load_theme_textdomain('ankium', get_template_directory() . '/languages');
  4. /*
  5.  * 移除Wordpress后台顶部左上角的W图标
  6.  */
  7. add_action('wp_before_admin_bar_render', 'annointed_admin_bar_remove', 0);
  8. function annointed_admin_bar_remove() {
  9.     global $wp_admin_bar;
  10.     /* Remove their stuff */
  11.     $wp_admin_bar->remove_menu('wp-logo');
  12. }
  13.  
  14.  
  15. /*
  16.  * 自定义后台登录Logo的Url
  17.  */
  18. add_filter( 'login_headerurl', 'custom_loginlogo_url' );
  19. function custom_loginlogo_url($url) {
  20.     return 'http://www.ankium.com';
  21. }
  22.  
  23.  
  24. /*
  25.  * 自定义 WordPress 后台底部的版权和版本信息
  26.  */
  27. add_filter('admin_footer_text', 'left_admin_footer_text');
  28. function left_admin_footer_text($text) {
  29.     // 左边信息
  30.     $text = '大道行思,开拓创新;大道至简,务实为要';
  31.     return $text;
  32. }
  33. add_filter('update_footer', 'right_admin_footer_text', 11);
  34. function right_admin_footer_text($text) {
  35.     // 右边信息
  36.     $text = "延安安琪云信息科技有限公司";
  37.     return $text;
  38. }
  39.  
  40.  
  41. /*
  42.  * 屏蔽 WP 后台“显示选项”和“帮助”选项卡
  43.  */
  44. //add_filter('screen_options_show_screen', 'remove_screen_options');
  45. //add_filter( 'contextual_help', 'remove_wp_help', 999, 3 );
  46. function remove_screen_options(){ return false;}
  47. function remove_wp_help($old_help, $screen_id, $screen){
  48.     $screen->remove_help_tabs();
  49.     return $old_help;
  50. }
  51.  
  52. /*
  53.  * 固定后台管理侧边栏
  54.  */
  55. add_action('admin_head', 'Bing_fixed_adminmenuwrap');
  56. function Bing_fixed_adminmenuwrap(){
  57.     echo '<style type="text/css">#adminmenuwrap{position:fixed;left:0px;z-index:2;}</style>';
  58. };
  59.  
  60.  
  61. /*
  62.  * 阻止站内文章互相Pingback
  63.  */
  64. add_action('pre_ping','Bing_noself_ping');
  65. function Bing_noself_ping($links) {
  66.     $home = get_option( 'home' );
  67.     foreach ( $links as $l => $link )
  68.         if ( 0 === strpos( $link, $home ) )
  69.             unset($links[$l]);
  70. }
  71.  
  72. /*
  73.  * 增强默认编辑器(mce_buttons:工具栏的第一行;mce_buttons_2:工具栏第二行;mce_buttons_3:工具栏第三行)
  74.  */
  75. add_filter("mce_buttons", "Bing_editor_buttons");
  76. function Bing_editor_buttons($buttons){
  77.  
  78.     //$buttons[] = 'wp_adv';        //隐藏按钮显示开关
  79.     $buttons[] = 'wp_adv_start';    //隐藏按钮区起始部分
  80.     $buttons[] = 'wp_adv_end';      //隐藏按钮区结束部分
  81.     //$buttons[] = 'bold';          //加粗
  82.     //$buttons[] = 'italic';        //斜体
  83.     $buttons[] = 'underline';       //下划线
  84.     $buttons[] = 'strikethrough';   //删除线
  85.     $buttons[] = 'justifyleft';     //左对齐
  86.     $buttons[] = 'justifycenter';   //居中
  87.     $buttons[] = 'justfyright';     //右对齐
  88.     $buttons[] = 'justfyfull';      //两端对齐
  89.     //$buttons[] = 'bullist';       //无序列表
  90.     //$buttons[] = 'numlist';       //编号列表
  91.     $buttons[] = 'outdent';         //减少缩进
  92.     $buttons[] = 'indent';          //缩进
  93.     $buttons[] = 'cut';             //剪切
  94.     $buttons[] = 'copy';            //复制
  95.     $buttons[] = 'paste';           //粘贴
  96.     $buttons[] = 'undo';            //撤销
  97.     $buttons[] = 'redo';            //重做
  98.     //$buttons[] = 'link';          //插入超链接
  99.     $buttons[] = 'unlink';          //取消超链接
  100.     $buttons[] = 'image';           //插入图片
  101.     $buttons[] = 'removeformat';    //清除格式
  102.     $buttons[] = 'code';            //打开HTML代码编辑器
  103.     $buttons[] = 'hr';              //水平线
  104.     $buttons[] = 'cleanup';         //清除冗余代码
  105.     $buttons[] = 'formmatselect';   //格式选择
  106.     $buttons[] = 'fontselect';      //字体选择
  107.     $buttons[] = 'fontsizeselect';  //字号选择
  108.     $buttons[] = 'styleselect';     //样式选择
  109.     $buttons[] = 'sub';             //上标
  110.     $buttons[] = 'sup';             //下标
  111.     $buttons[] = 'forecolor';       //字体颜色
  112.     $buttons[] = 'backcolor';       //字体背景色
  113.     $buttons[] = 'charmap';         //特殊符号
  114.     $buttons[] = 'anchor';          //锚文本
  115.     $buttons[] = 'newdocument';     //新建文本
  116.     //$buttons[] = 'wp_more';       //插入more标签
  117.     $buttons[] = 'wp_page';         //插入分页标签
  118.     $buttons[] = 'spellchecker';    //拼写检查
  119.     $buttons[] = 'wp_help';         //帮助
  120.     //$buttons[] = 'selectall';       //全选
  121.     //$buttons[] = 'visualaid';       //显示/隐藏指导线和不可见元素
  122.     $buttons[] = 'spellchecker';    //切换拼写检查器状态
  123.     $buttons[] = 'pastetext';       //以纯文本粘贴
  124.     $buttons[] = 'pasteword';       //从Word中粘贴
  125.     //$buttons[] = 'blockquote';      //引用
  126.     $buttons[] = 'forecolorpicker'; //选择文字颜色(拾色器)
  127.     $buttons[] = 'backcolorpicker'; //选择背景颜色(拾色器)
  128.     $buttons[] = 'spellchecker';    //切换拼写检查器状态
  129.  
  130.     return $buttons;
  131. }
  132.  
  133. /*
  134.  * TinyMCE编辑器增强:增加中文字体
  135.  */
  136. add_filter('tiny_mce_before_init', 'custum_fontfamily');
  137. function custum_fontfamily($initArray){
  138.     $initArray['font_formats'] = "微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings";
  139.     return $initArray;
  140. }
  141.  
  142.  
  143. /*
  144.  * 更改编辑器默认视图为HTML
  145.  */
  146. //add_filter('wp_default_editor', create_function('', 'return "html";'));
  147.  
  148. /*
  149.  * 在 WordPress 编辑器中为自定义文章类型设置默认内容
  150.  */
  151. add_filter( 'default_content', 'my_editor_content', 10, 2 );
  152. function my_editor_content( $content, $post ) {
  153.     switch( $post->post_type ) {
  154.         case 'sources':
  155.             $content = 'your content';
  156.             break;
  157.         case 'stories':
  158.             $content = 'your content';
  159.             break;
  160.         case 'pictures':
  161.             $content = 'your content';
  162.             break;
  163.         default:
  164.             $content = 'your default content';
  165.             break;
  166.     }
  167.     return $content;
  168. }
  169.  
  170. /*
  171.  * 添加编辑器默认内容(此方法添加的内容在发布文章时自动添加在内容的最后,在编辑的时候是看不见的)
  172.  */
  173. add_filter ('the_content', 'insertFootNote');
  174. function insertFootNote($content) {
  175.     if(!is_feed() && !is_home()) {
  176.         $content.= "这里的预定义内容在编辑器不可见";
  177.     }
  178.     return $content;
  179. }
  180.  
  181. /*
  182.  * 为编辑器添加更多的HTML标签
  183.  */
  184. add_filter('tiny_mce_before_init', 'fb_change_mce_options');
  185. function fb_change_mce_options($initArray) {
  186.     $ext = 'pre[id|name|class|style],iframe[align|longdesc|name|width|height|frameborder|scrolling|marginheight|marginwidth|src]';  //注意:格式为“标签一[属性一|属性二],标签二[属性一|属性二|属性三]”
  187.     if ( isset( $initArray['extended_valid_elements'] ) ) {
  188.         $initArray['extended_valid_elements'] .= ',' . $ext;
  189.     } else {
  190.         $initArray['extended_valid_elements'] = $ext;
  191.     }
  192.     return $initArray;
  193. }
  194.  
  195. /*
  196.  * 让编辑器支持中文拼写检查
  197.  */
  198. add_filter('tiny_mce_before_init', 'fb_mce_external_languages');
  199. function fb_mce_external_languages($initArray){
  200.     $initArray['spellchecker_languages'] = '+Chinese=zh,English=en';
  201.     return $initArray;
  202. }
  203.  
  204.  
  205. /*
  206.  * 更改后台字体
  207.  */
  208. add_action('admin_head', 'Bing_admin_lettering');
  209. function Bing_admin_lettering(){
  210.     //echo '<style type="text/css">*{font-family:"Microsoft YaHei" !important;}</style>';//修改字体
  211. }
  212.  
  213. /*
  214.  * WordPress 后台回复评论添加提交快捷键[Ctrl+Enter]
  215.  */
  216. add_action('admin_footer', 'Bing_admin_comment_ctrlenter');
  217. function Bing_admin_comment_ctrlenter(){
  218.     echo '<script type="text/javascript">
  219.         jQuery(document).ready(function($){
  220.             $("textarea").keypress(function(e){
  221.                 if(e.ctrlKey&&e.which==13||e.which==10){
  222.                     $("#replybtn").click();
  223.                 }
  224.             });
  225.         });
  226.     </script>';
  227. };
  228.  
  229. /*
  230.  * WordPress 让后台用户列表可以根据文章数进行排序
  231.  */
  232. if ( ! class_exists('Sort_Users_By_Post_Count') ) {
  233.     class Sort_Users_By_Post_Count {
  234.         function Sort_Users_By_Post_Count() {
  235.             // Make user table sortable by post count
  236.             add_filter( 'manage_users_sortable_columns', array( $this, 'add_custom_user_sorts' ) );
  237.         }
  238.         /* Add sorting by post count to user page */
  239.         function add_custom_user_sorts( $columns ) {
  240.             $columns['posts'] = 'post_count';
  241.             return $columns;
  242.         }
  243.     }
  244.     $Sort_Users_By_Post_Count = new Sort_Users_By_Post_Count();
  245. }
  246.  
  247. /*
  248.  * WordPress 4.3+ 默认开启页面的评论功能
  249.  */
  250. add_filter( 'get_default_comment_status', 'wp33516_open_comments_for_pages', 10, 3 );
  251. function wp33516_open_comments_for_pages( $status, $post_type, $comment_type ) {
  252.     if ( 'page' === $post_type ) {
  253.         $status = 'open';
  254.     }
  255.     return $status;
  256. }
  257.  
  258. /*
  259.  * 将WordPress后台的open-sans字体加载源从Google Fonts换为360 CDN
  260.  */
  261. add_action( 'init', 'wpdx_replace_open_sans' );
  262. function wpdx_replace_open_sans() {
  263.     wp_deregister_style('open-sans');
  264.     wp_register_style( 'open-sans', '//fonts.useso.com/css?family=Open+Sans:300italic,400italic,600italic,300,400,600' );
  265.     if(is_admin()) wp_enqueue_style( 'open-sans');
  266. }
  267.  
  268. /*
  269.  * WordPress 关闭 XML-RPC 的 pingback 端口
  270.  */
  271. add_filter( 'xmlrpc_methods', 'remove_xmlrpc_pingback_ping' );
  272. function remove_xmlrpc_pingback_ping( $methods ) {
  273.     unset( $methods['pingback.ping'] );
  274.     return $methods;
  275. }
  276.  
  277. /*
  278.  * 禁用 WordPress 的 JSON REST API
  279.  */
  280. add_filter('json_enabled', '__return_false');
  281. add_filter('json_jsonp_enabled', '__return_false');
  282.  
  283. /*
  284.  * 禁止WordPress压缩JGP图片质量
  285.  */
  286. add_filter( 'jpg_quality', 'high_jpg_quality' );
  287. function high_jpg_quality() {
  288.     return 100;
  289. }
  290.  
  291.  
  292. /*
  293.  * WordPress 隐藏特定插件的更新提示
  294.  */
  295. //add_filter( 'site_transient_update_plugins', 'filter_plugin_updates' );
  296. function filter_plugin_updates( $value ) {
  297.     unset( $value->response['plugin-directory/plugin-file.php'] );
  298.     return $value;
  299. }
  300.  
  301.  
  302. /*
  303.  * 隐藏核心更新提示 WP 3.0+
  304.  */
  305. //add_filter( 'pre_site_transient_update_core', create_function( '$a', "return null;" ) );
  306.  
  307. /*
  308.  * 隐藏插件更新提示 WP 3.0+
  309.  */
  310. //remove_action( 'load-update-core.php', 'wp_update_plugins' );
  311. //add_filter( 'pre_site_transient_update_plugins', create_function( '$b', "return null;" ) );
  312.  
  313. /*
  314.  * 隐藏主题更新提示 WP 3.0+
  315.  */
  316. //remove_action( 'load-update-core.php', 'wp_update_themes' );
  317. //add_filter( 'pre_site_transient_update_themes', create_function( '$c', "return null;" ) );
  318.  
  319. /*
  320.  * 为新用户预设默认的后台配色方案
  321.  */
  322. add_action('user_register', 'set_default_admin_color');
  323. function set_default_admin_color($user_id) {
  324.     $args = array(
  325.         'ID' => $user_id,
  326.         'admin_color' => 'sunrise'
  327.     );
  328.     wp_update_user( $args );
  329. }
  330.  
  331. /*
  332.  * 对非管理员移除配色方案设置选项
  333.  */
  334. if ( !current_user_can('manage_options') ){
  335.     remove_action( 'admin_color_scheme_picker', 'admin_color_scheme_picker' );
  336. }
  337.  
  338. /*
  339.  * 移除 WordPress 仪表盘欢迎面板
  340.  */
  341. //remove_action('welcome_panel', 'wp_welcome_panel');
  342.  
  343. /*
  344.  * 自定义 WordPress 仪表盘欢迎面板
  345.  */
  346. //add_action( 'welcome_panel', 'rc_my_welcome_panel' );
  347. function rc_my_welcome_panel() {
  348.     ?>
  349.     <script type="text/javascript">
  350.         /* 隐藏默认的欢迎信息 */
  351.         jQuery(document).ready( function($)
  352.         {
  353.             $('div.welcome-panel-content').hide();
  354.         });
  355.     </script>
  356.     <!-- 添加自定义信息 -->
  357.     <div class="custom-welcome-panel-content">
  358.         <h2><?php _e( '欢迎使用WordPress!' ); ?></h2>
  359.         <p class="about-description"><?php _e( '我们准备了几个链接供您开始:' ); ?></p>
  360.         <div class="welcome-panel-column-container">
  361.             <div class="welcome-panel-column">
  362.                 <h3 style="font-weight: bold"><?php _e( "开始使用" ); ?></h3>
  363.                 <a class="button button-primary button-hero load-customize hide-if-no-customize" href="http://www.ankium.com"><?php _e( '联系我们' ); ?></a>
  364.                 <p class="hide-if-no-customize"><?php printf( __( '或者 <a href="%s">设置网站</a>' ), admin_url( 'options-general.php' ) ); ?></p>
  365.             </div>
  366.             <div class="welcome-panel-column">
  367.                 <h4><?php _e( 'Next Steps' ); ?></h4>
  368.                 <ul>
  369.                     <?php if ( 'page' == get_option( 'show_on_front' ) && ! get_option( 'page_for_posts' ) ) : ?>
  370.                         <li><?php printf( '<a href="%s" class="welcome-icon welcome-edit-page">' . __( 'Edit your front page' ) . '</a>', get_edit_post_link( get_option( 'page_on_front' ) ) ); ?></li>
  371.                         <li><?php printf( '<a href="%s" class="welcome-icon welcome-add-page">' . __( 'Add additional pages' ) . '</a>', admin_url( 'post-new.php?post_type=page' ) ); ?></li>
  372.                     <?php elseif ( 'page' == get_option( 'show_on_front' ) ) : ?>
  373.                         <li><?php printf( '<a href="%s" class="welcome-icon welcome-edit-page">' . __( 'Edit your front page' ) . '</a>', get_edit_post_link( get_option( 'page_on_front' ) ) ); ?></li>
  374.                         <li><?php printf( '<a href="%s" class="welcome-icon welcome-add-page">' . __( 'Add additional pages' ) . '</a>', admin_url( 'post-new.php?post_type=page' ) ); ?></li>
  375.                         <li><?php printf( '<a href="%s" class="welcome-icon welcome-write-blog">' . __( 'Add a blog post' ) . '</a>', admin_url( 'post-new.php' ) ); ?></li>
  376.                     <?php else : ?>
  377.                         <li><?php printf( '<a href="%s" class="welcome-icon welcome-write-blog">' . __( 'Write your first blog post' ) . '</a>', admin_url( 'post-new.php' ) ); ?></li>
  378.                         <li><?php printf( '<a href="%s" class="welcome-icon welcome-add-page">' . __( 'Add an About page' ) . '</a>', admin_url( 'post-new.php?post_type=page' ) ); ?></li>
  379.                     <?php endif; ?>
  380.                     <li><?php printf( '<a href="%s" class="welcome-icon welcome-view-site">' . __( 'View your site' ) . '</a>', home_url( '/' ) ); ?></li>
  381.                 </ul>
  382.             </div>
  383.             <div class="welcome-panel-column welcome-panel-last">
  384.                 <h4><?php _e( 'More Actions' ); ?></h4>
  385.                 <ul>
  386.                     <li><?php printf( '<div class="welcome-icon welcome-widgets-menus">' . __( 'Manage <a href="%1$s">widgets</a> or <a href="%2$s">menus</a>' ) . '</div>', admin_url( 'widgets.php' ), admin_url( 'nav-menus.php' ) ); ?></li>
  387.                     <li><?php printf( '<a href="%s" class="welcome-icon welcome-comments">' . __( 'Turn comments on or off' ) . '</a>', admin_url( 'options-discussion.php' ) ); ?></li>
  388.                     <li><?php printf( '<a href="%s" class="welcome-icon welcome-learn-more">' . __( 'Learn more about getting started' ) . '</a>', __( 'http://codex.wordpress.org/First_Steps_With_WordPress' ) ); ?></li>
  389.                 </ul>
  390.             </div>
  391.         </div>
  392.         <div class="">
  393.             <h3><?php _e( '关于我们' ); ?></h3>
  394.             <!--<p class="about-description">延安安琪云信息科技有限公司</p>-->
  395.             <p>延安安琪云信息科技有限公司成立于2017年10月23日,是陕北地区新兴的互联网综合服务提供商。公司业务涉及网络工程、软件设计、电子商务、电子政务、数据维护及品牌网站定制开发。我们的目标是成为广大客户值得信赖的互联网综合解决方案提供商!</p>
  396.         </div>
  397.     </div>
  398.     <?php
  399. }
  400.  
  401.  
  402. /*
  403.  * WordPress 限制非管理员用户上传图片的最小宽度和高度
  404.  */
  405. add_action( 'admin_init', 'block_authors_from_uploading_small_images' );
  406. function block_authors_from_uploading_small_images(){
  407.     //除管理员以外,其他用户都限制
  408.     if( !current_user_can( 'manage_options') )
  409.         add_filter( 'wp_handle_upload_prefilter', 'block_small_images_upload' );
  410. }
  411. function block_small_images_upload( $file ){
  412.     // 检测文件的类型是否是图片
  413.     $mimes = array( 'image/jpeg', 'image/png', 'image/gif' );
  414.     // 如果不是图片,直接返回文件
  415.     if( !in_array( $file['type'], $mimes ) )
  416.         return $file;
  417.  
  418.     $img = getimagesize( $file['tmp_name'] );
  419.     // 设置最小宽度和高度
  420.     $minimum = array( 'width' => 640, 'height' => 480 );
  421.  
  422.     if ( $img[0] < $minimum['width'] )
  423.         $file['error'] =
  424.             '图片太小了,最小宽度是 '
  425.             . $minimum['width']
  426.             . 'px,当前上传的图片宽度是 '
  427.             . $img[0] . 'px';
  428.  
  429.     elseif ( $img[1] < $minimum['height'] )
  430.         $file['error'] =
  431.             '图片太小了,最小高度是 '
  432.             . $minimum['height']
  433.             . 'px,当前上传的图片高度是 '
  434.             . $img[1] . 'px';
  435.  
  436.     return $file;
  437. }
  438.  
  439.  
  440. /*
  441.  * WordPress 后台用户列表显示注册时间
  442.  */
  443. add_filter( 'manage_users_columns', array('RRHE','registerdate'));
  444. add_action( 'manage_users_custom_column',  array('RRHE','registerdate_columns'), 15, 3);
  445. add_filter( 'manage_users_sortable_columns', array('RRHE','registerdate_column_sortable') );
  446. add_filter( 'request', array('RRHE','registerdate_column_orderby') );
  447. class RRHE {
  448.     // Register the column - Registered
  449.     public static function registerdate($columns) {
  450.         $columns['registerdate'] = __('注册时间', 'registerdate');
  451.         return $columns;
  452.     }
  453.  
  454.     // Display the column content
  455.     public static function registerdate_columns( $value, $column_name, $user_id ) {
  456.         if ( 'registerdate' != $column_name )
  457.             return $value;
  458.         $user = get_userdata( $user_id );
  459.         $registerdate = get_date_from_gmt($user->user_registered);
  460.         return $registerdate;
  461.     }
  462.  
  463.     public static function registerdate_column_sortable($columns) {
  464.         $custom = array(
  465.             // meta column id => sortby value used in query
  466.             'registerdate'    => 'registered',
  467.         );
  468.         return wp_parse_args($custom, $columns);
  469.     }
  470.  
  471.     public static function registerdate_column_orderby( $vars ) {
  472.         if ( isset( $vars['orderby'] ) && 'registerdate' == $vars['orderby'] ) {
  473.             $vars = array_merge( $vars, array(
  474.                 'meta_key' => 'registerdate',
  475.                 'orderby' => 'meta_value'
  476.             ) );
  477.         }
  478.         return $vars;
  479.     }
  480.  
  481. }
  482.  
  483.  
  484. /*
  485.  * 在WordPress插件管理界面隐藏已启用的插件(包括管理员)
  486.  */
  487. //add_filter( 'all_plugins', 'hide_plugins');
  488. function hide_plugins($plugins)
  489. {
  490.     // 隐藏 你好,多莉 插件
  491.     if(is_plugin_active('hello.php')) {
  492.         unset( $plugins['hello.php'] );
  493.     }
  494.     // 隐藏 post series插件
  495.     if(is_plugin_active('ankium/ankium.php')) {
  496.         unset( $plugins['ankium/ankium.php'] );
  497.     }
  498.     return $plugins;
  499. }
  500.  
  501. /*
  502.  * 在WordPress插件管理界面隐藏已启用的插件(除指定用户)
  503.  */
  504. add_filter('all_plugins', 'filter_visible_plugins');
  505. function filter_visible_plugins($plugins) {
  506.     //添加插件的相对于 /wp-content/plugins/ 的路径
  507.     $pluginsToHide = array(
  508.         'hello.php',
  509.         'ankium/ankium.php'
  510.     );
  511.     //在这个例子中,我们对所有用户隐藏插件,除了用户 smith
  512.     $currentUser = wp_get_current_user();
  513.     $shouldHide = $currentUser->get('user_login') != 'ankium';
  514.  
  515.     if ( $shouldHide ) {
  516.         foreach($pluginsToHide as $pluginFile) {
  517.             unset($plugins[$pluginFile]);
  518.         }
  519.     }
  520.     return $plugins;
  521. }
  522.  
  523.  
  524. /*
  525.  * WordPress 移除插件列表所有已启用插件的“编辑”和“停用”链接
  526.  */
  527. //add_filter( 'plugin_action_links', 'remove_all_plugin_actions', 10, 4 );
  528. function remove_all_plugin_actions( $actions, $plugin_file, $plugin_data, $context )
  529. {
  530.     // 移除所有“编辑”链接
  531.     if ( isset( $actions['edit'] ) )
  532.     {
  533.         unset( $actions['edit'] );
  534.     }
  535.     // 移除插件的“停用”链接
  536.     if( isset( $actions['deactivate'] ) )
  537.     {
  538.         unset( $actions['deactivate'] );
  539.     }
  540.     return $actions;
  541. }
  542.  
  543.  
  544. /*
  545.  * WordPress 移除插件列表已启用特定插件的“编辑”和“停用”链接
  546.  */
  547. //add_filter( 'plugin_action_links', 'remove_plugin_actions', 10, 4 );
  548. function remove_plugin_actions( $actions, $plugin_file, $plugin_data, $context )
  549. {
  550.     // 移除所有“编辑”链接
  551.     if ( isset( $actions['edit'] ) )
  552.     {
  553.         unset( $actions['edit'] );
  554.     }
  555.     // 移除插件的“停用”链接
  556.     if( isset( $actions['deactivate'] ) )
  557.     {
  558.         switch($plugin_file)
  559.         {
  560.             // 添加插件的主文件目录
  561.             case 'hello.php': // 注意结尾是英文冒号
  562.                 unset( $actions['deactivate'] );
  563.                 break;
  564.         }
  565.     }
  566.     return $actions;
  567. }
  568.  
  569.  
  570. /*
  571.  * WordPress 禁用自定义文章类型的可视化编辑器
  572.  */
  573. //add_filter( 'user_can_richedit', 'disable_wysiwyg_editor_for_cpt' );
  574. function disable_wysiwyg_editor_for_cpt( $default ) {
  575.     global $post;
  576.     if ( get_post_type( $post ) == 'question') // 请修改 question 为你的文章类型
  577.         return false;
  578.     return $default;
  579. }
  580.  
  581.  
  582. /*
  583.  * WordPress 仪表盘显示待审核的文章列表
  584.  */
  585. add_action('wp_dashboard_setup', 'wpjam_modify_dashboard_widgets' );
  586. function wpjam_modify_dashboard_widgets() {
  587.     global $wp_meta_boxes;
  588.  
  589.     if(current_user_can('manage_options')){ //只有管理员才能看到
  590.         add_meta_box( 'pending_posts_dashboard_widget', '待审文章', 'pending_posts_dashboard_widget_function','dashboard', 'normal', 'core' );
  591.     }
  592. }
  593. function pending_posts_dashboard_widget_function() {
  594.     global $wpdb;
  595.     $pending_posts = $wpdb->get_results("SELECT * FROM {$wpdb->posts}  WHERE post_status = 'pending' ORDER BY post_modified DESC");
  596.  
  597.     if($pending_posts){ //判断是否有待审文章
  598.         echo '<ul>';
  599.         foreach ($pending_posts as $pending_post){
  600.             echo '<li><a href="'.admin_url().'post.php?post='.$pending_post->ID.'&action=edit">'.$pending_post->post_title.'</a></li>';
  601.         }
  602.         echo '</ul>';
  603.     }else echo '目前没有待审文章';
  604. }
  605.  
  606.  
  607. /*
  608.  * WordPress 仪表盘“近期评论”显示完整评论内容和格式
  609.  */
  610. //add_filter('comment_excerpt', 'full_comments_on_dashboard');
  611. function full_comments_on_dashboard($excerpt) {
  612.     global $comment;
  613.  
  614.     if ( !is_admin() )
  615.         return $excerpt;
  616.  
  617.     $content = wpautop($comment->comment_content);
  618.     $content = substr($content, 3, -5); // 移除第一个 <p> 和最后一个 </p>
  619.     $content = str_replace('<p>', '<p style="display:block; margin:1em 0">', $content);
  620.  
  621.     return $content;
  622. }
  623.  
  624.  
  625. /*
  626.  * WordPress 后台文章列表根据文章状态添加不同背景色
  627.  */
  628. add_action('admin_footer','posts_status_color');
  629. function posts_status_color(){
  630.     ?>
  631.     <style>
  632.         .status-draft{background: #FCE3F2 !important;/*草稿*/}
  633.         .status-pending{background: #87C5D6 !important;/*待审核*/}
  634.         .status-publish{/* 已发布,使用默认背景色,你也可以自己添加颜色 */}
  635.         .status-future{background: #C6EBF5 !important;/*定时发布*/}
  636.         .status-private{background:#F2D46F;/*私密日志*/}
  637.         .post-password-required{background:#D874DE;/*密码保护*/}
  638.     </style>
  639.     <?php
  640. }
  641.  
  642.  
  643. /*
  644.  * 更改标题输入框提示文字
  645.  */
  646. add_filter( 'enter_title_here', 'change_default_title' );
  647. function change_default_title( $title ){
  648.     $screen = get_current_screen();
  649.  
  650.     if( 'post' == $screen->post_type ) {
  651.         $title = '输入文章标题';
  652.     } elseif ('page' == $screen->post_type) {
  653.         $title = '输入页面标题';
  654.     } elseif ('book' == $screen->post_type) {
  655.         $title = '输入书籍标题';
  656.     }
  657.  
  658.     return $title;
  659. }
  660.  
  661. /*
  662.  * 让WordPress记住不同主题下所选择的的页面模板
  663.  */
  664. add_action( "updated_post_meta", "rmt_update_post_template_meta", 10, 4 );
  665. add_action( "added_post_meta", "rmt_update_post_template_meta", 10, 4 );
  666. function rmt_update_post_template_meta( $meta_id, $post_id, $meta_key, $meta_value ){
  667.  
  668.     if( '_wp_page_template' === $meta_key ){
  669.  
  670.         $theme = wp_get_theme();
  671.         $name = $theme->template;
  672.         if( $name ){
  673.             update_post_meta( $post_id, '_wp_page_template_' . $name, $meta_value );
  674.         }
  675.  
  676.     }
  677.  
  678. }
  679. add_filter( 'get_post_metadata', 'rmt_get_post_template_meta', 10, 4 );
  680. function rmt_get_post_template_meta( $value, $post_id, $meta_key, $single ){
  681.  
  682.     if( '_wp_page_template' === $meta_key ){
  683.  
  684.         $theme = wp_get_theme();
  685.         $name = $theme->template;
  686.  
  687.         if( $name ){
  688.             $template = get_post_meta( $post_id, '_wp_page_template_' . $name, $single );
  689.             if( $template  && locate_template( $template ) ){
  690.                 $value = $template;
  691.             }
  692.         }
  693.  
  694.     }
  695.  
  696.     return $value;
  697. }
  698.  
  699.  
  700. /*
  701.  * 在媒体库显示文件尺寸
  702.  */
  703. //add_filter('manage_upload_columns', 'size_column_register');
  704. function size_column_register($columns) {
  705.     $columns['dimensions'] = __('Dimensions');
  706.     return $columns;
  707. }
  708. //add_action('manage_media_custom_column', 'size_column_display', 10, 2);
  709. function size_column_display($column_name, $post_id) {
  710.     if( 'dimensions' != $column_name || !wp_attachment_is_image($post_id))
  711.         return;
  712.     list($url, $width, $height) = wp_get_attachment_image_src($post_id, 'full');
  713.     echo esc_html("{$width}×{$height}");
  714. }
  715.  
  716. /*
  717.  * 在媒体编辑页面显示文件大小
  718.  */
  719. //add_action( 'attachment_submitbox_misc_actions', 'mc_attachment_submitbox_filesize' );
  720. function mc_attachment_submitbox_filesize() {
  721.     $post = get_post();
  722.     $filesize = @filesize( get_attached_file( $post->ID ) );
  723.  
  724.     if ( ! empty( $filesize ) && is_numeric( $filesize ) && $filesize > 0 ) : ?>
  725.         <div class="misc-pub-section">
  726.             <?php _e( '文件大小:' ); ?> <strong><?php echo size_format( $filesize ); ?></strong>
  727.         </div>
  728.     <?php
  729.     endif;
  730. }
  731.  
  732. /*
  733.  * 让WordPress后台用户列表可以搜索名字、姓氏和公开显示名
  734.  */
  735. if (is_admin()) {//让函数只应用于WordPress后台
  736.     //通过钩子挂载函数
  737.     add_action('pre_user_query', 'wpdaxue_pre_user_query');
  738. }
  739. function wpdaxue_pre_user_query($user_search) {
  740.     global $wpdb;
  741.     $vars = $user_search->query_vars;
  742.     if (!is_null($vars['search'])) {
  743.         // 出于某种原因,搜索词被星号包括,删除它们
  744.         $search = preg_replace('/^\*/', '', $vars['search']);
  745.         $search = preg_replace('/\*$/', '', $search);
  746.  
  747.         //搜索公开显示名
  748.         if(!empty($search)){
  749.             $user_search->query_where = substr(trim($user_search->query_where), 0, -1) . " OR display_name LIKE '%". $search . "%')";
  750.         }
  751.         //搜索名字和姓氏
  752.         $user_search->query_from .= " INNER JOIN {$wpdb->usermeta} m1 ON " .
  753.             "{$wpdb->users}.ID=m1.user_id AND (m1.meta_key='first_name')";
  754.         $user_search->query_from .= " INNER JOIN {$wpdb->usermeta} m2 ON " .
  755.             "{$wpdb->users}.ID=m2.user_id AND (m2.meta_key='last_name')";
  756.         $names_where = $wpdb->prepare("m1.meta_value LIKE '%s' OR m2.meta_value LIKE '%s'", "%{$search}%", "%$search%");
  757.         $user_search->query_where = str_replace('WHERE 1=1 AND (', "WHERE 1=1 AND ({$names_where} OR ", $user_search->query_where);
  758.     }
  759.     return $user_search;
  760. }
  761.  
  762. /*
  763.  * 为WordPress后台的文章、分类等显示ID
  764.  */
  765. add_action('admin_init', 'ssid_add');
  766. // 添加一个新的列 ID
  767. function ssid_column($cols) {
  768.     $cols['ssid'] = 'ID';
  769.     return $cols;
  770. }
  771. // 显示 ID
  772. function ssid_value($column_name, $id) {
  773.     if ($column_name == 'ssid')
  774.         echo $id;
  775. }
  776. function ssid_return_value($value, $column_name, $id) {
  777.     if ($column_name == 'ssid')
  778.         $value = $id;
  779.     return $value;
  780. }
  781. // 为 ID 这列添加css
  782. function ssid_css() {
  783.     ?>
  784.     <style type="text/css">
  785.         #ssid { width: 50px; } /* Simply Show IDs */
  786.     </style>
  787.     <?php
  788. }
  789. // 通过动作/过滤器输出各种表格和CSS
  790. function ssid_add() {
  791.     add_action('admin_head', 'ssid_css');
  792.  
  793.     add_filter('manage_posts_columns', 'ssid_column');
  794.     add_action('manage_posts_custom_column', 'ssid_value', 10, 2);
  795.  
  796.     add_filter('manage_pages_columns', 'ssid_column');
  797.     add_action('manage_pages_custom_column', 'ssid_value', 10, 2);
  798.  
  799.     add_filter('manage_media_columns', 'ssid_column');
  800.     add_action('manage_media_custom_column', 'ssid_value', 10, 2);
  801.  
  802.     add_filter('manage_link-manager_columns', 'ssid_column');
  803.     add_action('manage_link_custom_column', 'ssid_value', 10, 2);
  804.  
  805.     add_action('manage_edit-link-categories_columns', 'ssid_column');
  806.     add_filter('manage_link_categories_custom_column', 'ssid_return_value', 10, 3);
  807.  
  808.     foreach ( get_taxonomies() as $taxonomy ) {
  809.         add_action("manage_edit-${taxonomy}_columns", 'ssid_column');
  810.         add_filter("manage_${taxonomy}_custom_column", 'ssid_return_value', 10, 3);
  811.     }
  812.  
  813.     add_action('manage_users_columns', 'ssid_column');
  814.     add_filter('manage_users_custom_column', 'ssid_return_value', 10, 3);
  815.  
  816.     add_action('manage_edit-comments_columns', 'ssid_column');
  817.     add_action('manage_comments_custom_column', 'ssid_value', 10, 2);
  818. }
  819.  
  820.  
  821. /*
  822.  * 为WordPress页面添加标签和分类
  823.  */
  824.  
  825. class PTCFP{
  826.  
  827.     function __construct(){
  828.         add_action( 'init', array( $this, 'taxonomies_for_pages' ) );
  829.         //确保这些查询修改不会作用于管理后台,防止文章和页面混杂
  830.         if ( ! is_admin() ) {
  831.             add_action( 'pre_get_posts', array( $this, 'category_archives' ) );
  832.             add_action( 'pre_get_posts', array( $this, 'tags_archives' ) );
  833.         }
  834.     }
  835.  
  836.     //为“页面”添加“标签”和“分类”
  837.     function taxonomies_for_pages() {
  838.         register_taxonomy_for_object_type( 'post_tag', 'page' );
  839.         register_taxonomy_for_object_type( 'category', 'page' );
  840.     }
  841.  
  842.     //在标签存档中包含“页面”
  843.     function tags_archives( $wp_query ) {
  844.         if ( $wp_query->get( 'tag' ) )
  845.             $wp_query->set( 'post_type', 'any' );
  846.     }
  847.  
  848.     //在分类存档中包含“页面”
  849.     function category_archives( $wp_query ) {
  850.         if ( $wp_query->get( 'category_name' ) || $wp_query->get( 'cat' ) )
  851.             $wp_query->set( 'post_type', 'any' );
  852.     }
  853.  
  854. }
  855.  
  856. $ptcfp = new PTCFP();
  857.  
  858. /*
  859.  * 限制文章标题输入字数
  860.  */
  861. //add_action( 'admin_head-post.php', 'title_count_js');
  862. //add_action( 'admin_head-post-new.php', 'title_count_js');
  863. function title_count_js(){
  864.     echo '<script>jQuery(document).ready(function(){
  865.     jQuery("#titlewrap").after("<div><small>标题字数: </small><input type=\"text\" value=\"0\" maxlength=\"3\" size=\"3\" id=\"title_counter\" readonly=\"\" style=\"background:#fff;\"> <small>最大长度不得超过 46 个字</small></div>");
  866.     jQuery("#title_counter").val(jQuery("#title").val().length);
  867.     jQuery("#title").keyup( function() {
  868.     jQuery("#title_counter").val(jQuery("#title").val().length);
  869.     });
  870.     jQuery("#titlewrap #title").keyup( function() {
  871.     var $this = jQuery(this);
  872.     if($this.val().length > 46)
  873.     $this.val($this.val().substr(0, 46));
  874.     });
  875. });</script>';
  876. }
  877.  
  878. /*
  879.  * 自定义排序WordPress后台管理菜单
  880.  */
  881. //add_filter('custom_menu_order', 'custom_menu_order');
  882. //add_filter('menu_order', 'custom_menu_order');
  883. function custom_menu_order($menu_ord) {
  884.     if (!$menu_ord) return true;
  885.     return array(
  886.         'index.php', // “仪表盘”菜单
  887.         'edit.php?post_type=question', // 自定义文章类型的菜单
  888.         'edit-comments.php', //“评论”菜单
  889.         'upload.php', //“多媒体”菜单
  890.         'edit.php?post_type=cmp_slider', //自定义文章类型的菜单
  891.         'plugins.php', //“插件”菜单
  892.         'themes.php', //“主题”菜单
  893.         'edit.php?post_type=page', // “页面”菜单
  894.         'edit.php', // “文章”菜单
  895.     );
  896. }
  897.  
  898. /*
  899.  * 在WordPress仪表盘“概况”显示自定义文章类型数据
  900.  */
  901. add_action( 'right_now_content_table_end' , 'wph_right_now_content_table_end' );
  902. function wph_right_now_content_table_end() {
  903.     $args = array(
  904.         'public' => true ,
  905.         '_builtin' => false
  906.     );
  907.     $output = 'object';
  908.     $operator = 'and';
  909.     $post_types = get_post_types( $args , $output , $operator );
  910.     foreach( $post_types as $post_type ) {
  911.         $num_posts = wp_count_posts( $post_type->name );
  912.         $num = number_format_i18n( $num_posts->publish );
  913.         $text = _n( $post_type->labels->singular_name, $post_type->labels->name , intval( $num_posts->publish ) );
  914.         if ( current_user_can( 'edit_posts' ) ) {
  915.             $num = "<a href='edit.php?post_type=$post_type->name'>$num</a>";
  916.             $text = "<a href='edit.php?post_type=$post_type->name'>$text</a>";
  917.         }
  918.         echo '<tr><td class="first num b b-' . $post_type->name . '">' . $num . '</td>';
  919.         echo '<td class="text t ' . $post_type->name . '">' . $text . '</td></tr>';
  920.     }
  921.     $taxonomies = get_taxonomies( $args , $output , $operator );
  922.     foreach( $taxonomies as $taxonomy ) {
  923.         $num_terms  = wp_count_terms( $taxonomy->name );
  924.         $num = number_format_i18n( $num_terms );
  925.         $text = _n( $taxonomy->labels->singular_name, $taxonomy->labels->name , intval( $num_terms ));
  926.         if ( current_user_can( 'manage_categories' ) ) {
  927.             $num = "<a href='edit-tags.php?taxonomy=$taxonomy->name'>$num</a>";
  928.             $text = "<a href='edit-tags.php?taxonomy=$taxonomy->name'>$text</a>";
  929.         }
  930.         echo '<tr><td class="first b b-' . $taxonomy->name . '">' . $num . '</td>';
  931.         echo '<td class="t ' . $taxonomy->name . '">' . $text . '</td></tr>';
  932.     }
  933. }
  934.  
  935. /*
  936.  * 仪表盘[活动]小工具输出自定义文章类型
  937.  */
  938. if ( is_admin() ) {
  939.     add_filter( 'dashboard_recent_posts_query_args', 'wpdx_add_cpt_to_dashboard_activity' );
  940.     function wpdx_add_cpt_to_dashboard_activity( $query ) {
  941.         // 如果你要显示所有文章类型,就删除下行的 //,并在 11 行前面添加 //
  942.         // $post_types = get_post_types();
  943.         // 如果你仅仅希望显示指定的文章类型,可以修改下行的数组内容,并确保上行前面添加 //
  944.         $post_types = ['post', 'download'];
  945.         if ( is_array( $query['post_type'] ) ) {
  946.             $query['post_type'] = $post_types;
  947.         } else {
  948.             $temp = $post_types;
  949.             $query['post_type'] = $temp;
  950.         }
  951.         return $query;
  952.     }
  953. }
  954.  
  955. /*
  956.  * 显示所有设置菜单
  957.  */
  958. add_action('admin_menu', 'all_settings_link');
  959. function all_settings_link() {
  960.     add_options_page(__('All Settings'), __('All Settings'), 'administrator', 'options.php');
  961. }
  962.  
  963. /*
  964.  * 在WordPress后台文章编辑器的上方或下方添加提示内容
  965.  */
  966. add_action( 'edit_form_after_title', 'below_the_title' );
  967. function below_the_title() {
  968.     echo '<h3>在编辑器上方添加的提示内容</h3>';
  969. }
  970. add_action( 'edit_form_after_editor', 'below_the_editor' );
  971. function below_the_editor() {
  972.     echo '<h4>在编辑器下方添加的提示内容</h4>';
  973. }
  974.  
  975. /*
  976.  * 在后台页面管理列表中隐藏特定的页面
  977.  */
  978. add_action( 'pre_get_posts' ,'exclude_this_page' );
  979. function exclude_this_page( $query ) {
  980.     if( !is_admin() )
  981.         return $query;
  982.     global $pagenow;
  983.     if( 'edit.php' == $pagenow && ( get_query_var('post_type') && 'page' == get_query_var('post_type') ) )
  984.         $query->set( 'post__not_in', array(23,28,30) ); // 页面的ID
  985.     return $query;
  986. }
  987.  
  988. /*
  989.  * 修改 WordPress 发送邮件的默认邮箱和发件人
  990.  */
  991. add_filter('wp_mail_from_name', 'new_from_name');
  992. add_filter('wp_mail_from', 'new_from_email');
  993. function new_from_name($email){//默认发件人
  994.     $wp_from_name = get_option('blogname');
  995.     return $wp_from_name;
  996. }
  997. function new_from_email($email) {//默认发件箱
  998.     $wp_from_email = get_option('admin_email');
  999.     return $wp_from_email;
  1000. }
  1001.  
  1002. /*
  1003.  * WordPress仪表盘添加自定义Feed订阅
  1004.  */
  1005. add_action('wp_dashboard_setup', 'ankium_add_dashboard_widgets' );
  1006. function dashboard_custom_feed_output() {
  1007.     echo '<div class="rss-widget">';
  1008.     wp_widget_rss_output(array(
  1009.         'url' => 'http://www.ankium.com/feed/', //rss地址
  1010.         'title' => '查看安琪云的最新内容',
  1011.         'items' => 10,         //显示篇数
  1012.         'show_summary' => 0,  //是否显示摘要,1为显示
  1013.         'show_author' => 0,   //是否显示作者,1为显示
  1014.         'show_date' => 1  )); //是否显示日期
  1015.     echo '</div>';
  1016. }
  1017. function ankium_add_dashboard_widgets() {
  1018.     wp_add_dashboard_widget('example_dashboard_widget', '安琪云', 'dashboard_custom_feed_output');
  1019. }
  1020.  
  1021. /*
  1022.  * 自定义WordPress图片附件的默认链接方式(’none’,’file’,’post’)
  1023.  */
  1024. update_option('image_default_link_type', 'file');
  1025.  
  1026. /*
  1027.  * 关闭WordPress的XML-RPC离线发布功能
  1028.  */
  1029. add_filter('xmlrpc_enabled', '__return_false');
  1030.  
  1031. /*
  1032.  * 恢复WordPress默认上传路径和生成文件的URL地址
  1033.  */
  1034. if(get_option('upload_path')=='wp-content/uploads' || get_option('upload_path')==null) {
  1035.     update_option('upload_path',WP_CONTENT_DIR.'/uploads');
  1036. }
  1037.  
  1038. /*
  1039.  * 自定义WordPress媒体文件的上传路径和生成文件的URL地址
  1040.  */
  1041. //add_filter( 'upload_dir', 'wpjam_custom_upload_dir' );
  1042. function wpjam_custom_upload_dir( $uploads ) {
  1043.     $upload_path = '';
  1044.     $upload_url_path = '';
  1045.  
  1046.     if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) {
  1047.         $uploads['basedir']  = WP_CONTENT_DIR . '/uploads';
  1048.     } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) {
  1049.         $uploads['basedir'] = path_join( ABSPATH, $upload_path );
  1050.     } else {
  1051.         $uploads['basedir'] = $upload_path;
  1052.     }
  1053.  
  1054.     $uploads['path'] = $uploads['basedir'].$uploads['subdir'];
  1055.  
  1056.     if ( $upload_url_path ) {
  1057.         $uploads['baseurl'] = $upload_url_path;
  1058.         $uploads['url'] = $uploads['baseurl'].$uploads['subdir'];
  1059.     }
  1060.     return $uploads;
  1061. }
  1062.  
  1063. /*
  1064.  * WordPress 后台管理员免密一键切换其他账号登录
  1065.  */
  1066. add_filter('user_row_actions', 'wpdx_user_switch_action', 10, 2);
  1067. function wpdx_user_switch_action($actions, $user){
  1068.     $capability = (is_multisite())?'manage_site':'manage_options';
  1069.     if(current_user_can($capability)){
  1070.         $actions['login_as'] = '<a title="以此身份登录" href="'.wp_nonce_url("users.php?action=login_as&users=$user->ID", 'bulk-users').'">以此身份登录</a>';
  1071.     }
  1072.     return $actions;
  1073. }
  1074. add_filter('handle_bulk_actions-users','wpdx_handle_user_switch_action', 10, 3);
  1075. function wpdx_handle_user_switch_action($sendback, $action, $user_ids){
  1076.     if($action == 'login_as'){
  1077.         wp_set_auth_cookie($user_ids, true);
  1078.         wp_set_current_user($user_ids);
  1079.     }
  1080.     return admin_url();
  1081. }
  1082.  
  1083. /*
  1084.  * WordPress自定义文章作者名称
  1085.  */
  1086. add_action('post_submitbox_misc_actions', 'cus_author_createCustomField');
  1087. add_action('save_post', 'cus_author_saveCustomField');
  1088. add_filter('the_author','cus_author_the_author');
  1089. /** 创建一个checkBox */
  1090. function cus_author_createCustomField() {
  1091.     $post_id = get_the_ID();
  1092.     if (get_post_type($post_id) != 'post') {
  1093.         return;
  1094.     }
  1095.     /*
  1096.      * 提取现有的值
  1097.      * @var boolean
  1098.      */
  1099.     $value = get_post_meta($post_id, '_custom_author_name', true);
  1100.     /*
  1101.      * 添加 nonce 安全处理
  1102.      */
  1103.     wp_nonce_field('custom_author_nonce' , 'custom_author_nonce');
  1104.     ?>
  1105.     <div class="misc-pub-section misc-pub-section-last dashicons-before dashicons-admin-users">
  1106.         <label><b>作者:</b><input type="text" value="<?php echo $value ?>" name="_custom_author_name" /></label>
  1107.     </div>
  1108.     <?php
  1109. }
  1110. //保存配置信息 $post_id 文章的ID
  1111. function cus_author_saveCustomField($post_id) {
  1112.     //自动保存不处理
  1113.     if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
  1114.         return;
  1115.     }
  1116.     //信息不正确不处理
  1117.     if (
  1118.         !isset($_POST['custom_author_nonce']) ||
  1119.         !wp_verify_nonce($_POST['custom_author_nonce'], 'custom_author_nonce')
  1120.     ) {
  1121.         return;
  1122.     }
  1123.     //用户无权编辑文章不处理
  1124.     if (!current_user_can('edit_post', $post_id)) {
  1125.         return;
  1126.     }
  1127.     //存在此项目就更新
  1128.     if (isset($_POST['_custom_author_name'])) {
  1129.         update_post_meta($post_id, '_custom_author_name', sanitize_text_field($_POST['_custom_author_name']));
  1130.     } else {
  1131.         //不存在就删除
  1132.         delete_post_meta($post_id, '_custom_author_name');
  1133.     }
  1134. }
  1135. function cus_author_the_author($author){
  1136.     $custom_author = get_post_meta(get_the_ID(), '_custom_author_name');
  1137.     if ($custom_author) {
  1138.         return $custom_author[0];
  1139.     } else {
  1140.         return $author;
  1141.     }
  1142. }
  1143.  
  1144. /*
  1145.  * 四合一简化 WordPress 后台用户个人信息姓名昵称设置
  1146.  */
  1147. add_action('show_user_profile','wpjam_edit_user_profile');
  1148. add_action('edit_user_profile','wpjam_edit_user_profile');
  1149. function wpjam_edit_user_profile($user){
  1150.     ?>
  1151.     <script>
  1152.         jQuery(document).ready(function($) {
  1153.             $('#first_name').parent().parent().hide();
  1154.             $('#last_name').parent().parent().hide();
  1155.             $('#display_name').parent().parent().hide();
  1156.             $('.show-admin-bar').hide();
  1157.         });
  1158.     </script>
  1159.     <?php
  1160. }
  1161. //更新时候,强制设置显示名称为昵称
  1162. add_action('personal_options_update','wpjam_edit_user_profile_update');
  1163. add_action('edit_user_profile_update','wpjam_edit_user_profile_update');
  1164. function wpjam_edit_user_profile_update($user_id){
  1165.     if (!current_user_can('edit_user', $user_id))
  1166.         return false;
  1167.     $user = get_userdata($user_id);
  1168.     $_POST['nickname'] = ($_POST['nickname'])?:$user->user_login;
  1169.     $_POST['display_name']  = $_POST['nickname'];
  1170.     $_POST['first_name']    = '';
  1171.     $_POST['last_name']     = '';
  1172. }
  1173.  
  1174. /*
  1175.  * 禁用 WordPress 4.7 新增的PDF缩略图预览功能
  1176.  */
  1177. add_filter('fallback_intermediate_image_sizes', 'wpb_disable_pdf_previews');
  1178. function wpb_disable_pdf_previews() {
  1179.     $fallbacksizes = array();
  1180.     return $fallbacksizes;
  1181. }
  1182.  
  1183. /**
  1184.  * 新文章自动使用ID作为别名
  1185.  * 作用:即使你设置固定连接结构为 %postname% ,仍旧自动生成 ID 结构的链接
  1186.  */
  1187. add_action( 'save_post', 'using_id_as_slug', 10, 2 );
  1188. function using_id_as_slug($post_id, $post){
  1189.     global $post_type;
  1190.     if($post_type=='post'){ //只对文章生效
  1191.         // 如果是文章的版本,不生效
  1192.         if (wp_is_post_revision($post_id))
  1193.             return false;
  1194.         // 取消挂载该函数,防止无限循环
  1195.         remove_action('save_post', 'using_id_as_slug' );
  1196.         // 使用文章ID作为文章的别名
  1197.         wp_update_post(array('ID' => $post_id, 'post_name' => $post_id ));
  1198.         // 重新挂载该函数
  1199.         add_action('save_post', 'using_id_as_slug' );
  1200.     }
  1201. }
  1202.  
  1203. //根据上传时间重命名文件
  1204. add_filter('wp_handle_upload_prefilter', 'custom_upload_filter' );
  1205. function custom_upload_filter( $file ){
  1206.     $info = pathinfo($file['name']);
  1207.     $ext = $info['extension'];
  1208.     $filedate = date('YmdHis').rand(10,99);//为了避免时间重复,再加一段2位的随机数
  1209.     $file['name'] = $filedate.'.'.$ext;
  1210.     return $file;
  1211. }
  1212.  
  1213.  
  1214. //自动调用媒体库中的图片作为缩略图
  1215. add_action('the_post', 'wpforce_featured');
  1216. add_action('save_post', 'wpforce_featured');
  1217. add_action('draft_to_publish', 'wpforce_featured');
  1218. add_action('new_to_publish', 'wpforce_featured');
  1219. add_action('pending_to_publish', 'wpforce_featured');
  1220. add_action('future_to_publish', 'wpforce_featured');
  1221. function wpforce_featured() {
  1222.     global $post;
  1223.     $already_has_thumb = has_post_thumbnail($post->ID);
  1224.     if (!$already_has_thumb)  {
  1225.        $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
  1226.         if ($attached_image) {
  1227.            foreach ($attached_image as $attachment_id => $attachment) {
  1228.               set_post_thumbnail($post->ID, $attachment_id);
  1229.             }
  1230.         } else {
  1231.             set_post_thumbnail($post->ID, '10181');
  1232.         }
  1233.     }
  1234. }  //end function

WordPress 建站主题开发常用功能函数

已有 284 人购买
查看演示升级 VIP立刻购买

也想出现在这里?联系我们
创客主机
收藏
(0)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!