34 次查询 耗时 0.013 秒
共写了10027个字,约17分钟读完,有13条留言
登录/注册
  • 首页
  • »
  • Notes
  • »
  • WordPress主题开发必备的10个函数
  • WordPress主题开发必备的10个函数

    作者:Misshylsay

    日期:2020年03月18日

    在WordPress主题开发的时候,有几个必备的函数,在这里给大家罗列一下:

    1、去除分类代码标志category

    //去除分类标志代码
    add_action( 'load-themes.php',  'no_category_base_refresh_rules');
    add_action('created_category', 'no_category_base_refresh_rules');
    add_action('edited_category', 'no_category_base_refresh_rules');
    add_action('delete_category', 'no_category_base_refresh_rules');
    function no_category_base_refresh_rules() {
        global $wp_rewrite;
        $wp_rewrite -> flush_rules();
    }
    // register_deactivation_hook(__FILE__, 'no_category_base_deactivate');
    // function no_category_base_deactivate() {
    //  remove_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');
    //  // We don't want to insert our custom rules again
    //  no_category_base_refresh_rules();
    // }
    // Remove category base
    add_action('init', 'no_category_base_permastruct');
    function no_category_base_permastruct() {
        global $wp_rewrite, $wp_version;
        if (version_compare($wp_version, '3.4', '<')) {
            // For pre-3.4 support
            $wp_rewrite -> extra_permastructs['category'][0] = '%category%';
        } else {
            $wp_rewrite -> extra_permastructs['category']['struct'] = '%category%';
        }
    }
    // Add our custom category rewrite rules
    add_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');
    function no_category_base_rewrite_rules($category_rewrite) {
        //var_dump($category_rewrite); // For Debugging
        $category_rewrite = array();
        $categories = get_categories(array('hide_empty' => false));
        foreach ($categories as $category) {
            $category_nicename = $category -> slug;
            if ($category -> parent == $category -> cat_ID)// recursive recursion
                $category -> parent = 0;
            elseif ($category -> parent != 0)
                $category_nicename = get_category_parents($category -> parent, false, '/', true) . $category_nicename;
            $category_rewrite['(' . $category_nicename . ')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
            $category_rewrite['(' . $category_nicename . ')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
            $category_rewrite['(' . $category_nicename . ')/?$'] = 'index.php?category_name=$matches[1]';
        }
        // Redirect support from Old Category Base
        global $wp_rewrite;
        $old_category_base = get_option('category_base') ? get_option('category_base') : 'category';
        $old_category_base = trim($old_category_base, '/');
        $category_rewrite[$old_category_base . '/(.*)$'] = 'index.php?category_redirect=$matches[1]';
        //var_dump($category_rewrite); // For Debugging
        return $category_rewrite;
    }
    // Add 'category_redirect' query variable
    add_filter('query_vars', 'no_category_base_query_vars');
    function no_category_base_query_vars($public_query_vars) {
        $public_query_vars[] = 'category_redirect';
        return $public_query_vars;
    }
    // Redirect if 'category_redirect' is set
    add_filter('request', 'no_category_base_request');
    function no_category_base_request($query_vars) {
        //print_r($query_vars); // For Debugging
        if (isset($query_vars['category_redirect'])) {
            $catlink = trailingslashit(get_option('home')) . user_trailingslashit($query_vars['category_redirect'], 'category');
            status_header(301);
            header("Location: $catlink");
            exit();
        }
        return $query_vars;
    }

    2、禁用谷歌字体

    //谷歌字体
    function remove_open_sans() {
        wp_deregister_style( 'open-sans' );
        wp_register_style( 'open-sans', false );
        wp_enqueue_style('open-sans','');
    }
    add_action( 'init', 'remove_open_sans' );

    3、禁json

    //禁json
    add_filter('rest_enabled', '_return_false');
    add_filter('rest_jsonp_enabled', '_return_false');
    remove_action( 'wp_head', 'rest_output_link_wp_head', 10 );
    remove_action( 'wp_head', 'wp_oembed_add_discovery_links', 10 );

    4、禁emoj

    //禁emoj
    function disable_embeds_init() {
        /* @var WP $wp */
        global $wp;
        // Remove the embed query var.
        $wp->public_query_vars = array_diff( $wp->public_query_vars, array(
            'embed',
        ) );
        // Remove the REST API endpoint.
        remove_action( 'rest_api_init', 'wp_oembed_register_route' );
        // Turn off
        add_filter( 'embed_oembed_discover', '__return_false' );
        // Don't filter oEmbed results.
        remove_filter( 'oembed_dataparse', 'wp_filter_oembed_result', 10 );
        // Remove oEmbed discovery links.
        remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
        // Remove oEmbed-specific JavaScript from the front-end and back-end.
        remove_action( 'wp_head', 'wp_oembed_add_host_js' );
        add_filter( 'tiny_mce_plugins', 'disable_embeds_tiny_mce_plugin' );
        // Remove all embeds rewrite rules.
        add_filter( 'rewrite_rules_array', 'disable_embeds_rewrites' );
    }
    add_action( 'init', 'disable_embeds_init', 9999 );

    5、冒充评论检验

    //冒充评论检验
    function CheckEmailAndName(){
    	global $wpdb;
    	$comment_author       = ( isset($_POST['author']) )  ? trim(strip_tags($_POST['author'])) : null;
    	$comment_author_email = ( isset($_POST['email']) )   ? trim($_POST['email']) : null;
    	if(!$comment_author || !$comment_author_email){
    		return;
    	}
    	$result_set = $wpdb->get_results("SELECT display_name, user_email FROM $wpdb->users WHERE display_name = '" . $comment_author . "' OR user_email = '" . $comment_author_email . "'");
    	if ($result_set) {
    		if ($result_set[0]->display_name == $comment_author){
    			err(__('警告: 您不能使用博主的昵称!'));
    		}else{
    			err(__('警告: 您不能使用博主的邮箱!'));
    		}
    		fail($errorMessage);
    	}
    }
    add_action('pre_comment_on_post', 'CheckEmailAndName');

    6、评论回复邮件通知(所有回复都邮件通知)*(美化版)

    //评论回复邮件通知(所有回复都邮件通知)*(美化版)
    function comment_mail_notify($comment_id) {
    $comment = get_comment($comment_id);
    $parent_id = $comment->comment_parent ? $comment->comment_parent : '';
    $spam_confirmed = $comment->comment_approved;
    if (($parent_id != '') && ($spam_confirmed != 'spam')) {
    $wp_email = 'no-reply@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME'])); //e-mail 发出点, no-reply 可改为可用的 e-mail.
    $to = trim(get_comment($parent_id)->comment_author_email);
    $subject = '您在 [' . get_option("blogname") . '] 的留言有了回复';
    $message = '
    <div style="background-color:#fff; border:1px solid #666666; color:#111;
    -moz-border-radius:8px; -webkit-border-radius:8px; -khtml-border-radius:8px;
    border-radius:8px; font-size:12px; width:702px; margin:0 auto; margin-top:10px;
    font-family:微软雅黑, Arial;">
    <div style="background:#666666; width:100%; height:60px; color:white;
    -moz-border-radius:6px 6px 0 0; -webkit-border-radius:6px 6px 0 0;
    -khtml-border-radius:6px 6px 0 0; border-radius:6px 6px 0 0; ">
    <span style="height:60px; line-height:60px; margin-left:30px; font-size:12px;">
    您在<a style="text-decoration:none; color:#00bbff;font-weight:600;"
    href="' . get_option('home') . '">' . get_option('blogname') . '
    </a>博客上的留言有回复啦!</span></div>
    <div style="width:90%; margin:0 auto">
    <p>' . trim(get_comment($parent_id)->comment_author) . ', 您好!</p>
    <p>您曾在 [' . get_option("blogname") . '] 的文章
    《' . get_the_title($comment->comment_post_ID) . '》 上发表评论:
    <p style="background-color: #EEE;border: 1px solid #DDD;
    padding: 20px;margin: 15px 0;">' . nl2br(get_comment($parent_id)->comment_content) . '</p>
    <p>' . trim($comment->comment_author) . ' 给您的回复如下:
    <p style="background-color: #EEE;border: 1px solid #DDD;padding: 20px;
    margin: 15px 0;">' . nl2br($comment->comment_content) . '</p>
    <p>您可以点击 <a style="text-decoration:none; color:#00bbff"
    href="' . htmlspecialchars(get_comment_link($parent_id)) . '">查看回复的完整內容</a></p>
    <p>欢迎再次光临 <a style="text-decoration:none; color:#00bbff"
    href="' . get_option('home') . '">' . get_option('blogname') . '</a></p>
    <p>(此邮件由系统自动发出, 请勿回复.)</p>
    </div>
    </div>';
    $message = convert_smilies($message);
    $from = "From: \"" . get_option('blogname') . "\" <$wp_email>";
    $headers = "$from\nContent-Type: text/html; charset=" . get_option('blog_charset') . "\n";
    wp_mail( $to, $subject, $message, $headers );
    //echo 'mail to ', $to, '<br/> ' , $subject, $message; // for testing
    }
    }
    add_action('comment_post', 'comment_mail_notify');

    7、移除顶部多余信息

    //移除顶部多余信息
    remove_action( 'wp_head', 'feed_links', 2 ); //移除feed
    remove_action( 'wp_head', 'feed_links_extra', 3 ); //移除feed
    remove_action( 'wp_head', 'rsd_link' ); //移除离线编辑器开放接口
    remove_action( 'wp_head', 'wlwmanifest_link' );  //移除离线编辑器开放接口
    remove_action( 'wp_head', 'index_rel_link' );//去除本页唯一链接信息
    remove_action('wp_head', 'parent_post_rel_link', 10, 0 );//清除前后文信息
    remove_action('wp_head', 'start_post_rel_link', 10, 0 );//清除前后文信息
    remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );
    remove_action( 'wp_head', 'locale_stylesheet' );
    remove_action('publish_future_post','check_and_publish_future_post',10, 1 );
    remove_action( 'wp_head', 'noindex', 1 );
    remove_action( 'wp_head', 'wp_print_styles', 8 );//载入css
    remove_action( 'wp_head', 'wp_print_head_scripts', 9 );
    remove_action( 'wp_head', 'wp_generator' ); //移除WordPress版本
    remove_action( 'wp_head', 'rel_canonical' );
    remove_action( 'wp_footer', 'wp_print_footer_scripts' );
    remove_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 );
    remove_action( 'template_redirect', 'wp_shortlink_header', 11, 0 );
    add_action('widgets_init', 'my_remove_recent_comments_style');
    function my_remove_recent_comments_style() {
    global $wp_widget_factory;
    remove_action('wp_head', array($wp_widget_factory->widgets['WP_Widget_Recent_Comments'] ,'recent_comments_style'));
    }

    8、删除仪表盘模块

    //删除仪表盘模块
    function example_remove_dashboard_widgets() {
        // Globalize the metaboxes array, this holds all the widgets for wp-admin
        global $wp_meta_boxes;
        // 以下这一行代码将删除 "快速发布" 模块
        unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']);
        // 以下这一行代码将删除 "引入链接" 模块
        unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);
        // 以下这一行代码将删除 "插件" 模块
        unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);
        // 以下这一行代码将删除 "近期评论" 模块
        unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']);
        // 以下这一行代码将删除 "近期草稿" 模块
        unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_recent_drafts']);
        // 以下这一行代码将删除 "WordPress 开发日志" 模块
        unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
        // 以下这一行代码将删除 "其它 WordPress 新闻" 模块
        unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);
        // 以下这一行代码将删除 "概况" 模块
        unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']);
    }
    add_action('wp_dashboard_setup', 'example_remove_dashboard_widgets' );

    9、垃圾评论过滤

    /* 垃圾评论 */  
    function refused_spam_comments( $comment_data ) {  
    $pattern = '/[一-龥]/u';  
    if(!preg_match($pattern,$comment_data['comment_content'])) {  
    err('评论必须含中文!');  
    }  
    return( $comment_data );  
    }  
    add_filter('preprocess_comment','refused_spam_comments');

    10、头像本地缓存,主题根目录下新建一个avatar文件夹。

    //头像本地缓存
    function lerm_avatar_cache( $avatar ){
        $tmp  = strpos( $avatar, 'http' );
        $g    = substr( $avatar, $tmp, strpos( $avatar, '\'', $tmp ) - $tmp );
        $tmp  = strpos( $g, 'avatar/' ) + 7;
        $f    = substr( $g, $tmp, strpos( $g, '?', $tmp ) - $tmp );//匹配图片名称
        $e    = get_template_directory() . '/avatar/' . $f . '.png';//图片缓存路径
        $t    = 604800; //缓存天数
        if( !is_file( $e ) || ( time() - filemtime( $e ) ) > $t ) copy( htmlspecialchars_decode( $g ), $e );
        else $avatar = strtr( $avatar, array( $g => get_template_directory_uri() . '/avatar/' . $f . '.png' ) );
        if( filesize( $e ) < 500 ) copy( get_template_directory()  . '/avatar/default.png', $e );
        return $avatar;
    }
    add_filter('get_avatar', 'lerm_avatar_cache' );

     

    — 原文地址:WordPress主题开发必备的10个函数
    — 文内标签:

    “WordPress主题开发必备的10个函数”共有13条评论

    1. ivermectin tablets

      俄罗斯 谷歌浏览器 Windows 8.1
    2. clomid fertility drug

      俄罗斯 谷歌浏览器 Windows 10
    3. zoloft generic 50mg

      俄罗斯 谷歌浏览器 Windows 10
    4. anafranil 50 mg

      俄罗斯 谷歌浏览器 Windows 10
    5. generic seroquel

      俄罗斯 谷歌浏览器 Windows 7
    6. synthroid 0.1 mg

      俄罗斯 谷歌浏览器 Windows 8
    7. propecia uk price comparison

      俄罗斯 谷歌浏览器 Windows 10
    8. seroquel 400

      俄罗斯 谷歌浏览器 Windows 10
    9. how can i get propecia

      俄罗斯 谷歌浏览器 Windows 10
    10. tadalafil cost uk

      俄罗斯 谷歌浏览器 Windows 10
    11. viagra medicine price in india

      俄罗斯 谷歌浏览器 Windows 10
    12. cialis over the counter in usa

      俄罗斯 谷歌浏览器 Windows 8.1
    13. yVWxkGBH

      乌克兰

    发表评论

    B em del U Link Code Quote