使用wordpress国外主题需要的一些代码

文章 1个月前 gary0806
43 0

记录使用wordpress国外主题需要的一些代码

/**
 * WordPress 在文章内容中间插入广告
 */
//在文章内容的第二段后面插入广告
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
    $ad_code = '<div><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- zishiying2 -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-7084165558570623"
     data-ad-slot="8417933659"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><p></p></div>'; 
    if ( is_single() && ! is_admin() ) {
        // 修改 2 这个段落数
        return prefix_insert_after_paragraph( $ad_code, 2, $content );
    }
    return $content;
}
 
// 插入广告所需的功能代码
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
    $closing_p = '</p>';
    $paragraphs = explode( $closing_p, $content );
    foreach ($paragraphs as $index => $paragraph) {
        if ( trim( $paragraph ) ) {
            $paragraphs[$index] .= $closing_p;
        }
        if ( $paragraph_id == $index + 1 ) {
            $paragraphs[$index] .= $insertion;
        }
    }
    return implode( '', $paragraphs );
}
/* 嗨趣儿 —— https://www.hiquer.com 自动为文章内的标签添加内链开始 */
$match_num_from = 1; //一篇文章中同一个标签少于几次不自动链接
$match_num_to = 1; //一篇文章中同一个标签最多自动链接几次
function tag_sort($a, $b){
 if ( $a->name == $b->name ) return 0;
 return ( strlen($a->name) > strlen($b->name) ) ? -1 : 1;
}
function tag_link($content){
 global $match_num_from,$match_num_to;
 $posttags = get_tags();
 if ($posttags) {
 usort($posttags, "tag_sort");
 foreach($posttags as $tag) {
 $link = get_tag_link($tag->term_id);
 $keyword = $tag->name;
 $cleankeyword = stripslashes($keyword);
 $url = "<a href=\"$link\" title=\"".str_replace('%s',addcslashes($cleankeyword, '$'),__('【查看含有[%s]标签的文章】'))."\"";
 $url .= ' target="_blank"';
 $url .= ">".addcslashes($cleankeyword, '$')."</a>";
 $limit = rand($match_num_from,$match_num_to);
 $content = preg_replace( '|(<a[^>]+>)(.*)('.$ex_word.')(.*)(</a[^>]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
 $content = preg_replace( '|(<img)(.*?)('.$ex_word.')(.*?)(>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
 $cleankeyword = preg_quote($cleankeyword,'\'');
 $regEx = '\'(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s' . $case;
 $content = preg_replace($regEx,$url,$content,$limit);
 $content = str_replace( '%&&&&&%', stripslashes($ex_word), $content);
 }
 }
 return $content;
}
add_filter('the_content','tag_link',1);
/* 自动为文章内的标签添加内链结束 */
function refused_spam_comments($comment_data) {
 $pattern = '/[一-龥]/u';
 $jpattern = '/[ぁ-ん]+|[ァ-ヴ]+/u';
 if (!preg_match($pattern, $comment_data['comment_content'])) {
 err(__('来一波汉字吧,苦逼的站长只认识汉字!You should type some Chinese word!'));
 }
 if (preg_match($jpattern, $comment_data['comment_content'])) {
 err(__('关于日语,站长勉强听懂雅蠛蝶 Japanese Get out!日本语出て行け! You should type some Chinese word!'));
 }
 return ($comment_data);
}
 add_filter('preprocess_comment', 'refused_spam_comments');

/**
    *自动添加图片 alt 和 title 属性
*/
function image_alttitle( $imgalttitle ){
        global $post;
        $category = get_the_category();
        $flname=$category[0]->cat_name;
        $btitle = get_bloginfo();
        $imgtitle = $post->post_title;
        $imgUrl = "<img\s[^>]*src=(\"??)([^\" >]*?)\\1[^>]*>";
        if(preg_match_all("/$imgUrl/siU",$imgalttitle,$matches,PREG_SET_ORDER)){
                if( !empty($matches) ){
                        for ($i=0; $i < count($matches); $i++){
                                $tag = $url = $matches[$i][0];
                                $j=$i+1;
                                $judge = '/title=/';
                                preg_match($judge,$tag,$match,PREG_OFFSET_CAPTURE);
                                if( count($match) < 1 )
                                $altURL = ' alt="'.$imgtitle.' '.$flname.' 第'.$j.'张" title="'.$imgtitle.' '.$flname.' 第'.$j.'张-'.$btitle.'" ';
                                $url = rtrim($url,'>');
                                $url .= $altURL.'>';
                                $imgalttitle = str_replace($tag,$url,$imgalttitle);
                        }
                }
        }
        return $imgalttitle;
}
add_filter( 'the_content','image_alttitle');
/**
    *后台添加链接模块
*/
add_filter( 'pre_option_link_manager_enabled', '__return_true' );
/* 自动给站外链接添加nofollow属性和新窗口打开 www.hiquer.com 开始*/
 
add_filter('the_content', 'auto_nofollow'); //nofollow文章中的站外链接
 
add_filter('comment_text', 'auto_nofollow'); //nofollow评论中的站外链接
 
function auto_nofollow($content) {
 //return stripslashes(wp_rel_nofollow($content));
 
 return preg_replace_callback('/<a>]+/', 'auto_nofollow_callback', $content);
}
 
function auto_nofollow_callback($matches) {
 $link = $matches[0];
 $site_link = get_bloginfo('url');
 
 if (strpos($link, 'rel') === false) {
 $link = preg_replace("%(href=S(?!$site_link))%i", 'rel="nofollow" $1', $link);
 } elseif (preg_match("%href=S(?!$site_link)%i", $link)) {
 $link = preg_replace('/rel=S(?!nofollow)S*/i', 'rel="nofollow"', $link);
 }
 return $link;
}
/* 自动给站外链接添加nofollow属性和新窗口打开 www.hiquer.com 结束*/
//在所有文章底部添加自定义内容
function add_after_post_content($content) {
    if(!is_feed() && !is_home() && is_singular() && is_main_query()) {
        $content .= '<div class="share-component" data-disabled="diandian,google,twitter,facebook"></div>';
    }
    return $content;
}
add_filter('the_content', 'add_after_post_content');
//去除分类标志代码
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;
}
//文章显示最后更新时间
function wpb_last_updated_date( $content ) {
$u_time = get_the_time('U'); 
$u_modified_time = get_the_modified_time('U'); 
$custom_content = ''; 
if ($u_modified_time >= $u_time + 86400) { 
$updated_date = get_the_modified_time('F jS, Y');
$updated_time = get_the_modified_time('h:i a'); 
$custom_content .= '<p class="last-updated">Last updated on '. $updated_date . ' at '. $updated_time .'</p>';  
} 
 
    $custom_content .= $content;
    return $custom_content;
}
add_filter( 'the_content', 'wpb_last_updated_date' );
//防止网站标题中的 “-” 被转义成 “& #8211;”
add_filter( 'run_wptexturize', '__return_false' );
//去除谷歌字体
class Disable_Google_Fonts {
public function __construct() {
add_filter( 'gettext_with_context', array( $this, 'disable_open_sans' ), 888, 4 );
}
public function disable_open_sans( $translations, $text, $context, $domain ) {
if ( 'Open Sans font: on or off' == $context && 'on' == $text ) {
$translations = 'off';
}
return $translations;
}
}
$disable_google_fonts = new Disable_Google_Fonts;

/**
 * Plugin Name: WPDX Replace Open Sans
 * Version:     1.0
 * License:     GPL
 */
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文章内容输入微信公众号验证码可见
function secret($atts, $content=null){
    extract(shortcode_atts(array('wxgzh'=>null,'keyword'=>null,'key'=>null,'gzh_img'=>null), $atts));
    if(isset($_POST['secret_key']) && $_POST['secret_key']==$key){
        return '<div class="secret-password">'.$content.'</div>';
      }
    else {
    return '
        <div class="post_hide_box">
            <img class="erweima" align="right" src="'.$gzh_img.'" width="160" height="160" alt="公众号二维码加载失败~~~"><div class="post-secret"><i class="fa fa-exclamation-circle"></i>此处内容已经被作者无情的隐藏,请输入验证码查看内容</div>
            <form action="'.get_permalink().'" method="post"> 
                <span>验证码:</span><input id="pwbox" type="password" size="20" name="secret_key">
                <a class="a2" href="javascript:;"><input type="submit" value="提交" name="Submit"></a>
            </form>
            <div class="details">请关注“<span>'.$wxgzh.'</span>”官方公众号,回复关键字“<span>'.$keyword.'</span>”,获取验证码。<br/>
            <span>【注】</span>手机扫描二维码快速关注“<span>'.$wxgzh.'</span>”官方公众号(sihaiba)。
        </div>
         </div>';
      }
}
add_shortcode('ghide', 'secret');
 
//文章编辑器添加按钮
function wpsites_add_gzh_quicktags() {
    if (wp_script_is('quicktags')){
?>
    <script type="text/javascript">
    QTags.addButton( 'ghide', ' 公众号隐藏', '\n[ghide wxgzh="四海吧" keyword="暗号" key="886" gzh_img="https://sihaiba.com/wp-content/uploads/2019/10/sihaiba.jpg"]隐藏内容[/ghide]', "" );
    </script>
<?php
    }
}
add_action( 'admin_print_footer_scripts', 'wpsites_add_gzh_quicktags' );
//禁用古腾堡
add_filter('use_block_editor_for_post', '__return_false');
remove_action( 'wp_enqueue_scripts', 'wp_common_block_scripts_and_styles' );
//移除 WordPress XML 站点地图
add_filter( 'wp_sitemaps_enabled', '__return_false' );

 

版权声明:gary0806 发表于 2020-08-11 19:45:06。
转载请注明:使用wordpress国外主题需要的一些代码 | 微目录