用Wordpress建站的初学者一定会需要用到的Wordpress模板主题中functions.php常用功能代码与常用插件。慢慢持续收集整理.......
目录
一、Wordpress模板主题中functions文件常用的代码
二、Wordpress自定义字段的设定与调用代码(系统常规自定义字段)
三、wordpress分类栏目添加自定义字段 (例如栏目图片)
- // 关闭核心提示
- add_filter('pre_site_transient_update_core', create_function('$a', "return null;"));
- // 关闭插件提示
- add_filter('pre_site_transient_update_plugins', create_function('$a', "return null;"));
- // 关闭主题提示
- add_filter('pre_site_transient_update_themes', create_function('$a', "return null;"));
-
-
-
- add_filter('automatic_updater_disabled', '__return_true'); // 彻底关闭自动更新
- remove_action('init', 'wp_schedule_update_checks'); // 关闭更新检查定时作业
- wp_clear_scheduled_hook('wp_version_check'); // 移除已有的版本检查定时作业
- wp_clear_scheduled_hook('wp_update_plugins'); // 移除已有的插件更新定时作业
- wp_clear_scheduled_hook('wp_update_themes'); // 移除已有的主题更新定时作业
- wp_clear_scheduled_hook('wp_maybe_auto_update'); // 移除已有的自动更新定时作业
-
- remove_action( 'admin_init', '_maybe_update_core' ); // 移除后台内核更新检查
- remove_action( 'load-plugins.php', 'wp_update_plugins' ); // 移除后台插件更新检查
- remove_action( 'load-update.php', 'wp_update_plugins' );
- remove_action( 'load-update-core.php', 'wp_update_plugins' );
- remove_action( 'admin_init', '_maybe_update_plugins' );
-
- remove_action( 'load-themes.php', 'wp_update_themes' ); // 移除后台主题更新检查
- remove_action( 'load-update.php', 'wp_update_themes' );
- remove_action( 'load-update-core.php', 'wp_update_themes' );
- remove_action( 'admin_init', '_maybe_update_themes' );
-
-
-
-
- // 自定义边栏小工具
- function wpdf_register_sidebar() {
- // 注册第一个边栏
- register_sidebar( array(
- 'name' => '边栏1',
- 'id' => 'sidebar-1',
- 'description' => '第一个边栏',
- 'before_widget' => '
' , - 'after_widget' => '',
- 'before_title' => '
'
, - 'after_title' => '',
- ));
-
-
- // 注册第二个边栏
- register_sidebar( array(
- 'name' => '边栏2',
- 'id' => 'sidebar-2',
- 'description' => '第二个边栏',
- 'before_widget' => '
' , - 'after_widget' => '',
- 'before_title' => '
'
, - 'after_title' => '',
- ));
- }
- add_action( 'widgets_init', 'wpdf_register_sidebar' );
-
- //删除wp-nav-menu函数菜单中多余的css选择器
- add_filter('nav_menu_css_class', 'my_css_attributes_filter', 100, 1);
- add_filter('nav_menu_item_id', 'my_css_attributes_filter', 100, 1);
- add_filter('page_css_class', 'my_css_attributes_filter', 100, 1);
- function my_css_attributes_filter($var) {
- return is_array($var) ? array() : '';
- }
-
- //移除后台用不到的菜单
- function yg_remove_menu_page() {
- //remove_menu_page('themes.php'); // 移除 "外观"
- //remove_menu_page('plugins.php'); // 移除 "插件"
- //remove_menu_page('tools.php'); // 移除 "工具"
-
- remove_submenu_page('tools.php','export.php'); //移除工具下的导出
-
- }
- add_action( 'admin_menu', 'yg_remove_menu_page' );
-
-
-
- //开启wordpress友情链接管理
- add_filter( 'pre_option_link_manager_enabled', '__return_true' );
- //开启wordpress特色图片
- add_theme_support( 'post-thumbnails' );
-
-
- //WordPress子分类页面使用父页面模板
- add_filter('category_template', 'f_category_template');
- function f_category_template($template){
- $category = get_queried_object();
- if($category->parent !='0'){
- while($category->parent !='0'){
- $category = get_category($category->parent);
- }
- }
-
- $templates = array();
-
- if ( $category ) {
- $templates[] = "category-{$category->slug}.php";
- $templates[] = "category-{$category->term_id}.php";
- }
- $templates[] = 'category.php';
- return locate_template( $templates );
- }
-
-
-
- /**分页 前端调用
- function kriesi_pagination($query_string){
- global $posts_per_page, $paged;
- $my_query = new WP_Query($query_string ."&posts_per_page=-1");
- $total_posts = $my_query->post_count;
- if(empty($paged))$paged = 1;
- $prev = $paged - 1;
- $next = $paged + 1;
- $range = 2; // only edit this if you want to show more page-links
- $showitems = ($range * 2)+1;
- $pages = ceil($total_posts/$posts_per_page);
- if(1 != $pages){
- echo "";
- for ($i=1; $i <= $pages; $i++){
- if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems )){
- }
- }
- echo "\n";
- }
- }
-
- //面包屑导航
- function wz(){
- $cat=get_the_category();
- $cat=$cat[0];
- if(!is_home() ){
- if(is_category()){
- echo $positions;
- }
- elseif(is_single()){
- echo $positions ;
- echo the_title();
- }
- elseif(is_search()){echo $s;}
- elseif(is_page()){
- the_title();
- }elseif(is_404()){echo '404错误页面';}
-
- }
- }
-
- //获取当前分类子分类列表
- function get_category_root_id($cat){
- $this_category = get_category($cat); // 取得当前分类
- while($this_category->category_parent) {// 若当前分类有上级分类时,循环
- $this_category = get_category($this_category->category_parent); // 将当前分类设为上级分类(往上爬)
- }
- return $this_category->term_id; // 返回根分类的id号
- }
-
-
-
- //分类目录后加 /
- function nice_trailingslashit($string, $type_of_url) {
- if ( $type_of_url != 'single' )
- $string = trailingslashit($string);
- return $string;
- }
- add_filter('user_trailingslashit', 'nice_trailingslashit', 10, 2);
-
-
- //移除WordPress后台顶部左上角的W图标
-
- add_action('wp_before_admin_bar_render', 'annointed_admin_bar_remove', 0);
- function annointed_admin_bar_remove() {
- global $wp_admin_bar;
- /* Remove their stuff */
- $wp_admin_bar->remove_menu('wp-logo');
- }
-
- //自定义后台登录Logo的Url
- add_filter( 'login_headerurl', 'custom_loginlogo_url' );
- function custom_loginlogo_url($url) {
- return 'http://www.nongyejing.com';
- }
-
- // 自定义 WordPress 后台底部的版权和版本信息
- add_filter('admin_footer_text', 'left_admin_footer_text');
- function left_admin_footer_text($text) {
- // 左边信息
- $text = '左边版权信息';
- return $text;
- }
- add_filter('update_footer', 'right_admin_footer_text', 11);
- function right_admin_footer_text($text) {
- // 右边信息
- $text = "这是右边信息";
- return $text;
- }
-
- //屏蔽 WP 后台“显示选项”和“帮助”选项卡
- add_filter('screen_options_show_screen', 'remove_screen_options');
- add_filter( 'contextual_help', 'remove_wp_help', 999, 3 );
- function remove_screen_options(){ return false;}
- function remove_wp_help($old_help, $screen_id, $screen){
- $screen->remove_help_tabs();
- return $old_help;
- }
-
- //固定后台管理侧边栏
-
- add_action('admin_head', 'Bing_fixed_adminmenuwrap');
- function Bing_fixed_adminmenuwrap(){
- echo '';
- }
-
- //阻止站内文章互相Pingback
- add_action('pre_ping','Bing_noself_ping');
- function Bing_noself_ping($links) {
- $home = get_option( 'home' );
- foreach ( $links as $l => $link )
- if ( 0 === strpos( $link, $home ) )
- unset($links[$l]);
- }
-
- // 增强默认编辑器(mce_buttons:工具栏的第一行;mce_buttons_2:工具栏第二行;mce_buttons_3:工具栏第三行)
-
- add_filter("mce_buttons", "Bing_editor_buttons");
- function Bing_editor_buttons($buttons){
-
- //$buttons[] = 'wp_adv'; //隐藏按钮显示开关
- $buttons[] = 'wp_adv_start'; //隐藏按钮区起始部分
- $buttons[] = 'wp_adv_end'; //隐藏按钮区结束部分
- //$buttons[] = 'bold'; //加粗
- //$buttons[] = 'italic'; //斜体
- $buttons[] = 'underline'; //下划线
- $buttons[] = 'strikethrough'; //删除线
- $buttons[] = 'justifyleft'; //左对齐
- $buttons[] = 'justifycenter'; //居中
- $buttons[] = 'justfyright'; //右对齐
- $buttons[] = 'justfyfull'; //两端对齐
- //$buttons[] = 'bullist'; //无序列表
- //$buttons[] = 'numlist'; //编号列表
- $buttons[] = 'outdent'; //减少缩进
- $buttons[] = 'indent'; //缩进
- $buttons[] = 'cut'; //剪切
- $buttons[] = 'copy'; //复制
- $buttons[] = 'paste'; //粘贴
- $buttons[] = 'undo'; //撤销
- $buttons[] = 'redo'; //重做
- //$buttons[] = 'link'; //插入超链接
- $buttons[] = 'unlink'; //取消超链接
- $buttons[] = 'image'; //插入图片
- $buttons[] = 'removeformat'; //清除格式
- $buttons[] = 'code'; //打开HTML代码编辑器
- $buttons[] = 'hr'; //水平线
- $buttons[] = 'cleanup'; //清除冗余代码
- $buttons[] = 'formmatselect'; //格式选择
- $buttons[] = 'fontselect'; //字体选择
- $buttons[] = 'fontsizeselect'; //字号选择
- $buttons[] = 'styleselect'; //样式选择
- $buttons[] = 'sub'; //上标
- $buttons[] = 'sup'; //下标
- $buttons[] = 'forecolor'; //字体颜色
- $buttons[] = 'backcolor'; //字体背景色
- $buttons[] = 'charmap'; //特殊符号
- $buttons[] = 'anchor'; //锚文本
- $buttons[] = 'newdocument'; //新建文本
- //$buttons[] = 'wp_more'; //插入more标签
- $buttons[] = 'wp_page'; //插入分页标签
- $buttons[] = 'spellchecker'; //拼写检查
- $buttons[] = 'wp_help'; //帮助
- //$buttons[] = 'selectall'; //全选
- //$buttons[] = 'visualaid'; //显示/隐藏指导线和不可见元素
- $buttons[] = 'spellchecker'; //切换拼写检查器状态
- $buttons[] = 'pastetext'; //以纯文本粘贴
- $buttons[] = 'pasteword'; //从Word中粘贴
- //$buttons[] = 'blockquote'; //引用
- $buttons[] = 'forecolorpicker'; //选择文字颜色(拾色器)
- $buttons[] = 'backcolorpicker'; //选择背景颜色(拾色器)
- $buttons[] = 'spellchecker'; //切换拼写检查器状态
-
- return $buttons;
- }
-
- //TinyMCE编辑器增强:增加中文字体
- add_filter('tiny_mce_before_init', 'custum_fontfamily');
- function custum_fontfamily($initArray){
- $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";
- return $initArray;
- }
-
- //更改编辑器默认视图为HTML
- //add_filter('wp_default_editor', create_function('', 'return "html";'));
-
- //在 WordPress 编辑器中为自定义文章类型设置默认内容
- add_filter( 'default_content', 'my_editor_content', 10, 2 );
- function my_editor_content( $content, $post ) {
- switch( $post->post_type ) {
- case 'sources':
- $content = 'your content';
- break;
- case 'stories':
- $content = 'your content';
- break;
- case 'pictures':
- $content = 'your content';
- break;
- default:
- $content = 'your default content';
- break;
- }
- return $content;
- }
-
- //添加编辑器默认内容(此方法添加的内容在发布文章时自动添加在内容的最后,在编辑的时候是看不见的)
- add_filter ('the_content', 'insertFootNote');
- function insertFootNote($content) {
- if(!is_feed() && !is_home()) {
- $content.= "这里的预定义内容在编辑器不可见";
- }
- return $content;
- }
-
- //为编辑器添加更多的HTML标签
- add_filter('tiny_mce_before_init', 'fb_change_mce_options');
- function fb_change_mce_options($initArray) {
- $ext = 'pre[id|name|class|style],iframe[align|longdesc|name|width|height|frameborder|scrolling|marginheight|marginwidth|src]'; //注意:格式为“标签一[属性一|属性二],标签二[属性一|属性二|属性三]”
- if ( isset( $initArray['extended_valid_elements'] ) ) {
- $initArray['extended_valid_elements'] .= ',' . $ext;
- } else {
- $initArray['extended_valid_elements'] = $ext;
- }
- return $initArray;
- }
-
- //让编辑器支持中文拼写检查
- add_filter('tiny_mce_before_init', 'fb_mce_external_languages');
- function fb_mce_external_languages($initArray){
- $initArray['spellchecker_languages'] = '+Chinese=zh,English=en';
- return $initArray;
- }
-
- //更改后台字体
- add_action('admin_head', 'Bing_admin_lettering');
- function Bing_admin_lettering(){
- //echo '';//修改字体
- }
-
- //WordPress 后台回复评论添加提交快捷键[Ctrl+Enter]
- add_action('admin_footer', 'Bing_admin_comment_ctrlenter');
- function Bing_admin_comment_ctrlenter(){
- echo '
- jQuery(document).ready(function($){
- $("textarea").keypress(function(e){
- if(e.ctrlKey&&e.which==13||e.which==10){
- $("#replybtn").click();
- }
- });
- });
- ';
- }
-
- //WordPress 让后台用户列表可以根据文章数进行排序
-
- if ( ! class_exists('Sort_Users_By_Post_Count') ) {
- class Sort_Users_By_Post_Count {
- function Sort_Users_By_Post_Count() {
- // Make user table sortable by post count
- add_filter( 'manage_users_sortable_columns', array( $this, 'add_custom_user_sorts' ) );
- }
- /* Add sorting by post count to user page */
- function add_custom_user_sorts( $columns ) {
- $columns['posts'] = 'post_count';
- return $columns;
- }
- }
- $Sort_Users_By_Post_Count = new Sort_Users_By_Post_Count();
- }
-
- //WordPress 4.3+ 默认开启页面的评论功能
- add_filter( 'get_default_comment_status', 'wp33516_open_comments_for_pages', 10, 3 );
- function wp33516_open_comments_for_pages( $status, $post_type, $comment_type ) {
- if ( 'page' === $post_type ) {
- $status = 'open';
- }
- return $status;
- }
-
- //将WordPress后台的open-sans字体加载源从Google Fonts换为360 CDN
- add_action( 'init', 'wpdx_replace_open_sans' );
- function wpdx_replace_open_sans() {
- wp_deregister_style('open-sans');
- wp_register_style( 'open-sans', '//fonts.useso.com/css?family=Open+Sans:300italic,400italic,600italic,300,400,600' );
- if(is_admin()) wp_enqueue_style( 'open-sans');
- }
-
- //WordPress 关闭 XML-RPC 的 pingback 端口
- add_filter( 'xmlrpc_methods', 'remove_xmlrpc_pingback_ping' );
- function remove_xmlrpc_pingback_ping( $methods ) {
- unset( $methods['pingback.ping'] );
- return $methods;
- }
-
- //禁用 WordPress 的 JSON REST API
- add_filter('json_enabled', '__return_false');
- add_filter('json_jsonp_enabled', '__return_false');
-
- //禁止WordPress压缩JGP图片质量
- add_filter( 'jpg_quality', 'high_jpg_quality' );
- function high_jpg_quality() {
- return 100;
- }
-
- //WordPress 隐藏特定插件的更新提示
- //add_filter( 'site_transient_update_plugins', 'filter_plugin_updates' );
- function filter_plugin_updates( $value ) {
- unset( $value->response['plugin-directory/plugin-file.php'] );
- return $value;
- }
-
- //隐藏核心更新提示 WP 3.0+
- //add_filter( 'pre_site_transient_update_core', create_function( '$a', "return null;" ) );
-
- //隐藏插件更新提示 WP 3.0+
- //remove_action( 'load-update-core.php', 'wp_update_plugins' );
- //add_filter( 'pre_site_transient_update_plugins', create_function( '$b', "return null;" ) );
-
- //隐藏主题更新提示 WP 3.0+
- //remove_action( 'load-update-core.php', 'wp_update_themes' );
- //add_filter( 'pre_site_transient_update_themes', create_function( '$c', "return null;" ) );
-
- //新用户预设默认的后台配色方案
- add_action('user_register', 'set_default_admin_color');
- function set_default_admin_color($user_id) {
- $args = array(
- 'ID' => $user_id,
- 'admin_color' => 'sunrise'
- );
- wp_update_user( $args );
- }
-
- //对非管理员移除配色方案设置选项
- if ( !current_user_can('manage_options') ){
- remove_action( 'admin_color_scheme_picker', 'admin_color_scheme_picker' );
- }
-
- //移除 WordPress 仪表盘欢迎面板
- //remove_action('welcome_panel', 'wp_welcome_panel');
-
-
- //自定义 WordPress 仪表盘欢迎面板
- //add_action( 'welcome_panel', 'rc_my_welcome_panel' );
- function rc_my_welcome_panel() {
- ?>
-
-
- class="custom-welcome-panel-content">
- <h2>php _e( '欢迎使用WordPress!' ); ?>h2>
- <p class="about-description">php _e( '我们准备了几个链接供您开始:' ); ?>p>
- <div class="welcome-panel-column-container">
- <div class="welcome-panel-column">
- <h3 style="font-weight: bold">php _e( "开始使用" ); ?>h3>
- <a class="button button-primary button-hero load-customize hide-if-no-customize" href="http://www.nongyejing.com">php _e( '联系我们' ); ?>a>
- <p class="hide-if-no-customize">php printf( __( '或者 <a href="%s">设置网站a>' ), admin_url( 'options-general.php' ) ); ?>p>
- div>
- <div class="welcome-panel-column">
- <h4>php _e( 'Next Steps' ); ?>h4>
- <ul>
- php if ( 'page' == get_option( 'show_on_front' ) && ! get_option( 'page_for_posts' ) ) : ?>
- <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>
- <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>
- php elseif ( 'page' == get_option( 'show_on_front' ) ) : ?>
- <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>
- <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>
- <li>php printf( '<a href="%s" class="welcome-icon welcome-write-blog">' . __( 'Add a blog post' ) . 'a>', admin_url( 'post-new.php' ) ); ?>li>
- php else : ?>
- <li>php printf( '<a href="%s" class="welcome-icon welcome-write-blog">' . __( 'Write your first blog post' ) . 'a>', admin_url( 'post-new.php' ) ); ?>li>
- <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>
- php endif; ?>
- <li>php printf( '<a href="%s" class="welcome-icon welcome-view-site">' . __( 'View your site' ) . 'a>', home_url( '/' ) ); ?>li>
- ul>
- div>
- <div class="welcome-panel-column welcome-panel-last">
- <h4>php _e( 'More Actions' ); ?>h4>
- <ul>
- <li>php printf( '<div class="welcome-icon welcome-widgets-menus">' . __( 'Manage <a href="%1$s">widgetsa> or <a href="%2$s">menusa>' ) . 'div>', admin_url( 'widgets.php' ), admin_url( 'nav-menus.php' ) ); ?>li>
- <li>php printf( '<a href="%s" class="welcome-icon welcome-comments">' . __( 'Turn comments on or off' ) . 'a>', admin_url( 'options-discussion.php' ) ); ?>li>
- <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>
- ul>
- div>
- div>
- <div class="">
- <h3>php _e( '关于我们' ); ?>h3>
-
- <p>延农业经网成立于2015年6月20日,一个农业新媒体资讯平台。提供一站式的农业+互联网综合解决方案!p>
- div>
- div>
- php
- }
- //WordPress 限制非管理员用户上传图片的最小宽度和高度
- add_action( 'admin_init', 'block_authors_from_uploading_small_images' );
- function block_authors_from_uploading_small_images(){
- //除管理员以外,其他用户都限制
- if( !current_user_can( 'manage_options') )
- add_filter( 'wp_handle_upload_prefilter', 'block_small_images_upload' );
- }
- function block_small_images_upload( $file ){
- // 检测文件的类型是否是图片
- $mimes = array( 'image/jpeg', 'image/png', 'image/gif' );
- // 如果不是图片,直接返回文件
- if( !in_array( $file['type'], $mimes ) )
- return $file;
-
- $img = getimagesize( $file['tmp_name'] );
- // 设置最小宽度和高度
- $minimum = array( 'width' => 640, 'height' => 480 );
-
- if ( $img[0] < $minimum['width'] )
- $file['error'] =
- '图片太小了,最小宽度是 '
- . $minimum['width']
- . 'px,当前上传的图片宽度是 '
- . $img[0] . 'px';
-
- elseif ( $img[1] < $minimum['height'] )
- $file['error'] =
- '图片太小了,最小高度是 '
- . $minimum['height']
- . 'px,当前上传的图片高度是 '
- . $img[1] . 'px';
-
- return $file;
- }
-
- //WordPress 后台用户列表显示注册时间
-
- add_filter( 'manage_users_columns', array('RRHE','registerdate'));
- add_action( 'manage_users_custom_column', array('RRHE','registerdate_columns'), 15, 3);
- add_filter( 'manage_users_sortable_columns', array('RRHE','registerdate_column_sortable') );
- add_filter( 'request', array('RRHE','registerdate_column_orderby') );
- class RRHE {
- // Register the column - Registered
- public static function registerdate($columns) {
- $columns['registerdate'] = __('注册时间', 'registerdate');
- return $columns;
- }
-
- // Display the column content
- public static function registerdate_columns( $value, $column_name, $user_id ) {
- if ( 'registerdate' != $column_name )
- return $value;
- $user = get_userdata( $user_id );
- $registerdate = get_date_from_gmt($user->user_registered);
- return $registerdate;
- }
-
- public static function registerdate_column_sortable($columns) {
- $custom = array(
- // meta column id => sortby value used in query
- 'registerdate' => 'registered',
- );
- return wp_parse_args($custom, $columns);
- }
-
- public static function registerdate_column_orderby( $vars ) {
- if ( isset( $vars['orderby'] ) && 'registerdate' == $vars['orderby'] ) {
- $vars = array_merge( $vars, array(
- 'meta_key' => 'registerdate',
- 'orderby' => 'meta_value'
- ) );
- }
- return $vars;
- }
-
- }
-
- //在WordPress插件管理界面隐藏已启用的插件(包括管理员)
- //add_filter( 'all_plugins', 'hide_plugins');
- function hide_plugins($plugins)
- {
- // 隐藏 你好,多莉 插件
- if(is_plugin_active('hello.php')) {
- unset( $plugins['hello.php'] );
- }
- // 隐藏 post series插件
- if(is_plugin_active('ankium/ankium.php')) {
- unset( $plugins['ankium/ankium.php'] );
- }
- return $plugins;
- }
-
- //在WordPress插件管理界面隐藏已启用的插件(除指定用户)
- add_filter('all_plugins', 'filter_visible_plugins');
- function filter_visible_plugins($plugins) {
- //添加插件的相对于 /wp-content/plugins/ 的路径
- $pluginsToHide = array(
- 'hello.php',
- 'ankium/ankium.php'
- );
- //在这个例子中,我们对所有用户隐藏插件,除了用户 smith
- $currentUser = wp_get_current_user();
- $shouldHide = $currentUser->get('user_login') != 'ankium';
-
- if ( $shouldHide ) {
- foreach($pluginsToHide as $pluginFile) {
- unset($plugins[$pluginFile]);
- }
- }
- return $plugins;
- }
-
- //WordPress 移除插件列表所有已启用插件的“编辑”和“停用”链接
-
- //add_filter( 'plugin_action_links', 'remove_all_plugin_actions', 10, 4 );
- function remove_all_plugin_actions( $actions, $plugin_file, $plugin_data, $context )
- {
- // 移除所有“编辑”链接
- if ( isset( $actions['edit'] ) )
- {
- unset( $actions['edit'] );
- }
- // 移除插件的“停用”链接
- if( isset( $actions['deactivate'] ) )
- {
- unset( $actions['deactivate'] );
- }
- return $actions;
- }
-
- //WordPress 移除插件列表已启用特定插件的“编辑”和“停用”链接
- //add_filter( 'plugin_action_links', 'remove_plugin_actions', 10, 4 );
- function remove_plugin_actions( $actions, $plugin_file, $plugin_data, $context )
- {
- // 移除所有“编辑”链接
- if ( isset( $actions['edit'] ) )
- {
- unset( $actions['edit'] );
- }
- // 移除插件的“停用”链接
- if( isset( $actions['deactivate'] ) )
- {
- switch($plugin_file)
- {
- // 添加插件的主文件目录
- case 'hello.php': // 注意结尾是英文冒号
- unset( $actions['deactivate'] );
- break;
- }
- }
- return $actions;
- }
-
-
- //WordPress 禁用自定义文章类型的可视化编辑器
- //add_filter( 'user_can_richedit', 'disable_wysiwyg_editor_for_cpt' );
- function disable_wysiwyg_editor_for_cpt( $default ) {
- global $post;
- if ( get_post_type( $post ) == 'question') // 请修改 question 为你的文章类型
- return false;
- return $default;
- }
-
-
- //WordPress 仪表盘显示待审核的文章列表
- add_action('wp_dashboard_setup', 'wpjam_modify_dashboard_widgets' );
- function wpjam_modify_dashboard_widgets() {
- global $wp_meta_boxes;
-
- if(current_user_can('manage_options')){ //只有管理员才能看到
- add_meta_box( 'pending_posts_dashboard_widget', '待审文章', 'pending_posts_dashboard_widget_function','dashboard', 'normal', 'core' );
- }
- }
- function pending_posts_dashboard_widget_function() {
- global $wpdb;
- $pending_posts = $wpdb->get_results("SELECT * FROM {$wpdb->posts} WHERE post_status = 'pending' ORDER BY post_modified DESC");
-
- if($pending_posts){ //判断是否有待审文章
- echo '
'
; - foreach ($pending_posts as $pending_post){
- }
- echo '';
- }else echo '目前没有待审文章';
- }
-
-
- //WordPress 仪表盘“近期评论”显示完整评论内容和格式
-
- //add_filter('comment_excerpt', 'full_comments_on_dashboard');
- function full_comments_on_dashboard($excerpt) {
- global $comment;
-
- if ( !is_admin() )
- return $excerpt;
-
- $content = wpautop($comment->comment_content);
- $content = substr($content, 3, -5); // 移除第一个
和最后一个
- $content = str_replace('
'
, ''
, $content); -
- return $content;
- }
-
- //WordPress 后台文章列表根据文章状态添加不同背景色
-
- add_action('admin_footer','posts_status_color');
- function posts_status_color(){
- ?>
-
- .status-draft{background: #FCE3F2 !important;/*草稿*/}
- .status-pending{background: #87C5D6 !important;/*待审核*/}
- .status-publish{/* 已发布,使用默认背景色,你也可以自己添加颜色 */}
- .status-future{background: #C6EBF5 !important;/*定时发布*/}
- .status-private{background:#F2D46F;/*私密日志*/}
- .post-password-required{background:#D874DE;/*密码保护*/}
-
-
- }
-
- //更改标题输入框提示文字
-
- add_filter( 'enter_title_here', 'change_default_title' );
- function change_default_title( $title ){
- $screen = get_current_screen();
-
- if( 'post' == $screen->post_type ) {
- $title = '输入文章标题';
- } elseif ('page' == $screen->post_type) {
- $title = '输入页面标题';
- } elseif ('book' == $screen->post_type) {
- $title = '输入书籍标题';
- }
-
- return $title;
- }
-
- //让WordPress记住不同主题下所选择的的页面模板
- add_action( "updated_post_meta", "rmt_update_post_template_meta", 10, 4 );
- add_action( "added_post_meta", "rmt_update_post_template_meta", 10, 4 );
- function rmt_update_post_template_meta( $meta_id, $post_id, $meta_key, $meta_value ){
-
- if( '_wp_page_template' === $meta_key ){
-
- $theme = wp_get_theme();
- $name = $theme->template;
- if( $name ){
- update_post_meta( $post_id, '_wp_page_template_' . $name, $meta_value );
- }
-
- }
-
- }
- add_filter( 'get_post_metadata', 'rmt_get_post_template_meta', 10, 4 );
- function rmt_get_post_template_meta( $value, $post_id, $meta_key, $single ){
-
- if( '_wp_page_template' === $meta_key ){
-
- $theme = wp_get_theme();
- $name = $theme->template;
-
- if( $name ){
- $template = get_post_meta( $post_id, '_wp_page_template_' . $name, $single );
- if( $template && locate_template( $template ) ){
- $value = $template;
- }
- }
-
- }
-
- return $value;
- }
-
- //在媒体库显示文件尺寸
- //add_filter('manage_upload_columns', 'size_column_register');
- function size_column_register($columns) {
- $columns['dimensions'] = __('Dimensions');
- return $columns;
- }
- //add_action('manage_media_custom_column', 'size_column_display', 10, 2);
- function size_column_display($column_name, $post_id) {
- if( 'dimensions' != $column_name || !wp_attachment_is_image($post_id))
- return;
- list($url, $width, $height) = wp_get_attachment_image_src($post_id, 'full');
- echo esc_html("{$width}×{$height}");
- }
-
- //在媒体编辑页面显示文件大小
- //add_action( 'attachment_submitbox_misc_actions', 'mc_attachment_submitbox_filesize' );
- function mc_attachment_submitbox_filesize() {
- $post = get_post();
- $filesize = @filesize( get_attached_file( $post->ID ) );
-
- if ( ! empty( $filesize ) && is_numeric( $filesize ) && $filesize > 0 ) : ?>
- class="misc-pub-section">
- php _e( '文件大小:' ); ?> <strong>php echo size_format( $filesize ); ?>strong>
- div>
- php
- endif;
- }
- //让WordPress后台用户列表可以搜索名字、姓氏和公开显示名
- if (is_admin()) {//让函数只应用于WordPress后台
- //通过钩子挂载函数
- add_action('pre_user_query', 'wpdaxue_pre_user_query');
- }
- function wpdaxue_pre_user_query($user_search) {
- global $wpdb;
- $vars = $user_search->query_vars;
- if (!is_null($vars['search'])) {
- // 出于某种原因,搜索词被星号包括,删除它们
- $search = preg_replace('/^\*/', '', $vars['search']);
- $search = preg_replace('/\*$/', '', $search);
-
- //搜索公开显示名
- if(!empty($search)){
- $user_search->query_where = substr(trim($user_search->query_where), 0, -1) . " OR display_name LIKE '%". $search . "%')";
- }
- //搜索名字和姓氏
- $user_search->query_from .= " INNER JOIN {$wpdb->usermeta} m1 ON " .
- "{$wpdb->users}.ID=m1.user_id AND (m1.meta_key='first_name')";
- $user_search->query_from .= " INNER JOIN {$wpdb->usermeta} m2 ON " .
- "{$wpdb->users}.ID=m2.user_id AND (m2.meta_key='last_name')";
- $names_where = $wpdb->prepare("m1.meta_value LIKE '%s' OR m2.meta_value LIKE '%s'", "%{$search}%", "%$search%");
- $user_search->query_where = str_replace('WHERE 1=1 AND (', "WHERE 1=1 AND ({$names_where} OR ", $user_search->query_where);
- }
- return $user_search;
- }
-
-
- //为WordPress后台的文章、分类等显示ID
- add_action('admin_init', 'ssid_add');
- // 添加一个新的列 ID
- function ssid_column($cols) {
- $cols['ssid'] = 'ID';
- return $cols;
- }
- // 显示 ID
- function ssid_value($column_name, $id) {
- if ($column_name == 'ssid')
- echo $id;
- }
- function ssid_return_value($value, $column_name, $id) {
- if ($column_name == 'ssid')
- $value = $id;
- return $value;
- }
- // 为 ID 这列添加css
- function ssid_css() {
- ?>
-
-
- }
- // 通过动作/过滤器输出各种表格和CSS
- function ssid_add() {
- add_action('admin_head', 'ssid_css');
-
- add_filter('manage_posts_columns', 'ssid_column');
- add_action('manage_posts_custom_column', 'ssid_value', 10, 2);
-
- add_filter('manage_pages_columns', 'ssid_column');
- add_action('manage_pages_custom_column', 'ssid_value', 10, 2);
-
- add_filter('manage_media_columns', 'ssid_column');
- add_action('manage_media_custom_column', 'ssid_value', 10, 2);
-
- add_filter('manage_link-manager_columns', 'ssid_column');
- add_action('manage_link_custom_column', 'ssid_value', 10, 2);
-
- add_action('manage_edit-link-categories_columns', 'ssid_column');
- add_filter('manage_link_categories_custom_column', 'ssid_return_value', 10, 3);
-
- foreach ( get_taxonomies() as $taxonomy ) {
- add_action("manage_edit-${taxonomy}_columns", 'ssid_column');
- add_filter("manage_${taxonomy}_custom_column", 'ssid_return_value', 10, 3);
- }
-
- add_action('manage_users_columns', 'ssid_column');
- add_filter('manage_users_custom_column', 'ssid_return_value', 10, 3);
-
- add_action('manage_edit-comments_columns', 'ssid_column');
- add_action('manage_comments_custom_column', 'ssid_value', 10, 2);
- }
-
- //WordPress 页面添加标签和分类
- class PTCFP{
-
- function __construct(){
- add_action( 'init', array( $this, 'taxonomies_for_pages' ) );
- //确保这些查询修改不会作用于管理后台,防止文章和页面混杂
- if ( ! is_admin() ) {
- add_action( 'pre_get_posts', array( $this, 'category_archives' ) );
- add_action( 'pre_get_posts', array( $this, 'tags_archives' ) );
- }
- }
-
- //为“页面”添加“标签”和“分类”
- function taxonomies_for_pages() {
- register_taxonomy_for_object_type( 'post_tag', 'page' );
- register_taxonomy_for_object_type( 'category', 'page' );
- }
-
- //在标签存档中包含“页面”
- function tags_archives( $wp_query ) {
- if ( $wp_query->get( 'tag' ) )
- $wp_query->set( 'post_type', 'any' );
- }
-
- //在分类存档中包含“页面”
- function category_archives( $wp_query ) {
- if ( $wp_query->get( 'category_name' ) || $wp_query->get( 'cat' ) )
- $wp_query->set( 'post_type', 'any' );
- }
-
- }
-
- $ptcfp = new PTCFP();
-
- //限制文章标题输入字数
- /add_action( 'admin_head-post.php', 'title_count_js');
- //add_action( 'admin_head-post-new.php', 'title_count_js');
- function title_count_js(){
- echo '';
- }
-
- //自定义排序WordPress后台管理菜单
- //add_filter('custom_menu_order', 'custom_menu_order');
- //add_filter('menu_order', 'custom_menu_order');
- function custom_menu_order($menu_ord) {
- if (!$menu_ord) return true;
- return array(
- 'index.php', // “仪表盘”菜单
- 'edit.php?post_type=question', // 自定义文章类型的菜单
- 'edit-comments.php', //“评论”菜单
- 'upload.php', //“多媒体”菜单
- 'edit.php?post_type=cmp_slider', //自定义文章类型的菜单
- 'plugins.php', //“插件”菜单
- 'themes.php', //“主题”菜单
- 'edit.php?post_type=page', // “页面”菜单
- 'edit.php', // “文章”菜单
- );
- }
-
- //在WordPress仪表盘“概况”显示自定义文章类型数据
-
- add_action( 'right_now_content_table_end' , 'wph_right_now_content_table_end' );
- function wph_right_now_content_table_end() {
- $args = array(
- 'public' => true ,
- '_builtin' => false
- );
- $output = 'object';
- $operator = 'and';
- $post_types = get_post_types( $args , $output , $operator );
- foreach( $post_types as $post_type ) {
- $num_posts = wp_count_posts( $post_type->name );
- $num = number_format_i18n( $num_posts->publish );
- $text = _n( $post_type->labels->singular_name, $post_type->labels->name , intval( $num_posts->publish ) );
- if ( current_user_can( 'edit_posts' ) ) {
- $num = "$num";
- $text = "$text";
- }
- echo '
$post_type->name . '">' . $num . ' ';- echo '
$post_type->name . '">' . $text . ' '; - }
- $taxonomies = get_taxonomies( $args , $output , $operator );
- foreach( $taxonomies as $taxonomy ) {
- $num_terms = wp_count_terms( $taxonomy->name );
- $num = number_format_i18n( $num_terms );
- $text = _n( $taxonomy->labels->singular_name, $taxonomy->labels->name , intval( $num_terms ));
- if ( current_user_can( 'manage_categories' ) ) {
- $num = "$num";
- $text = "$text";
- }
- echo '
$taxonomy->name . '">' . $num . ' ';- echo '
$taxonomy->name . '">' . $text . ' '; - }
- }
-
- //仪表盘[活动]小工具输出自定义文章类型
-
- if ( is_admin() ) {
- add_filter( 'dashboard_recent_posts_query_args', 'wpdx_add_cpt_to_dashboard_activity' );
- function wpdx_add_cpt_to_dashboard_activity( $query ) {
- // 如果你要显示所有文章类型,就删除下行的 //,并在 11 行前面添加 //
- // $post_types = get_post_types();
- // 如果你仅仅希望显示指定的文章类型,可以修改下行的数组内容,并确保上行前面添加 //
- $post_types = ['post', 'download'];
- if ( is_array( $query['post_type'] ) ) {
- $query['post_type'] = $post_types;
- } else {
- $temp = $post_types;
- $query['post_type'] = $temp;
- }
- return $query;
- }
- }
-
- //显示所有设置菜单
-
- add_action('admin_menu', 'all_settings_link');
- function all_settings_link() {
- add_options_page(__('All Settings'), __('All Settings'), 'administrator', 'options.php');
- }
-
- /*
- * 在WordPress后台文章编辑器的上方或下方添加提示内容
- */
- add_action( 'edit_form_after_title', 'below_the_title' );
- function below_the_title() {
- echo '
在编辑器上方添加的提示内容
'; - }
- add_action( 'edit_form_after_editor', 'below_the_editor' );
- function below_the_editor() {
- echo '
在编辑器下方添加的提示内容
'; - }
-
- //后台页面管理列表中隐藏特定的页面
- add_action( 'pre_get_posts' ,'exclude_this_page' );
- function exclude_this_page( $query ) {
- if( !is_admin() )
- return $query;
- global $pagenow;
- if( 'edit.php' == $pagenow && ( get_query_var('post_type') && 'page' == get_query_var('post_type') ) )
- $query->set( 'post__not_in', array(23,28,30) ); // 页面的ID
- return $query;
- }
-
- //修改 WordPress 发送邮件的默认邮箱和发件人
- add_filter('wp_mail_from_name', 'new_from_name');
- add_filter('wp_mail_from', 'new_from_email');
- function new_from_name($email){//默认发件人
- $wp_from_name = get_option('blogname');
- return $wp_from_name;
- }
- function new_from_email($email) {//默认发件箱
- $wp_from_email = get_option('admin_email');
- return $wp_from_email;
- }
-
- //WordPress仪表盘添加自定义Feed订阅
- add_action('wp_dashboard_setup', 'ankium_add_dashboard_widgets' );
- function dashboard_custom_feed_output() {
- echo '
- wp_widget_rss_output(array(
- 'url' => 'http://www.anongyejing.com/feed/', //rss地址
- 'title' => '查看安琪云的最新内容',
- 'items' => 10, //显示篇数
- 'show_summary' => 0, //是否显示摘要,1为显示
- 'show_author' => 0, //是否显示作者,1为显示
- 'show_date' => 1 )); //是否显示日期
- echo '';
- }
- function ankium_add_dashboard_widgets() {
- wp_add_dashboard_widget('example_dashboard_widget', '订阅名', 'dashboard_custom_feed_output');
- }
-
- // 自定义WordPress图片附件的默认链接方式(’none’,’file’,’post’)
- update_option('image_default_link_type', 'file');
-
- //关闭WordPress的XML-RPC离线发布功能
- add_filter('xmlrpc_enabled', '__return_false');
-
- //恢复WordPress默认上传路径和生成文件的URL地址
- if(get_option('upload_path')=='wp-content/uploads' || get_option('upload_path')==null) {
- update_option('upload_path',WP_CONTENT_DIR.'/uploads');
- }
-
- //自定义WordPress媒体文件的上传路径和生成文件的URL地址
-
- //add_filter( 'upload_dir', 'wpjam_custom_upload_dir' );
- function wpjam_custom_upload_dir( $uploads ) {
- $upload_path = '';
- $upload_url_path = '';
-
- if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) {
- $uploads['basedir'] = WP_CONTENT_DIR . '/uploads';
- } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) {
- $uploads['basedir'] = path_join( ABSPATH, $upload_path );
- } else {
- $uploads['basedir'] = $upload_path;
- }
-
- $uploads['path'] = $uploads['basedir'].$uploads['subdir'];
-
- if ( $upload_url_path ) {
- $uploads['baseurl'] = $upload_url_path;
- $uploads['url'] = $uploads['baseurl'].$uploads['subdir'];
- }
- return $uploads;
- }
-
- //WordPress 后台管理员免密一键切换其他账号登录
- add_filter('user_row_actions', 'wpdx_user_switch_action', 10, 2);
- function wpdx_user_switch_action($actions, $user){
- $capability = (is_multisite())?'manage_site':'manage_options';
- if(current_user_can($capability)){
- $actions['login_as'] = 'wp_nonce_url("users.php?action=login_as&users=$user->ID", 'bulk-users').'">以此身份登录';
- }
- return $actions;
- }
- add_filter('handle_bulk_actions-users','wpdx_handle_user_switch_action', 10, 3);
- function wpdx_handle_user_switch_action($sendback, $action, $user_ids){
- if($action == 'login_as'){
- wp_set_auth_cookie($user_ids, true);
- wp_set_current_user($user_ids);
- }
- return admin_url();
- }
-
-
-
- //WordPress自定义文章作者名称
- add_action('post_submitbox_misc_actions', 'cus_author_createCustomField');
- add_action('save_post', 'cus_author_saveCustomField');
- add_filter('the_author','cus_author_the_author');
- /** 创建一个checkBox */
- function cus_author_createCustomField() {
- $post_id = get_the_ID();
- if (get_post_type($post_id) != 'post') {
- return;
- }
- /*
- * 提取现有的值
- * @var boolean
- */
- $value = get_post_meta($post_id, '_custom_author_name', true);
- /*
- * 添加 nonce 安全处理
- */
- wp_nonce_field('custom_author_nonce' , 'custom_author_nonce');
- ?>
- class="misc-pub-section misc-pub-section-last dashicons-before dashicons-admin-users">
- <label><b>作者:b><input type="text" value="php echo $value ?>" name="_custom_author_name" />label>
- div>
- php
- }
- //保存配置信息 $post_id 文章的ID
- function cus_author_saveCustomField($post_id) {
- //自动保存不处理
- if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
- return;
- }
- //信息不正确不处理
- if (
- !isset($_POST['custom_author_nonce']) ||
- !wp_verify_nonce($_POST['custom_author_nonce'], 'custom_author_nonce')
- ) {
- return;
- }
- //用户无权编辑文章不处理
- if (!current_user_can('edit_post', $post_id)) {
- return;
- }
- //存在此项目就更新
- if (isset($_POST['_custom_author_name'])) {
- update_post_meta($post_id, '_custom_author_name', sanitize_text_field($_POST['_custom_author_name']));
- } else {
- //不存在就删除
- delete_post_meta($post_id, '_custom_author_name');
- }
- }
- function cus_author_the_author($author){
- $custom_author = get_post_meta(get_the_ID(), '_custom_author_name');
- if ($custom_author) {
- return $custom_author[0];
- } else {
- return $author;
- }
- }
-
-
-
- //四合一简化 WordPress 后台用户个人信息姓名昵称设置
- add_action('show_user_profile','wpjam_edit_user_profile');
- add_action('edit_user_profile','wpjam_edit_user_profile');
- function wpjam_edit_user_profile($user){
- ?>
-
- jQuery(document).ready(function($) {
- $('#first_name').parent().parent().hide();
- $('#last_name').parent().parent().hide();
- $('#display_name').parent().parent().hide();
- $('.show-admin-bar').hide();
- });
-
-
- }
- //更新时候,强制设置显示名称为昵称
- add_action('personal_options_update','wpjam_edit_user_profile_update');
- add_action('edit_user_profile_update','wpjam_edit_user_profile_update');
- function wpjam_edit_user_profile_update($user_id){
- if (!current_user_can('edit_user', $user_id))
- return false;
- $user = get_userdata($user_id);
- $_POST['nickname'] = ($_POST['nickname'])?:$user->user_login;
- $_POST['display_name'] = $_POST['nickname'];
- $_POST['first_name'] = '';
- $_POST['last_name'] = '';
- }
-
- //禁用 WordPress 4.7 新增的PDF缩略图预览功能
- add_filter('fallback_intermediate_image_sizes', 'wpb_disable_pdf_previews');
- function wpb_disable_pdf_previews() {
- $fallbacksizes = array();
- return $fallbacksizes;
- }
-
-
- //新文章自动使用ID作为别名
- //作用:即使你设置固定连接结构为 %postname% ,仍旧自动生成 ID 结构的链接
- add_action( 'save_post', 'using_id_as_slug', 10, 2 );
- function using_id_as_slug($post_id, $post){
- global $post_type;
- if($post_type=='post'){ //只对文章生效
- // 如果是文章的版本,不生效
- if (wp_is_post_revision($post_id))
- return false;
- // 取消挂载该函数,防止无限循环
- remove_action('save_post', 'using_id_as_slug' );
- // 使用文章ID作为文章的别名
- wp_update_post(array('ID' => $post_id, 'post_name' => $post_id ));
- // 重新挂载该函数
- add_action('save_post', 'using_id_as_slug' );
- }
- }
-
- //根据上传时间重命名文件
- add_filter('wp_handle_upload_prefilter', 'custom_upload_filter' );
- function custom_upload_filter( $file ){
- $info = pathinfo($file['name']);
- $ext = $info['extension'];
- $filedate = date('YmdHis').rand(10,99);//为了避免时间重复,再加一段2位的随机数
- $file['name'] = $filedate.'.'.$ext;
- return $file;
- }
-
-
- //自动调用媒体库中的图片作为缩略图
- add_action('the_post', 'wpforce_featured');
- add_action('save_post', 'wpforce_featured');
- add_action('draft_to_publish', 'wpforce_featured');
- add_action('new_to_publish', 'wpforce_featured');
- add_action('pending_to_publish', 'wpforce_featured');
- add_action('future_to_publish', 'wpforce_featured');
- function wpforce_featured() {
- global $post;
- $already_has_thumb = has_post_thumbnail($post->ID);
- if (!$already_has_thumb) {
- $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
- if ($attached_image) {
- foreach ($attached_image as $attachment_id => $attachment) {
- set_post_thumbnail($post->ID, $attachment_id);
- }
- } else {
- set_post_thumbnail($post->ID, '10181');
- }
- }
- }
-
- //Wordpress 如何判断是否为微信、QQ内置浏览器访问
-
- // if (is_wx_qq()) {
- // die('网站不支持QQ或者微信内访问,请点击右上角菜单,使用外部浏览器打开网站');
- //这里可以写入你要做的任何操作,例如跳转、提示、代码
- // }
-
- function is_wx_qq(){
- $user_agent = $_SERVER['HTTP_USER_AGENT'];
- if (strpos($user_agent, 'MicroMessenger') == false && strpos($user_agent, 'QQ/') == false) {
- return false;
- } else {
- return true;
- }
- }
-
-
- //wordpress摘要去掉p标签
- remove_filter( 'the_excerpt', 'wpautop' );
-
-
-
-
-
-
-
-
-
-
-
二、Wordpress自定义字段的设定与调用代码(系统常规自定义字段)
Wordpress自定义字段
1、在wordpress主题文件functions.php中添加如下代码就可以添加一些我们常用的系统常规字段,在数据库表 wp_options 中保存。比如系统参数字段如:备案号、统计代码、phone,qq 为自定义字段名等。注:如果不知道字段名是什么可以在数据库表 wp_options查看,或者到function.php文件中找到你添加自定义字段的代码查看。
- // 自定义系统字段
- function set_global_fields() {
- $global_fields = new GlobalFields();
- $global_fields->setting_fields();
- }
- add_action( 'admin_init', 'set_global_fields' );
-
- class GlobalFields
- {
- public function setting_fields()
- {
- $text_input = [
- 'contact' => '联系人',
- 'email' => '邮箱',
- 'address' => '地址',
- 'phone' => '电话',
- 'wechat' => '微信',
- 'qq' => 'QQ',
- 'copyright' => '备案号',
- 'seo_title' => 'seo标题',
- 'seo_keywords' => 'seo关键字',
- ];
- $textarea_input = [ 'seo_description' => 'seo描述','tongji' => '统计代码' ];
- foreach($text_input as $key => $val)
- {
- $this->sonliss_settings_field($key, $val, 'sonliss_textbox_callback', [$key]);
- $this->sonliss_register_setting($key);
- }
- foreach($textarea_input as $key => $val)
- {
- $this->sonliss_settings_field($key, $val, 'sonliss_textareabox_callback', [$key]);
- $this->sonliss_register_setting($key);
- }
- }
-
- /**
- * id ID
- * title 显示在页面的标题即label
- * callback 回调
- * args []
- */
- public function sonliss_settings_field($id, $title, $callback, $args)
- {
- add_settings_field(
- $id,
- $title,
- [ $this, $callback ],
- 'general', // general, reading, writing, discussion, media
- 'default', // 块,对应add_settings_section的id
- $args
- );
- }
-
- /**
- * id ID
- */
- public function sonliss_register_setting($id)
- {
- register_setting('general', $id);
- }
-
- /**
- * input text
- */
- public function sonliss_textbox_callback($args) {
- $option = get_option($args[0]);
- echo '$args[0] .'" name="'. $args[0] .'" value="' . $option . '" class="regular-text" />';
- }
-
- /**
- * area
- */
- public function sonliss_textareabox_callback($args) {
- $option = get_option($args[0]);
- echo '[0] .'" name="'. $args[0] .'" class="regular-text">'. $option .'';
- }
- }
注:如果需要添加继续添加新的字段 单行文本 在$text_input =[] 添加新的字段名 多行文本 在$textarea_input =[] 添加新的字段
列:$textarea_input = [ 'seo_description' => 'seo描述','tongji' => '统计代码' ];
2、模板里调用:
- echo get_option('phone'); ?>
- echo get_option('qq'); ?>
三、wordpress分类栏目添加自定义字段 (例如栏目图片)
1.添加方法,将下方代码复制到 function.php 中
- class Ludou_Tax_Image{
- function __construct(){
- // 新建分类页面添加自定义字段输入框
- add_action( 'category_add_form_fields', array( $this, 'add_tax_image_field' ) );
- // 编辑分类页面添加自定义字段输入框
- add_action( 'category_edit_form_fields', array( $this, 'edit_tax_image_field' ) );
-
- // 保存自定义字段数据
- add_action( 'edited_category', array( $this, 'save_tax_meta' ), 10, 2 );
- add_action( 'create_category', array( $this, 'save_tax_meta' ), 10, 2 );
-
- }
-
- // 新建分类页面添加自定义字段输入框
-
- public function add_tax_image_field(){
- ?>
- class="form-field">
- <label for="term_meta[tax_image]">分类封面label>
- <input type="text" name="term_meta[tax_image]" id="term_meta[tax_image]" value="" />
- <p class="description">输入分类封面图片URLp>
- div>
-
-
-
-
- php
- } // add_tax_image_field
-
- /**
- * 编辑分类页面添加自定义字段输入框
- *
- * @uses get_option() 从option表中获取option数据
- * @uses esc_url() 确保字符串是url
- */
- public function edit_tax_image_field( $term ){
-
- // $term_id 是当前分类的id
- $term_id = $term->term_id;
-
- // 获取已保存的option
- $term_meta = get_option( "ludou_taxonomy_$term_id" );
- // option是一个二维数组
- $image = $term_meta['tax_image'] ? $term_meta['tax_image'] : '';
-
- /**
- * TODO: 在这里追加获取其他自定义字段值,如:
- * $keywords = $term_meta['tax_keywords'] ? $term_meta['tax_keywords'] : '';
- */
- ?>
-
class="form-field">- <th scope="row">
- <label for="term_meta[tax_image]">分类封面label>
- <td>
- <input type="text" name="term_meta[tax_image]" id="term_meta[tax_image]" value="php echo esc_url( $image ); ?>" />
- <p class="description">输入分类封面图片URLp>
- td>
- th>
- tr>
-
-
-
-
-
- php
- } // edit_tax_image_field
-
- /**
- * 保存自定义字段的数据
- *
- * @uses get_option() 从option表中获取option数据
- * @uses update_option() 更新option数据,如果没有就新建option
- */
- public function save_tax_meta( $term_id ){
-
- if ( isset( $_POST['term_meta'] ) ) {
-
- // $term_id 是当前分类的id
- $t_id = $term_id;
- $term_meta = array();
-
- // 获取表单传过来的POST数据,POST数组一定要做过滤
- $term_meta['tax_image'] = isset ( $_POST['term_meta']['tax_image'] ) ? esc_url( $_POST['term_meta']['tax_image'] ) : '';
-
- /**
- * TODO: 在这里追加获取其他自定义字段表单的值,如:
- * $term_meta['tax_keywords'] = isset ( $_POST['term_meta']['tax_keywords'] ) ? $_POST['term_meta']['tax_keywords'] : '';
- */
-
- // 保存option数组
- update_option( "ludou_taxonomy_$t_id", $term_meta );
-
- } // if isset( $_POST['term_meta'] )
- }
- }
-
- $wptt_tax_image = new Ludou_Tax_Image();
2.模板中调用方法:
- //$cat 默认为当前分类id seo-title自定义字段
-
- $post_id = "category_".$cat;
- $value = get_field( 'seo-title', $post_id );
- echo $value;
- ?>
-
- //输出图片字段
- $post_id = "category_".$cat; echo get_field('img_ioc',$post_id);?>
-
- //案例
- $post_id = "category_".$cat; ?>
echo get_field( 'seo-title', $post_id ); ?> - "keywords" content="$post_id ); ?>"/>
- "description" content="$post_id ); ?>"/>
四、文章页自定义字段添加与调用标签
1、添加
2、调用
- 1、普通自定义字段
- echo get_field('自定义字段名'); ?>
- 2、自定义图片字段
- $image = get_field('自定义字段名'); echo $image['url'];?>
五、单页自定义字段添加与调用标签
1、添加
2、调用
- 1、普通自定义字段
- echo get_field('自定义字段名'); ?>
- 2、自定义图片字段
- $image = get_field('自定义字段名'); echo $image['url'];?>
六、wordpress常用判断语句
- is_single()?> //判断是否是具体文章的页面
- is_single('2')?> //判断是否是具体文章(id=2)的页面
- is_single('Beef Stew') ?> //判断是否是具体文章(标题判断)的页面
- is_single('beef-stew') ?> //判断是否是具体文章(缩略名判断)的页面
- comments_open() ?> //是否留言开启
- pings_open() ?> //是否开启ping
- is_page() ?> //是否是页面
- is_page('42') ?> //id判断,即是否是id为42的页面
- is_page('About Me') ?> //判断标题
- is_page('about-me') ?> //缩略名判断
- is_category() ?> //是否是分类
- is_category('6') ?> //id判断,即是否是id为6的分类
- is_category('Cheeses') ?> //分类title判断
- is_category('cheeses') ?> //分类缩略名判断
- in_category('5') ?> //判断当前的文章是否属于分类5
- is_author() ?> //将所有的作者的页面显示出来
- is_author(’1337′) ?> //显示author number为1337的页面
- is_author('Elite Hacker') ?> //通过昵称来显示当前作者的页面
- is_archive() ?> //判断当前是否是归档页面
- is_search() ?> //判断是否是搜索
- is_404() ?> //判断页面是否404
- is_date()、is_year()、is_month()、is_day()、is_time() ?> //判断实现以年、月、日、时间等方式来显示归档
七、wordpress循环调用标签讲解
- //循环标签(不同页面使用以上默认循环得到的结果是不同的)
-
- while(have_posts()):the_post(); ?>
- endwhile;?>
-
- //首页会输出所有分类下面的最新文章
- //分类页会显示当前分类下的文章
- //归档页会显示符合当前归档的文章
- //内容页只会显示当前ID的文章
持续整理更新中........
-
相关阅读:
Stable Diffusion 参数介绍及用法
jdbc访问KingbaseES数据库SocketTimeoutException Read timed out
mmclassification 训练自定义数据
头歌MySQL数据库实训答案 有目录
论文复现|Panoptic Deeplab(全景分割PyTorch)
使用XLua在Unity中获取lua全局变量和函数
SpringBoot 前端406 后端Could not find acceptable representation
Django学习3 数据库
使用Redis优化Java应用的性能
spring boot 整合 sentinel
-
原文地址:https://blog.csdn.net/cnpinpai/article/details/128093567