File: /www/wwwroot/q.autos58.cn/wp-content/themes/kong20/inc/functions/core-function.php
<?php
defined('ABSPATH') || exit;
if (!_hua('display_wp_update')) {
remove_action('admin_init', '_maybe_update_core');
remove_action('admin_init', '_maybe_update_plugins');
remove_action('admin_init', '_maybe_update_themes');
add_filter('auto_update_core', '__return_false');
add_filter('auto_update_plugin', '__return_false');
add_filter('auto_update_theme', '__return_false');
}
add_filter('the_content', 'wpautop');
remove_action('post_updated', 'wp_save_post_revision');
if (!_hua('disable_gutenberg_edit')) {
add_filter('use_block_editor_for_post', '__return_false');
add_filter('use_widgets_block_editor', '__return_false');
add_filter('gutenberg_use_widgets_block_editor', '__return_false');
add_action('wp_enqueue_scripts', function() {
wp_dequeue_style('wp-block-library'); // 主区块库
wp_dequeue_style('wp-block-library-theme'); // 主题区块样式
wp_dequeue_style('classic-theme-styles'); // 显式移除经典主题样式
}, 100);
add_action('wp_head', function() {
ob_start(function($html) {
return preg_replace('/<style id=\'classic-theme-styles-inline-css\'>.*?<\/style>/', '', $html);
}, 1);
}, 1);
}
function disable_autosave() {
wp_deregister_script('autosave');
}
add_action( 'wp_print_scripts', 'disable_autosave' );
add_filter( 'autosave_interval', function() {
return 999999;
});
function ashuwp_clean_theme_meta() {
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles', 10);
remove_action('wp_head', 'rsd_link');///移除「Really Simple Discovery」链接(用于 XML-RPC)
remove_action('wp_head', 'wp_generator');// 移除 WordPress 版本号(安全优化)
remove_action('wp_head', 'wlwmanifest_link');// 移除 Windows Live Writer 支持链接
remove_action('wp_head', 'feed_links', 2);
remove_action('wp_head', 'feed_links_extra', 3);
remove_action('wp_head', 'index_rel_link');
remove_action('wp_head', 'start_post_rel_link');
remove_action('wp_head', 'parent_post_rel_link');
remove_action('wp_head', 'adjacent_posts_rel_link');
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
remove_action('wp_head', 'wp_shortlink_wp_head');// 移除短链接
remove_action('wp_head', 'rest_output_link_wp_head');// 移除 REST API 链接
remove_action('wp_head', 'wp_oembed_add_discovery_links');// 移除 oEmbed 发现链接
remove_action('wp_head', 'rel_canonical');// 移除规范链接(需确保 SEO 插件替代)
}
add_action('after_setup_theme', 'ashuwp_clean_theme_meta');
if (!_hua('disable_admin_bar')) {
add_filter('show_admin_bar', '__return_false');
}
function wpdx_disable_open_sans($translations, $text, $context, $domain) {
if ('Open Sans font: on or off' == $context && 'on' == $text) {
$translations = 'off';
}
return $translations;
}
add_filter('gettext_with_context', 'wpdx_disable_open_sans', 888, 4);
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' );
remove_action( 'wp_head', 'wp_resource_hints', 2 );
function my_admin_footer_text() {
return '<i class="fa fa-wordpress"></i> the wordpress theme by <a href="https://www.huatheme.com/" target="_blank">www.huatheme.com</a>';
}
add_filter('admin_footer_text', 'my_admin_footer_text');
function replace_get_avatar( $avatar ) {
if (is_admin()) {
$avatar = preg_replace("/http:\/\/(www|\d).gravatar.com\/avatar\//","http://cdn.v2ex.com/gravatar/",$avatar);
return $avatar;
}else{
return $avatar;
}
}
add_filter('get_avatar', 'replace_get_avatar');
add_filter('pre_option_link_manager_enabled', '__return_true');
if (function_exists('add_theme_support')) {
add_theme_support('post-thumbnails');
}
function hua_new_filename($filename) {
if (!_hua('md5_file_update', true)) return $filename;
$info = pathinfo($filename);
$ext = isset($info['extension']) ? '.' . $info['extension'] : '';
$name = basename($filename, $ext);
return time() . '-' . substr(bin2hex(random_bytes(8)), 0, 15) . $ext;
}
add_filter('sanitize_file_name', 'hua_new_filename', 10);
function remove_width_attribute($html) {
return preg_replace('/(width|height)=["\']\d*["\']\s?/', "", $html);
}
add_filter('post_thumbnail_html', 'remove_width_attribute', 10);
add_filter('image_send_to_editor', 'remove_width_attribute', 10);
function shapeSpace_disable_image_sizes($sizes) {
if (_hua('thumb_shapeSpace_disable', true)) return $sizes;
$disabled_sizes = [
'thumbnail', 'medium', 'large',
'medium_large', '1536x1536', '2048x2048'
];
foreach ($disabled_sizes as $size) {
unset($sizes[$size]);
}
return $sizes;
}
add_action('intermediate_image_sizes_advanced', 'shapeSpace_disable_image_sizes');
function _the_theme_thumb() {
static $default_thumb = null;
if (is_null($default_thumb)) {
$default_thumb = _hua('post_default_thumb')
?: '';
}
return $default_thumb;
}
if (!function_exists('_get_post_thumbnail_url')):
function _get_post_thumbnail_url($post = null, $size = null) {
$post = get_post($post);
if (!$post) return _the_theme_thumb();
$thumbnail_size = $size ?: _hua('thumbnail_def_get_size', 'full');
if (has_post_thumbnail($post)) {
$image = wp_get_attachment_image_src(
get_post_thumbnail_id($post),
$thumbnail_size
);
return $image[0] ?? _the_theme_thumb();
}
if (_hua('thumb_postfirstimg_s', true)) {
$first_img = '';
if (preg_match('/<img[^>]+src=["\']([^"\']+)["\']/', $post->post_content, $matches)) {
$first_img = esc_url($matches[1]);
}
return $first_img ?: _the_theme_thumb();
}
return _the_theme_thumb();
}
endif;
if ( _hua('no_categoty') && !function_exists('no_category_base_refresh_rules')) {
/* hooks */
register_activation_hook(__FILE__, 'no_category_base_refresh_rules');
register_deactivation_hook(__FILE__, 'no_category_base_deactivate');
/* actions */
add_action('created_category', 'no_category_base_refresh_rules');
add_action('delete_category', 'no_category_base_refresh_rules');
add_action('edited_category', 'no_category_base_refresh_rules');
add_action('init', 'no_category_base_permastruct');
/* filters */
add_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');
add_filter('query_vars', 'no_category_base_query_vars'); // Adds 'category_redirect' query variable
add_filter('request', 'no_category_base_request'); // Redirects if 'category_redirect' is set
function no_category_base_refresh_rules() {
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
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();
}
/**
* Removes category base.
*
* @return void
*/
function no_category_base_permastruct() {
global $wp_rewrite;
global $wp_version;
if ($wp_version >= 3.4) {
$wp_rewrite->extra_permastructs['category']['struct'] = '%category%';
} else {
$wp_rewrite->extra_permastructs['category'][0] = '%category%';
}
}
/**
* Adds our custom category rewrite rules.
*
* @param array $category_rewrite Category rewrite rules.
*
* @return array
*/
function no_category_base_rewrite_rules($category_rewrite) {
global $wp_rewrite;
$category_rewrite = array();
/* WPML is present: temporary disable terms_clauses filter to get all categories for rewrite */
if (class_exists('Sitepress')) {
global $sitepress;
remove_filter('terms_clauses', array($sitepress, 'terms_clauses'));
$categories = get_categories(array('hide_empty' => false));
add_filter('terms_clauses', array($sitepress, 'terms_clauses'));
} else {
$categories = get_categories(array('hide_empty' => false));
}
foreach ($categories as $category) {
$category_nicename = $category->slug;
if ($category->parent == $category->cat_ID) {
$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})/{$wp_rewrite->pagination_base}/?([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
$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]';
return $category_rewrite;
}
function no_category_base_query_vars($public_query_vars) {
$public_query_vars[] = 'category_redirect';
return $public_query_vars;
}
/**
* Handles category redirects.
*
* @param $query_vars Current query vars.
*
* @return array $query_vars, or void if category_redirect is present.
*/
function no_category_base_request($query_vars) {
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 _get_tax_meta($id = 0, $field = '', $default = '', $escape = true) {
$id = absint($id);
if ($id === 0) return $default;
$meta = get_option("_taxonomy_meta_{$id}", []);
if (empty($field)) {
if (empty($meta)) return $default;
return $escape ? array_map('esc_attr', $meta) : $meta;
}
if (!isset($meta[$field])) return $default;
return $escape ? esc_attr($meta[$field]) : $meta[$field];
}
function hua_get_excerpt($limit = 200, $after = '...') {
global $post;
$custom_desc = trim(get_post_meta($post->ID, 'description', true));
if ($custom_desc) {
return hua_str_cut($custom_desc, 0, $limit, $after);
}
$content = !empty($post->post_excerpt) ? $post->post_excerpt : $post->post_content;
$excerpt = strip_shortcodes($content);
$excerpt = strip_tags($excerpt);
$excerpt = str_replace(array("\r\n", "\r", "\n", " ", " ", "\""), " ", $excerpt);
$excerpt = trim(preg_replace('/\s+/', ' ', $excerpt));
return hua_str_cut($excerpt, 0, $limit, $after);
}
function hua_str_cut($str, $start = 0, $width = 100, $trimmarker = '...') {
if (empty($str) || is_null($str)) return $str;
$encoding = mb_detect_encoding($str, ['UTF-8', 'ASCII', 'GB2312', 'GBK'], true);
$str = $encoding !== 'UTF-8' ? mb_convert_encoding($str, 'UTF-8', $encoding) : $str;
$str_length = mb_strlen($str, 'UTF-8');
if ($str_length <= $width) return $str;
$start = max(0, (int)$start);
$substring = mb_substr($str, $start, $width, 'UTF-8');
return $substring . $trimmarker;
}
function mb_display_length($str, $charset = 'UTF-8') {
if (empty($str)) return 0;
$length = 0;
$str_length = mb_strlen($str, $charset);
for ($i = 0; $i < $str_length; $i++) {
$char = mb_substr($str, $i, 1, $charset);
$length += (strlen($char) > 1) ? 2 : 1;
}
return $length;
}
function get_the_subtitle($span = true, $class = '', $post_id = null) {
$post_id = $post_id ?: get_the_ID();
$subtitle = get_post_meta($post_id, 'subtitle', true);
if (empty($subtitle)) {
return null;
}
if ($span) {
$class_attr = $class ? ' class="' . esc_attr($class) . '"' : '';
return '<span' . $class_attr . '>' . esc_html($subtitle) . '</span>';
}
return esc_html($subtitle);
}
function output_custom_site_css() {
$custom_css = _hua('web_css');
if (empty($custom_css)) {
return;
}
$sanitized_css = wp_strip_all_tags($custom_css);
$sanitized_css = preg_replace('/\s+/', ' ', $sanitized_css); // 压缩空格
$sanitized_css = trim($sanitized_css);
if (!empty($sanitized_css)) {
printf(
'<style id="custom-site-css">%s</style>',
$sanitized_css
);
}
}
add_action('wp_head', 'output_custom_site_css', 10);
function custom_foot_js() {
$js_str = _hua('web_js');
if (!empty($js_str)) {
if (strpos($js_str, '<script') !== false) {
echo $js_str;
} else {
echo '<script type="text/javascript" id="custom-site-js">' .
wp_strip_all_tags($js_str) .
'</script>';
}
}
}
add_action('wp_footer', 'custom_foot_js', 98);
function hua_item_style() {
$default_style = _hua('the_style', 'list');
if (is_category() || is_tax('series')) {
$term_id = get_queried_object_id();
$term_style = get_term_meta($term_id, 'the_style', true);
return $term_style ?: _hua('latest_layout', 'list');
}
if (is_archive() || is_search() || is_home()) {
return $default_style;
}
return 'list';
}
function single_item_style() {
if (!is_single()) {
return '';
}
$categories = get_the_category();
if (empty($categories)) {
return _hua('latest_layout', 'list');
}
$primary_cat_id = $categories[0]->term_id;
$term_style = get_term_meta($primary_cat_id, 'the_style_single', true);
return $term_style ?: _hua('latest_layout', 'list');
}
function the_slug() {
global $post;
if (!$post) {
return '';
}
$page_id = $post->ID;
$ancestors = get_post_ancestors($post->ID);
if (!empty($ancestors)) {
$page_id = end($ancestors);
}
$post_data = get_post($page_id, ARRAY_A);
return $post_data['post_name'] ?? '';
}
function category_img() {
global $post;
$html = '';
$default_img = get_template_directory_uri() . '/images/cat-banner.jpg';
if (is_category()) {
$cat_ID = get_current_category_id();
$html = get_category_img($cat_ID);
} elseif (is_single()) {
$categories = get_the_category();
if (!empty($categories)) {
$cat_ID = $categories[0]->term_id;
$html = get_category_img($cat_ID);
}
} elseif (is_page()) {
$current_page_id = get_the_ID();
$html = get_page_img($current_page_id);
}
return !empty($html) ? $html : $default_img;
}
function get_category_img($cat_id) {
if (empty($cat_id)) return '';
$top_term_id = get_category_root_id($cat_id);
$current_img = get_term_meta($cat_id, 'categoty-img', true);
$parent_img = get_term_meta($top_term_id, 'categoty-img', true);
return !empty($current_img) ? $current_img : $parent_img;
}
function get_page_img($page_id) {
if (empty($page_id)) return '';
$current_img = get_post_meta($page_id, 'categoty-img', true);
if (!empty($current_img)) {
return $current_img;
}
$page_ancestors = get_post_ancestors($page_id);
foreach ($page_ancestors as $ancestor_id) {
$ancestor_img = get_post_meta($ancestor_id, 'categoty-img', true);
if (!empty($ancestor_img)) {
return $ancestor_img;
}
}
return '';
}
function get_category_root_id($cat_id) {
if (empty($cat_id)) return 0;
$category = get_category($cat_id);
if (is_wp_error($category) || !$category) return 0;
while ($category->parent) {
$category = get_category($category->parent);
if (is_wp_error($category) || !$category) return 0;
}
return $category->term_id;
}
function get_current_category_id() {
$category = get_queried_object();
return ($category instanceof WP_Term) ? $category->term_id : 0;
}
function hua_breadcrumbs() {
global $post, $wp_query;
$output = '<a href="' . esc_url(home_url()) . '">' . __('首页', 'hua') . '</a><i>></i>';
if (is_category()) {
$cat_obj = $wp_query->get_queried_object();
$this_cat = get_category($cat_obj->term_id);
if ($this_cat->parent != 0) {
$output .= _get_category_parents($this_cat->parent);
}
$output .= '<a href="' . esc_url(get_category_link($this_cat->term_id)) . '">' . single_cat_title('', false) . '</a><i>></i><span>列表</span>';
} elseif (is_day()) {
$year = get_the_time('Y');
$month = get_the_time('m');
$output .= '<a href="' . esc_url(get_year_link($year)) . '">' . $year . '</a><i>></i>';
$output .= '<a href="' . esc_url(get_month_link($year, $month)) . '">' . get_the_time('F') . '</a><i>></i>';
$output .= '<span>' . get_the_time('d') . '</span>';
} elseif (is_month()) {
$output .= '<a href="' . esc_url(get_year_link(get_the_time('Y'))) . '">' . get_the_time('Y') . '</a><i>></i>';
$output .= '<span>' . get_the_time('F') . '</span>';
} elseif (is_year()) {
$output .= '<span>' . get_the_time('Y') . '</span>';
} elseif (is_attachment()) {
$output .= '<span>' . get_the_title() . '</span>';
} elseif (is_single()) {
$post_type = get_post_type();
if ($post_type == 'post') {
$categories = get_the_category();
if (!empty($categories)) {
$output .= _get_category_parents($categories[0]->term_id);
}
$output .= '<span>正文</span>';
} elseif ($post_type == 'question') {
$terms = get_the_terms($post->ID, 'question_cat');
if ($terms && !is_wp_error($terms)) {
foreach ($terms as $term) {
$output .= '<i>></i>' . _get_term_parents($term->term_id, 'question_cat', true, '<i>></i>');
}
$output .= '<span>' . __('问题详情', 'hua') . '</span>';
}
} else {
$post_type_obj = get_post_type_object($post_type);
$output .= '<span>' . esc_html($post_type_obj->labels->singular_name) . '</span>';
}
} elseif (is_page()) {
if ($post->post_parent) {
$ancestors = get_post_ancestors($post->ID);
$ancestors = array_reverse($ancestors);
foreach ($ancestors as $ancestor) {
$output .= '<a href="' . esc_url(get_permalink($ancestor)) . '">' . get_the_title($ancestor) . '</a><i>></i>';
}
}
$output .= '<span>' . get_the_title() . '</span>';
} elseif (is_search()) {
$search_query = get_search_query();
$output .= '<span>' . sprintf(__('搜索: %s 的结果', 'hua'), esc_html($search_query ?: __('无', 'hua'))) . '</span>';
} elseif (is_tag()) {
$output .= '<span>' . single_tag_title('', false) . '</span>';
} elseif (is_author()) {
$author = get_queried_object();
$output .= '<span>' . esc_html($author->display_name) . '</span>';
} elseif (is_404()) {
$output .= '<span>' . __('404 ERROR', 'hua') . '</span>';
}
if (get_query_var('paged')) {
// $output .= '<i>></i><span>' . sprintf(__('第%s页', 'hua'), get_query_var('paged')) . '</span>';
}
echo $output;
}
function _get_category_parents($term_id, $visited = array()) {
$chain = '';
$parent = get_term($term_id, 'category');
if (is_wp_error($parent) || !$parent) {
return $chain;
}
if ($parent->parent && !in_array($parent->parent, $visited)) {
$visited[] = $parent->parent;
$chain .= _get_category_parents($parent->parent, $visited);
}
$chain .= '<a href="' . esc_url(get_category_link($parent->term_id)) . '">' . esc_html($parent->name) . '</a><i>></i>';
return $chain;
}
function _get_term_parents($term_id, $taxonomy, $link = true, $separator = '', $nicename = false, $visited = array()) {
$chain = '';
$parent = get_term($term_id, $taxonomy);
if (is_wp_error($parent) || !$parent) {
return $chain;
}
$name = $nicename ? $parent->slug : $parent->name;
if ($parent->parent && !in_array($parent->parent, $visited)) {
$visited[] = $parent->parent;
$chain .= _get_term_parents($parent->parent, $taxonomy, $link, $separator, $nicename, $visited);
}
if ($link) {
$chain .= '<a href="' . esc_url(get_term_link($parent)) . '">' . esc_html($name) . '</a>' . $separator;
} else {
$chain .= esc_html($name) . $separator;
}
return $chain;
}
function hua_pagination($range = 5, $args = array()) {
global $wp_query, $paged;
$output = '';
$range = max(1, absint($range));
$max_page = isset($args['numpages']) ? (int)$args['numpages'] : $wp_query->max_num_pages;
$current_page = isset($args['paged']) ? (int)$args['paged'] : (get_query_var('paged') ?: 1);
if ($max_page <= 1) return;
$output .= '<div class="pagination">';
if ($current_page > $range + 1) {
$output .= '<a href="'. esc_url(get_pagenum_link(1)) .'" class="first-page">首页</a>';
}
if ($current_page > 1) {
$output .= sprintf(
'<a href="%s" class="prev">%s</a>',
esc_url(get_pagenum_link($current_page - 1)),
esc_html__('上一页', 'text-domain')
);
}
if ($max_page > $range) {
if ($current_page < $range) {
$start = 1;
$end = min($range + 1, $max_page);
}
elseif ($current_page >= ($max_page - floor($range/2))) {
$start = max(1, $max_page - $range);
$end = $max_page;
}
else {
$start = $current_page - floor($range/2);
$end = $current_page + floor($range/2);
}
} else {
$start = 1;
$end = $max_page;
}
for ($i = $start; $i <= $end; $i++) {
if ($i == $current_page) {
$output .= sprintf('<a href="" class="page-num-current">%d</a>', $i);
} else {
$output .= sprintf(
'<a href="%s" class="page-num">%d</a>',
esc_url(get_pagenum_link($i)),
$i
);
}
}
if ($current_page < $max_page) {
$output .= sprintf(
'<a href="%s" class="next">%s</a>',
esc_url(get_pagenum_link($current_page + 1)),
esc_html__('下一页', 'text-domain')
);
}
if ($current_page < $max_page - $range) {
$output .= '<a href="'. esc_url(get_pagenum_link($max_page)) .'" class="last-page">末页</a>';
}
$output .= '</div>';
echo $output;
}
function infinite_scroll_js() {
if (!is_singular() ) {
?>
<script type="text/javascript">
var ias = $.ias({
container: "#content", //包含所有文章的元素
item: ".post", //文章元素
pagination: ".navigation", //分页元素
next: ".nav-previous a", //下一页元素
});
ias.extension(new IASTriggerExtension({
text: '加载更多', // 按钮文字
offset: 1, // 加载1页后显示按钮
html: '<div class="btn-more"><button class="load-more-btn">{text}</button></div>' // 自定义按钮HTML
}));
// 添加加载指示器
ias.extension(new IASSpinnerExtension({
html: '<div class="btn-more"><i class="fas fa-spinner fa-spin"></i> 加载中...</div>',
delay: 500
}));
// 没有更多内容时的提示
ias.extension(new IASNoneLeftExtension({
html: '<div class="btn-more"><p>已加载全部内容</p></div>'
}));
</script>
<?php
}
}
add_action('wp_footer', 'infinite_scroll_js', 100);
function twentytwelve_content_nav( $html_id ) {
global $wp_query;
if ( $wp_query->max_num_pages > 1 ) : ?>
<nav id="<?php echo esc_attr( $html_id ); ?>" class="navigation" role="navigation">
<h3 class="assistive-text"><?php _e( 'Post navigation', 'twentytwelve' ); ?></h3>
<div class="nav-previous"><?php next_posts_link( __( '<span class="meta-nav">←</span> Older posts', 'twentytwelve' ) ); ?></div>
<div class="nav-next"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">→</span>', 'twentytwelve' ) ); ?></div>
</nav><!-- .navigation -->
<?php endif;
}
function exclude_sticky_posts($query){
if ( is_admin() || ! $query->is_main_query() )
return;
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'ignore_sticky_posts', 1 );
}
}
add_action('pre_get_posts','exclude_sticky_posts');
function hy_nohtml($str, $preserve_breaks = false) {
$str = is_string($str) ? $str : '';
if ($preserve_breaks) {
$str = wp_strip_all_tags($str, false);
$str = str_replace(["\r\n", "\n", "\r"], ' ', $str);
} else {
$str = wp_strip_all_tags($str);
}
return preg_replace('/^[\s ]+|[\s ]+$/u', '', $str);
}
add_filter('category_description', 'hy_nohtml');
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){
$match_num_from = 1;
$match_num_to = 1;
$ex_word='';
$case='';
$posttags = get_the_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[^>]+>)(.*)<pre.*?>('.$ex_word.')(.*)<\/pre>(</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;
}
if (_hua('sing_tag_link')) {
add_filter('the_content','tag_link',1);
}
function replace_text_wps($content){
$match_num_from = 1;
$match_num_to = 1;
$ex_word='';
$case='';
$huakey = _hua('huakey');
if ($huakey) {
usort($huakey, "tag_sort");
foreach($huakey as $tag) {
$link = $tag['link']['url'];
$keyword = $tag['text'];
$cleankeyword = stripslashes($keyword);
$url = "<a href=\"$link\" title=\"".str_replace('%s',addcslashes($cleankeyword, '$'),__('更多关于 %s 的文章77'))."\"";
$url .= ' target="_blank"';
$url .= ">".addcslashes($cleankeyword, '$')."</a>";
$limit = rand($match_num_from,$match_num_to);
$content = preg_replace( '|(<a[^>]+>)(.*)<pre.*?>('.$ex_word.')(.*)<\/pre>(</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','replace_text_wps',1);
function _get_excerpt($limit = null, $after = '...') {
$default_limit = (int) _hua('_site_excerpt_length', '300');
$limit = is_null($limit) ? $default_limit : (int) $limit;
$excerpt = get_the_excerpt();
$text = wp_strip_all_tags($excerpt);
if ($limit <= 0 || mb_strlen($text) <= $limit) {
return $text;
}
return mb_substr($text, 0, $limit, 'UTF-8') . $after;
}
function _excerpt_length($length) {
return (int) _hua('_site_excerpt_length', '300');
}
add_filter('excerpt_length', '_excerpt_length');
function _excerpt_more($more) {
return '...';
}
add_filter('excerpt_more', '_excerpt_more');
add_filter('post_link', 'custom_post_type_link', 10, 3);
function custom_post_type_link($permalink, $post, $leavename) {
if (!($post instanceof WP_Post) || $post->post_type !== 'post') {
return $permalink;
}
$categories = get_the_category($post->ID);
if (empty($categories)) {
return $permalink;
}
$subcategory_slugs = array();
foreach ($categories as $category) {
if ($category->parent != 0) {
$subcategory_slugs[] = $category->slug . '/';
}
}
if (!empty($subcategory_slugs)) {
$permalink = str_replace($subcategory_slugs, '', $permalink);
}
return $permalink;
}
function add_post_views()
{
global $post;
if (!is_single()) return;
$post_views = (int) get_post_meta($post->ID, "views", true);
if (!update_post_meta($post->ID, 'views', ($post_views + 1))) {
add_post_meta($post->ID, 'views', 1, true);
}
}
add_action('wp_head', 'add_post_views');
function _get_post_views($post_id = null) {
if (empty($post_id)) {
global $post;
$post_id = $post->ID;
}
wp_cache_delete($post_id, 'post_meta');
$views = (int) get_post_meta($post_id, 'views', true);
if ($views >= 10000) {
return round($views / 1000000, 1) . 'W';
} elseif ($views >= 1000) {
return round($views / 1000, 1) . 'K';
}
return $views ? $views : '0';
}
function hua_thumbup()
{
$id = $_POST["um_id"];
$action = $_POST["um_action"];
if ($action == 'hua_thumbup') {
$specs_raters = get_post_meta($id, 'hua_thumbup', true);
$expire = time() + 99999999;
$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false; // make cookies work with localhost
setcookie('hua_thumbup_' . $id, $id, $expire, '/', $domain, false);
if (!$specs_raters || !is_numeric($specs_raters)) {
update_post_meta($id, 'hua_thumbup', 1);
} else {
update_post_meta($id, 'hua_thumbup', ($specs_raters + 1));
}
echo get_post_meta($id, 'hua_thumbup', true);
}
die;
}
add_action('wp_ajax_nopriv_hua_thumbup', 'hua_thumbup');
add_action('wp_ajax_hua_thumbup', 'hua_thumbup');
function _get_post_thumbup()
{
global $post;
$post_ID = $post->ID;
$views = (int)get_post_meta($post_ID, 'hua_thumbup', true);
return $views;
}
function search_by_title_only($search, $wp_query) {
global $wpdb;
// 如果搜索条件为空或不是主查询,直接返回
if (empty($search) || !$wp_query->is_main_query()) {
return $search;
}
$query_vars = $wp_query->query_vars;
if (empty($query_vars['search_terms'])) {
return $search;
}
$search_terms = $query_vars['search_terms'];
$exact_search = !empty($query_vars['exact']);
$search_parts = array();
foreach ((array) $search_terms as $term) {
$term = $wpdb->esc_like($term);
$wildcard = $exact_search ? '' : '%';
$search_parts[] = $wpdb->prepare(
"($wpdb->posts.post_title LIKE %s)",
$wildcard . $term . $wildcard
);
}
if (!empty($search_parts)) {
$search = " AND (" . implode(' AND ', $search_parts) . ")";
// 对未登录用户隐藏有密码保护的文章
if (!is_user_logged_in()) {
$search .= " AND ($wpdb->posts.post_password = '')";
}
}
return $search;
}
add_filter('posts_search', 'search_by_title_only', 500, 2);
function get_post_tags_sorted($class = 'color', $before = '', $after = '', $count = 0) {
global $post;
if (!isset($post->ID)) {
return '';
}
$tags = get_the_tags($post->ID);
return generate_tags_html($tags, $class, $before, $after, $count);
}
function sort_object_array($array, $sort_key, $sort_order = SORT_DESC, $sort_type = SORT_NUMERIC) {
if (!is_array($array) || empty($array)) {
return false;
}
$sort_values = array_column($array, $sort_key);
if (empty($sort_values)) {
return $array;
}
array_multisort($sort_values, $sort_order, $sort_type, $array);
return $array;
}
function generate_tags_html($tags, $class = 'color', $before = '', $after = '', $count = 0) {
if (empty($tags) || !is_array($tags)) {
return '';
}
$sorted_tags = sort_object_array($tags, 'count');
if (empty($sorted_tags)) {
return '';
}
$html = '';
$i = 0;
foreach ($sorted_tags as $tag) {
$i++;
$tag_url = get_tag_link($tag);
$tag_name = $tag->name;
$html .= sprintf(
'<a href="%s" class="%s%d" title="%s"%s>%s%s</a>',
esc_url($tag_url),
esc_attr($class),
$i,
esc_attr('查看此标签更多文章8'),
esc_html($before),
esc_html($tag_name),
esc_html($after)
);
if ($count > 0 && $i >= $count) {
break;
}
}
return $html;
}
function get_prevnext($in_same_term = true, $taxonomy = 'category') {
$prev = get_previous_post($in_same_term, '', $taxonomy);
$next = get_next_post($in_same_term, '', $taxonomy);
return [
'prev' => $prev ? [
'id' => $prev->ID,
'title' => get_the_title($prev),
'url' => get_permalink($prev),
'date' => get_the_date('', $prev),
'thumbnail' => get_the_post_thumbnail($prev, 'thumbnail'),
'excerpt' => get_the_excerpt($prev)
] : null,
'next' => $next ? [
'id' => $next->ID,
'title' => get_the_title($next),
'url' => get_permalink($next),
'date' => get_the_date('', $next),
'thumbnail' => get_the_post_thumbnail($next, 'thumbnail'),
'excerpt' => get_the_excerpt($next)
] : null
];
}
function custom_login_logo() {
$logo_url = _hua('site_logo');
if (empty($logo_url)) {
return;
}
$logo_size = @getimagesize($logo_url);
$logo_width = $logo_size ? min($logo_size[0], 320) : 200;
$logo_height = $logo_size ? ($logo_size[1] * $logo_width / $logo_size[0]) : 50;
$css = sprintf(
'<style type="text/css">
.login h1 a {
background-image: url(%1$s) !important;
width: %2$dpx !important;
height: %3$dpx !important;
background-size: contain !important;
background-position: center center;
background-repeat: no-repeat;
}
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
.login h1 a {
background-image: url(%1$s);
background-size: %2$dpx auto;
}
}
</style>',
esc_url($logo_url),
absint($logo_width),
absint($logo_height)
);
echo $css;
}
add_action('login_head', 'custom_login_logo');
add_filter('login_headerurl', function() {
return home_url();
});
add_filter('login_headertext', function() {
return get_bloginfo('name');
});
function auto_save_remote_images($post_id) {
// 防止无限循环
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
if (wp_is_post_revision($post_id)) return;
// 检查开关是否开启
$enable_localization = _hua('enable_remote_image_localization', true);
if (!$enable_localization) return;
$post = get_post($post_id);
$content = $post->post_content;
// 匹配所有图片标签
preg_match_all('/<img[^>]+src=["\']([^"\']+)["\'][^>]*>/i', $content, $matches);
if (isset($matches[1]) && !empty($matches[1])) {
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
foreach ($matches[1] as $image_url) {
// 跳过已经是本地URL的图片
if (strpos($image_url, site_url()) !== false) continue;
// 设置自定义header绕过简单防盗链
$args = array(
'headers' => array(
'Referer' => $image_url,
'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
)
);
// 下载图片
$tmp = download_url($image_url, 10, false, $args);
if (!is_wp_error($tmp)) {
// 准备文件数组
$file_array = array(
'name' => basename($image_url),
'tmp_name' => $tmp
);
// 上传到媒体库
$attachment_id = media_handle_sideload($file_array, $post_id);
if (!is_wp_error($attachment_id)) {
// 获取新图片URL
$new_image_url = wp_get_attachment_url($attachment_id);
// 替换内容中的URL
$content = str_replace($image_url, $new_image_url, $content);
}
// 清理临时文件
@unlink($tmp);
}
}
// 更新文章内容
if ($content != $post->post_content) {
wp_update_post(array(
'ID' => $post_id,
'post_content' => $content
));
}
}
}
add_action('save_post', 'auto_save_remote_images', 10, 1);
function handle_views_orderby($args = []) {
if (isset($args['orderby']) && $args['orderby'] === 'views') {
$args['meta_key'] = 'views';
$args['orderby'] = 'meta_value_num';
if (!isset($args['order'])) {
$args['order'] = 'DESC';
}
}
return $args;
}