File: /www/wwwroot/www.213n.cn/wp-content/themes/rk-blogger/wbc/common/utilities.php
<?php
/**
* Author: wbolt team
* Author URI: https://www.wbolt.com
*
*/
//获取设置数据
function wb_opt($name, $default = 0)
{
$res = class_exists('WBOptions') ? WBOptions::opt($name) : null;
return $res != null ? $res : $default;
}
//获取广告代码
function wb_insert_ad_block($ad_name = '', $box_class = 'adbanner-block')
{
return class_exists('WBOptions') ? WBOptions::inset_adblock($ad_name, $box_class) : '';
}
//处理评论区头象烂图问题
function get_ssl_avatar($avatar)
{
$https = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 1 : 0;
if ($https) return;
$avatar = preg_replace('/.*\/avatar\/(.*)\?s=([\d]+)&.*/', '<img src="https://secure.gravatar.com/avatar/$1?s=$2" class="avatar avatar-$2" height="$2" width="$2">', $avatar);
return $avatar;
}
//add_filter('get_avatar', 'get_ssl_avatar');
function wb_def_avatar($avatar_defaults)
{
$wb_avatar = get_template_directory_uri() . '/images/def_avatar.png';
$avatar_defaults[$wb_avatar] = 'wbolt';
return $avatar_defaults;
}
add_filter('avatar_defaults', 'wb_def_avatar');
//自定义菜单
class Wbolt_Walker_Nav_Menu extends Walker_Nav_Menu
{
function start_lvl(&$output, $depth = 0, $args = array())
{
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<div class=\"sub-menu lv-$depth\">\n<ul>";
}
function end_lvl(&$output, $depth = 0, $args = array())
{
$indent = str_repeat("\t", $depth);
$output .= "$indent</ul>\n</div>";
}
}
//自定义菜单
class Wbolt_Walker_Nav_Menu_m extends Walker_Nav_Menu
{
function start_lvl(&$output, $depth = 0, $args = array())
{
$indent = str_repeat("\t", $depth);
$output .= "\n$indent" . ($depth == 0 ? '<i class="nav-arrow"></i>' : '') . "<div class=\"sub-menu-m lv-$depth\"><ul>";
}
function end_lvl(&$output, $depth = 0, $args = array())
{
$indent = str_repeat("\t", $depth);
$output .= "$indent</ul>\n</div>";
}
}
//移除菜单的多余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_intersect($var, array('menu-item-has-children')) : '';
}
//详情通用变量
function wb_post_meta_val($key, $default = 0)
{
$post_id = get_the_ID();
if (!$post_id) return $default;
$val = get_post_meta($post_id, $key, true);
return $val ? $val : $default;
}
//浏览数
function wb_get_post_views($post_id)
{
$count_key = 'post_views_count';
$count = get_post_meta($post_id, $count_key, true);
if ($count == '') {
delete_post_meta($post_id, $count_key);
add_post_meta($post_id, $count_key, '0');
return '0';
}
if ($count > 1000) {
$count = intval($count / 1000) . 'K+';
}
return $count;
}
function wb_set_post_views($post_id)
{
$count_key = 'post_views_count';
$count = get_post_meta($post_id, $count_key, true);
if ($count == '') {
$count = 0;
delete_post_meta($post_id, $count_key);
add_post_meta($post_id, $count_key, '0');
} else {
$count++;
update_post_meta($post_id, $count_key, $count);
}
}
//获取一级分类菜单ID
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;
}
function get_article_category_ID()
{
$category = get_the_category();
return $category[0]->cat_ID;
}
//获取所有一级分类
function wb_get_root_category()
{
return wb_get_category(0);
}
function wb_get_root_category_id()
{
$term_list = wb_get_category(0);
$ret = array();
foreach ($term_list as $term) {
$ret[] = $term['term_id'];
}
return $ret;
}
function wb_get_category($cid = null)
{
global $wpdb;
$cate_list = array();
$tm_1 = $wpdb->terms;
$tm_2 = $wpdb->term_taxonomy;
$sql = "SELECT b.name,b.slug,a.parent,a.term_id FROM $tm_2 a,$tm_1 b WHERE a.term_id=b.term_id AND a.taxonomy='category' order by a.parent";
$term_list = $wpdb->get_results($sql, ARRAY_A);
foreach ($term_list as $term) {
if (!isset($cate_list[$term['parent']])) {
$cate_list[$term['parent']] = array();
}
$cate_list[$term['parent']][] = $term;
// $term_list2[$term['term_id']] = $term;
}
if ($cid !== null) {
return $cate_list[$cid];
}
return $cate_list;
}
function wb_get_category_count($cid = '')
{
// 获取当前分类信息
$cat = get_category($cid);
if (!$cat) {
return false;
}
// 当前分类文章数
$count = (int) $cat->count;
// 获取当前分类所有子孙分类
$tax_terms = get_terms('category', array('child_of' => $cid));
foreach ($tax_terms as $tax_term) {
// 子孙分类文章数累加
$count += $tax_term->count;
}
return $count;
}
//缩略图
/**
* Display an optional post thumbnail.
*/
function wbolt_post_thumbnail($post_id = null, $size = 'post-thumbnail', $echo = true)
{
$html = '';
if (has_post_thumbnail($post_id) && get_the_post_thumbnail($post_id) !== '') {
$html = get_the_post_thumbnail($post_id, $size, array('alt' => get_the_title($post_id)));
} elseif ($img = wbolt_catch_first_image($post_id)) {
if (isset($img['src'])) {
$html = '<img class="auto-cover' . $img['spc_class'] . '" src="' . $img['src'] . '" loading="lazy" decoding="async" alt="' . get_the_title($post_id) . '">';
} else {
$html = '<img src="' . wb_def_image() . '" alt="' . get_the_title($post_id) . '">';
}
} else {
$html = '<img src="' . wb_def_image() . '" alt="' . get_the_title($post_id) . '">';
}
if ($echo) echo $html;
return $html;
}
//抽取文章第一张图
function wbolt_catch_first_image($post_id = null)
{
$post = get_post($post_id);
$first_img = array();
if (preg_match_all('#<img[^>]+>#is', $post->post_content, $match)) {
$match_frist = $match[0][0];
if ($match_frist) :
preg_match('#src=[\'"]([^\'"]+)[\'"]#', $match_frist, $src);
preg_match('#width=[\'"]([^\'"]+)[\'"]#', $match_frist, $width);
preg_match('#height=[\'"]([^\'"]+)[\'"]#', $match_frist, $height);
$first_img['src'] = $src ? $src[1] : '';
$first_img['width'] = $width ? $width[1] : '';
$first_img['height'] = $height ? $height[1] : '';
endif;
}
/**
* 高宽比不一致时设定特别类名
*/
$first_img['spc_class'] = '';
if (isset($first_img['height']) && $first_img['height']) {
$o_rate = round(($first_img['height'] / $first_img['width']), 4);
$opt_rate = get_thumb_rate();
$first_img['spc_class'] = (($o_rate <= $opt_rate) ? ' spc' : '');
}
return $first_img;
}
/**
* 返回主体内容图片sizes设定
* @param $sizes
* @param $size
*
* @return string
*/
function wbolt_content_image_sizes_attr($sizes, $size)
{
if (WB_CONTENT_WIDTH_CNF <= $size[0]) {
$sizes = WB_CONTENT_IMG_SIZES_CNF;
}
return $sizes;
}
add_filter('wp_calculate_image_sizes', 'wbolt_content_image_sizes_attr', 10, 2);
/**
* Add custom image sizes attribute to enhance responsive image functionality
* for post thumbnails
*/
function wbolt_post_thumbnail_sizes_attr($attr, $attachment, $size)
{
if (is_admin() || (isset($_REQUEST['action']) && $_REQUEST['action'] != 'wb_lazy_load')) return $attr;
/**
* 定义size
*/
if ('post-thumbnail' === $size) {
$attr['sizes'] = WB_THUMBNAIL_SIZES_CNF;
}
/**
* 高宽比不一致时设定特别类名
*/
$size_info = wp_get_attachment_image_src($attachment->ID, 'post-thumbnail');
if ($size_info[2] && $size_info[1]) {
$o_rate = round(($size_info[2] / $size_info[1]), 4);
$opt_rate = get_thumb_rate();
$attr['class'] .= (($o_rate <= $opt_rate) ? ' spc' : '');
}
return $attr;
}
add_filter('wp_get_attachment_image_attributes', 'wbolt_post_thumbnail_sizes_attr', 10, 3);
/***
* 列表文章概要字数重置
*/
function wb_excerpt_length($length)
{
return $length;
}
add_filter('excerpt_length', 'wb_excerpt_length');
function wb_excerpt_more()
{
return '...';
}
add_filter('excerpt_more', 'wb_excerpt_more');
/**
* 插入svg icon
* e.g. wbolt_svg_icon('icon-time');
*/
function wbolt_svg_icon($name, $size_class = '')
{
return '<svg class="wb-icon ' . $name . ($size_class ? ' ' . $size_class : '') . '"><use xlink:href="#' . $name . '"></use></svg>';
}
/**
* favicon 图标
*/
if (wb_opt('favicon')) {
function wb_favicon()
{
echo '<link rel="shortcut icon" href="' . wb_opt('favicon') . '" />' . "\n";
}
add_action('admin_head', 'wb_favicon');
add_action('wp_head', 'wb_favicon');
}
/**
* 封面图比例
*/
function get_thumb_rate()
{
$rate = wb_opt('thumbnail_rate');
$rate = $rate ? $rate : '3:2';
$arr = explode(":", $rate);
return round((int)$arr[1] / (int)$arr[0], 4);
}
/**
* 默认图
*/
function wb_def_image()
{
return wb_opt('def_img_url', 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==');
}
if (!function_exists('wbolt_header')) {
function body_class_name($classes)
{
global $is_IE;
if ($is_IE) {
$classes[] = 'ie';
}
if (wp_is_mobile()) {
$classes[] = 'wb-is-mobile';
}
return $classes;
}
add_filter('body_class', 'body_class_name');
function wbolt_header()
{
wp_enqueue_style('wbolt-style', get_template_directory_uri() . '/css/style_wbolt.css', false, WB_ASSETS_VER);
wp_enqueue_script('wbolt-base', get_template_directory_uri() . '/js/base.js', false, WB_ASSETS_VER, true);
if (wb_opt('jquery_switch')) {
wp_enqueue_script("jquery");
}
}
add_action('wp_enqueue_scripts', 'wbolt_header');
}
/**
* 移除jquery_migrate.js
*/
function dequeue_jquery_migrate($scripts)
{
if (!is_admin() && !empty($scripts->registered['jquery'])) {
$scripts->registered['jquery']->deps = array_diff(
$scripts->registered['jquery']->deps,
['jquery-migrate']
);
}
}
add_action('wp_default_scripts', 'dequeue_jquery_migrate');
function wb_enqueue_jquery()
{
wp_enqueue_script("jquery");
}
/**
* 禁用古腾堡
*/
if (wb_opt('gutenberg_switch')) {
add_filter('use_block_editor_for_post_type', function ($is_user, $post_type) {
return false;
}, 10, 2);
//WordPress 5.0+ 移除 block-library CSS
add_action('wp_enqueue_scripts', 'tonjay_remove_block_library_css', 100);
function tonjay_remove_block_library_css()
{
wp_dequeue_style('wp-block-library');
}
}
// 搜索只显示 post
function search_filter_page($query)
{
if ($query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}
add_filter('pre_get_posts', 'search_filter_page');
// 建议插件
add_action('tgmpa_register', 'wbolt_register_required_plugins');
function wbolt_register_required_plugins()
{
$plugins = array(
array(
'name' => 'Smart SEO Tool', // The plugin name.
'slug' => 'smart-seo-tool', // The plugin slug (typically the folder name).
'source' => 'https://downloads.wordpress.org/plugin/smart-seo-tool.zip', // The plugin source.
'required' => false, // If false, the plugin is only 'recommended' instead of required.
'external_url' => 'https://wordpress.org/plugins/smart-seo-tool/', // If set, overrides default API URL and points to an external URL.
),
array(
'name' => '搜索推送收录管理',
'slug' => 'baidu-submit-link',
'source' => 'https://downloads.wordpress.org/plugin/baidu-submit-link.zip',
'required' => false,
'external_url' => 'https://wordpress.org/plugins/baidu-submit-link/',
),
array(
'name' => '搜索引擎蜘蛛分析插件',
'slug' => 'spider-analyser',
'source' => 'https://downloads.wordpress.org/plugin/spider-analyser.zip',
'required' => false,
'external_url' => 'https://wordpress.org/plugins/spider-analyser/',
),
array(
'name' => '热门关键词推荐插件',
'slug' => 'smart-keywords-tool',
'source' => 'https://downloads.wordpress.org/plugin/smart-keywords-tool.zip',
'required' => false,
'external_url' => 'https://wordpress.org/plugins/smart-keywords-tool/',
),
array(
'name' => '图片采集抓取插件',
'slug' => 'imgspider',
'source' => 'https://downloads.wordpress.org/plugin/imgspider.zip',
'required' => false,
'external_url' => 'https://wordpress.org/plugins/imgspider/',
),
array(
'name' => 'WordPress性能优化插件',
'slug' => 'wpturbo',
'source' => 'https://downloads.wordpress.org/plugin/wpturbo.zip',
'required' => false,
'external_url' => 'https://wordpress.org/plugins/wpturbo/',
),
array(
'name' => '文章管理功能增强插件',
'slug' => 'magicpost',
'source' => 'https://downloads.wordpress.org/plugin/magicpost.zip',
'required' => false,
'external_url' => 'https://wordpress.org/plugins/magicpost/',
),
);
$config = array(
'id' => 'wbolt', // Unique ID for hashing notices for multiple instances of TGMPA.
'default_path' => '', // Default absolute path to bundled plugins.
'menu' => 'tgmpa-install-plugins', // Menu slug.
'parent_slug' => 'wbs', // Parent menu slug.
'capability' => 'edit_theme_options', // Capability needed to view plugin install page, should be a capability associated with the parent menu used.
'has_notices' => true, // Show admin notices or not.
'dismissable' => true, // If false, a user cannot dismiss the nag message.
'dismiss_msg' => '', // If 'dismissable' is false, this message will be output at top of nag.
'is_automatic' => false, // Automatically activate plugins after installation or not.
'message' => '', // Message to output right before the plugins table.
);
tgmpa($plugins, $config);
}
/**
* 友链输出
*/
function wb_get_links()
{
return WBOptions::wb_get_links();
}
/**
* 判断文章中是否有图片
*/
function is_has_image()
{
if (is_single() || is_page()) {
global $post;
if (has_post_thumbnail()) return true;
$content = $post->post_content;
preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?:|\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER);
if (!empty($strResult[1])) return true;
return false;
}
}
/**
* 友链开关
* @return bool
*/
function wb_links_switch()
{
return wb_opt('links_section_switch');
}
function get_wb_related_posts($optinos = array(
'mode' => 'img',
'max' => 3
))
{
if (wp_is_mobile()) {
return WB_Related_Post::related_posts_html();
}
return WB_Related_Post::related_posts_html($optinos);
}
/**
* 小工具开关
*
*/
function wb_dynamic_sidebar_switch()
{
return wb_opt('dynamic_sidebar_switch', false) == 1;
}
/**
* 数组合并
*
* @param [type] $array1
* @param [type] $array2
* @return void
*/
function wb_array_merge($array1, $array2)
{
foreach ($array2 as $key => $value) {
if (is_int($key)) {
array_push($array1, $value);
} elseif (is_array($value) && isset($array1[$key]) && is_array($array1[$key])) {
$array1[$key] = wb_array_merge($array1[$key], $value);
} else {
$array1[$key] = $value;
}
}
return $array1;
}
if (!function_exists('wb_member_url')) {
function wb_member_url()
{
if (class_exists('WBMember')) {
return esc_url(home_url('?wbp=member'));
}
return admin_url();
}
}