Wordpress'te temada functions phpdebu kod hata veriyor
<?php
/**
 * blackcat functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package bkthmes
 */
date_default_timezone_set('Asia/Shanghai');
global $wpdb, $order_table_name, $paylog_table_name, $coupon_table_name, $balance_log_table_name,$chat_table_name,$attestation_table_name;
$order_table_name       = isset($table_prefix) ? ($table_prefix . 'blackcat_order') : ($wpdb->prefix . 'blackcat_order');
$paylog_table_name      = isset($table_prefix) ? ($table_prefix . 'blackcat_paylog') : ($wpdb->prefix . 'blackcat_paylog');
$coupon_table_name      = isset($table_prefix) ? ($table_prefix . 'blackcat_coupon') : ($wpdb->prefix . 'blackcat_coupon');
$balance_log_table_name = isset($table_prefix) ? ($table_prefix . 'blackcat_balance_log') : ($wpdb->prefix . 'blackcat_balance_log');
$favorite_table_name = isset($table_prefix) ? ($table_prefix . 'blackcat_favorite') : ($wpdb->prefix . 'blackcat_favorite');
$ref_log_table_name = isset($table_prefix) ? ($table_prefix . 'blackcat_ref_log') : ($wpdb->prefix . 'blackcat_ref_log');
$chat_table_name = isset($table_prefix) ? ($table_prefix . 'blackcat_chat') : ($wpdb->prefix . 'blackcat_chat');
$attestation_table_name = isset($table_prefix) ? ($table_prefix . 'blackcat_attestation') : ($wpdb->prefix . 'blackcat_attestation');

if (!function_exists('bkthmes_setup')):
    /**
     * Sets up theme defaults and registers support for various WordPress features.
     *
     * Note that this function is hooked into the after_setup_theme hook, which
     * runs before the init hook. The init hook is too late for some features, such
     * as indicating support for post thumbnails.
     */
    function bkthmes_setup()
    {
        $setupDb = new setupDb();
        $setupDb->install();

        /*
         * Let WordPress manage the document title.
         * By adding theme support, we declare that this theme does not use a
         * hard-coded <title> tag in the document head, and expect WordPress to
         * provide it for us.
         */
        add_theme_support('title-tag');

        /*
         * Enable support for Post Thumbnails on posts and pages.
         *
         * @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
         */
        add_theme_support('post-thumbnails');

        register_nav_menus(array(
            'primary' => '顶部菜单',
            'about-nav' => __('底部关于我们菜单'),
            'about-rules' => __('底部网站协议菜单'),
        ));

        /*
         * Switch default core markup for search form, comment form, and comments
         * to output valid HTML5.
         */
        add_theme_support('html5', array(
            'search-form',
            'comment-form',
            'comment-list',
            'gallery',
            'caption',
        ));

        // Load regular editor styles into the new block-based editor.
        add_theme_support('editor-styles');

        // Load default block styles.
        add_theme_support('wp-block-styles');

        // Add theme support for selective refresh for widgets.
        add_theme_support('customize-selective-refresh-widgets');


        add_theme_support( 'post-formats', array( 'video','image') );
        // CREATE PAGES
        $init_pages = array(
            'pages/collection.php' => array('专题页面', 'collection'),
        );

       

        //更新伪静态规则
        flush_rewrite_rules();

    }
endif;
add_action('after_setup_theme', 'bkthmes_setup');

function bkthmes_widgets_init()
{
    $sidebars = array(
        'single' => '文章页侧栏',
        // 'shop'   => '商品页面侧栏',
        'page'   => '页面侧栏',
    );
    foreach ($sidebars as $key => $value) {
        register_sidebar(array(
            'name'          => $value,
            'id'            => $key,
            'before_widget' => '<div class="widget %2$s">',
            'after_widget'  => '</div>',
            'before_title'  => '<div class="widget--title"><h2>',
            'after_title'   => '</h2></div>',
        ));
    }
    ;

}
add_action('widgets_init', 'bkthmes_widgets_init');
function bkthmes_scripts()
{
    $theme_assets = get_template_directory_uri() . '/assets';
    if (!is_admin()) {
        wp_deregister_script('jquery');
        wp_deregister_script('l10n');

        //引入CSS
        wp_enqueue_style('blackcat-style', get_stylesheet_uri());
        wp_enqueue_style('external', $theme_assets . '/css/external.css', array(), '', 'all');
        wp_enqueue_style('bootstrap', $theme_assets . '/css/bootstrap.min.css', array(), '', 'all');
        wp_enqueue_style('iview', $theme_assets . '/css/iview.css', array(), '', 'all');
        wp_enqueue_style('style', $theme_assets . '/css/style.css', array('bootstrap'), '', 'all');
        wp_enqueue_style('main', $theme_assets . '/css/main.css', array(), '', 'all');

        // 引入JS
        wp_enqueue_script('module', $theme_assets . '/js/module.js', array(), '', true);
        wp_enqueue_script('vue', $theme_assets . '/js/index.js', array(), '', true);
        wp_enqueue_script('main', $theme_assets . '/js/main.js', array(), '', true);
        if (is_singular('post')) {
            wp_enqueue_script('viewpost', $theme_assets . '/js/post.js', array(), '', true);
        }
        
        
        // llqrcode
        if (is_page_template('pages/setting.php')) {
            wp_enqueue_script('llqrcode', $theme_assets . '/js/plugins/llqrcode.js', array(), '2.0', true);
        }
        if (is_singular() && comments_open() && get_option('thread_comments')) {
            wp_enqueue_script('comment-reply');
        }
        $toastrc= _blackcat('toastr');
        //脚本本地化
        wp_localize_script('main', 'blackcat',
            array(
                'ajaxurl'    => admin_url('admin-ajax.php'),
                'is_singular'    => is_singular() ? 1 : 0,
                'data_var_2' => 'value2',
                'infinite_load' => '加载更多',
                'infinite_loading' => '<i class="fa fa-spinner fa-spin"></i> 加载中...',
            )
        );

    }
}
add_action('wp_enqueue_scripts', 'bkthmes_scripts');

// 管理页面CSS
function blackcatAdminScripts() {   
    wp_enqueue_style('blackcatadmin', get_template_directory_uri() . '/assets/css/admin.css', array(), '', 'all');
    wp_enqueue_script('echarts', 'https://lib.baomitu.com/echarts/4.7.0/echarts-en.min.js');
}
add_action( 'admin_enqueue_scripts', 'blackcatAdminScripts' );
require_once get_template_directory() . '/modules/codestar-framework/codestar-framework.php';
if (false) {
    require_once get_template_directory() . '/modules/core-functions.php';
}else{
    if (extension_loaded('swoole_loader')) {
        $php_v = substr(PHP_VERSION,0,3);
        require_once get_template_directory() . '/modules/core-functions.'.$php_v.'.php';
    }
}
require_once get_template_directory() . '/modules/theme-functions.php';
require_once get_template_directory() . '/modules/core-ajax.php';
 if (false) {
     require_once get_template_directory() . '/modules/class/core.class.php';
 }else{
     if (extension_loaded('swoole_loader')) {
         $php_v = substr(PHP_VERSION,0,3);
         require_once get_template_directory() . '/modules/class/core.class.'.$php_v.'.php';
     }
 }
require_once get_template_directory() . '/modules/class/class-wp-bootstrap-navwalker.php';
require_once get_template_directory() . '/vendor/autoload.php';
require_once get_template_directory() . '/modules/admin/init.php';
function lo_all_view(){
    global $wpdb;
    $count =  $wpdb->get_var("SELECT sum(meta_value) FROM $wpdb->postmeta WHERE meta_key='views'");
    return $count;
}
add_action('wp_ajax_nopriv_bigfa_like', 'bigfa_like');
add_action('wp_ajax_bigfa_like', 'bigfa_like');
function bigfa_like(){
    global $wpdb,$post;
    $id = $_POST["um_id"];
    $action = $_POST["um_action"];
    if ( $action == 'ding'){
    $bigfa_raters = get_post_meta($id,'bigfa_ding',true);
    $expire = time() + 99999999;
    $domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false; // make cookies work with localhost
    setcookie('bigfa_ding_'.$id,$id,$expire,'/',$domain,false);
    if (!$bigfa_raters || !is_numeric($bigfa_raters)) {
        update_post_meta($id, 'bigfa_ding', 1);
    }
    else {
            update_post_meta($id, 'bigfa_ding', ($bigfa_raters + 1));
        }
    echo get_post_meta($id,'bigfa_ding',true);
    }
    die;
};


add_filter('the_time','time_ago');
function time_ago(){
    global $post ;
    $to = time();
    $from = get_the_time('U') ;
    $diff = (int) abs($to - $from);
    if ($diff <= 3600) {
        $mins = round($diff / 60);
        if ($mins <= 1) {
            $mins = 1;
        }
        $time = sprintf('%s 分钟前', $mins);
    }
    elseif (($diff <= 86400) && ($diff > 3600)) {
        $hours = round($diff / 3600);
        if ($hours <= 1) {
            $hours = 1;
        }
        $time = sprintf('%s 小时前', $hours);
    }
    elseif ($diff >= 86400) {
        $days = round($diff / 86400);
        if ($days <= 1) {
            $days = 1;
            $time = sprintf('%s 天前', $days);
        }
        elseif( $days > 29){
            $time = get_the_time(get_option('date_format'));
        }
        else{
            $time = sprintf('%s 天前', $days);
        }
    }
    return $time;
}
add_filter( 'pre_option_link_manager_enabled', '__return_true' );

function loadCustomTemplate($template) {
    global $wp_query;
    if(!file_exists($template))return;
    $wp_query->is_page = true;
    $wp_query->is_single = false;
    $wp_query->is_home = false;
    $wp_query->comments = false;
    // if we have a 404 status
    if ($wp_query->is_404) {
    // set status of 404 to false
        unset($wp_query->query["error"]);
        $wp_query->query_vars["error"]="";
        $wp_query->is_404=false;
    }
    // change the header to 200 OK
    header("HTTP/1.1 200 OK");
    //load our template
    include($template);
    exit;
}
 
function templateRedirect() {
    $basename = basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']);
    loadCustomTemplate(TEMPLATEPATH.'/template-bases/'."/$basename.php");
}
  
add_action('template_redirect', 'templateRedirect');


function get_client_ip() {  
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))  
        $ip = getenv("HTTP_CLIENT_IP");  
    else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"),  
"unknown"))  
        $ip = getenv("HTTP_X_FORWARDED_FOR");  
    else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))  
        $ip = getenv("REMOTE_ADDR");  
    else if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR']  
&& strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))  
        $ip = $_SERVER['REMOTE_ADDR'];  
    else  
        $ip = "unknown";  
    return ($ip);  
}  
// 创建一个新字段存储用户注册时的IP地址  
add_action('user_register', 'log_ip');  
function log_ip($user_id){  
    $ip = get_client_ip();  
    update_user_meta($user_id, 'signup_ip', $ip);  
}  
// 创建新字段存储用户登录时间和登录IP  
add_action( 'wp_login', 'insert_last_login' );  
function insert_last_login( $login ) {  
    global $user_id;  
    $user = get_userdatabylogin( $login );  
    update_user_meta( $user->ID, 'last_login', current_time( 'mysql' ) );  
    $last_login_ip = get_client_ip();  
    update_user_meta( $user->ID, 'last_login_ip', $last_login_ip);  
}  
// 添加额外的栏目  
add_filter('manage_users_columns', 'add_user_additional_column');  
function add_user_additional_column($columns) {  
    $columns['user_nickname'] = '昵称';  
    $columns['reg_time'] = '注册时间';  
    $columns['last_login'] = '上次登录';  
    $columns['last_login_ip'] = '登录IP';  
    unset($columns['name']);
    return $columns;  
}  
//显示栏目的内容  
add_action('manage_users_custom_column',  'show_user_additional_column_content', 10, 3);  
function show_user_additional_column_content($value, $column_name, $user_id) {  
    $user = get_userdata( $user_id );  
    // 输出“昵称”  
    if ( 'user_nickname' == $column_name )  
        return $user->nickname;  

    // 输出注册时间和注册IP  
    if('reg_time' == $column_name ){  
        return get_date_from_gmt($user->user_registered) ;  
    }  
// 输出注册时间和注册IP  
    if('signup' == $column_name ){  
        return get_user_meta( $user->ID, 'signup_ip', true);  
    }  
    // 输出最近登录时间和登录IP  
    if ( 'last_login' == $column_name && $user->last_login ){  
        return get_user_meta( $user->ID, 'last_login', true );  
    }  
  
// 输出最近登录时间和登录IP  
    if ( 'last_login_ip' == $column_name ){  
        return get_user_meta( $user->ID, 'last_login_ip', true );  
    }  
    return $value;  
}  
  
// 默认按照注册时间排序  
add_filter( "manage_users_sortable_columns", 'cmhello_users_sortable_columns' );  
function cmhello_users_sortable_columns($sortable_columns){  
    $sortable_columns['reg_time'] = 'reg_time';  
    return $sortable_columns;  
}  
add_action( 'pre_user_query', 'cmhello_users_search_order' );  
function cmhello_users_search_order($obj){  
    if(!isset($_REQUEST['orderby']) || $_REQUEST['orderby']=='reg_time' ){  
        if( !in_array($_REQUEST['order'],array('asc','desc')) ){  
            $_REQUEST['order'] = 'desc';  
        }  
        $obj->query_orderby = "ORDER BY user_registered ".$_REQUEST['order']."";  
    }  
}  


// 彻底关闭自动更新
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' );

// 分类选择模板
class Select_Category_Template{
    public function __construct() {
        add_filter( 'category_template', array($this,'get_custom_category_template' ));
        add_action ( 'edit_category_form_fields', array($this,'category_template_meta_box'));
        add_action( 'category_add_form_fields', array( &$this, 'category_template_meta_box') );
        add_action( 'created_category', array( &$this, 'save_category_template' ));
        add_action ( 'edited_category', array($this,'save_category_template'));
        do_action('Custom_Category_Template_constructor',$this);
    }
 
    // 添加表单到分类编辑页面
    public function category_template_meta_box( $tag ) {
        $t_id = $tag->term_id;
        $cat_meta = get_option( "category_templates");
        $template = isset($cat_meta[$t_id]) ? $cat_meta[$t_id] : false;
        ?>
        <tr class="form-field">
            <th scope="row" valign="top"><label for="cat_Image_url"><?php _e('Category Template'); ?></label></th>
            <td>
                <select name="cat_template" id="cat_template">
                    <option value='default'><?php _e('Default Template'); ?></option>
                    <?php page_template_dropdown($template); ?>
                </select>
                <br />
                <span class="description"><?php _e('为此分类选择一个模板'); ?></span>
            </td>
        </tr>
        <?php
        do_action('Custom_Category_Template_ADD_FIELDS',$tag);
    }
 
    // 保存表单
    public function save_category_template( $term_id ) {
        if ( isset( $_POST['cat_template'] )) {
            $cat_meta = get_option( "category_templates");
            $cat_meta[$term_id] = $_POST['cat_template'];
            update_option( "category_templates", $cat_meta );
            do_action('Custom_Category_Template_SAVE_FIELDS',$term_id);
        }
    }
 
    // 处理选择的分类模板
    function get_custom_category_template( $category_template ) {
        $cat_ID = absint( get_query_var('cat') );
        $cat_meta = get_option('category_templates');
        if (isset($cat_meta[$cat_ID]) && $cat_meta[$cat_ID] != 'default' ){
            $temp = locate_template($cat_meta[$cat_ID]);
            if (!empty($temp))
                return apply_filters("Custom_Category_Template_found",$temp);
        }
        return $category_template;
    }
}
 
$cat_template = new Select_Category_Template();

silince modules/theme-functions.php hata veriyor
<?php


function _the_theme_name()
{
    $current_theme = wp_get_theme();
    return $current_theme->get('Name');
}

function _the_theme_version()
{
    $current_theme = wp_get_theme();
    return $current_theme->get('Version');
}

function _the_theme_aurl()
{
    $current_theme = wp_get_theme();
    return $current_theme->get('ThemeURI');
}

function _get_description_max_length()
{
    return 200;
}

function _get_delimiter()
{
    return _blackcat('connector') ? _blackcat('connector') : '-';
}
remove_action('wp_head', '_wp_render_title_tag', 1);

function _title()
{

    global $paged;

    $html = '';
    $t    = trim(wp_title('', false));

    if ($t) {
        $html .= $t . _get_delimiter();
    }

    if (get_query_var('page')) {
        $html .= '第' . get_query_var('page') . '页' . _get_delimiter();
    }

    $html .= get_bloginfo('name');

    if (is_home()) {
        if ($paged > 1) {
            $html .= _get_delimiter() . '最新发布';
        } elseif (get_option('blogdescription')) {
            $html .= _get_delimiter() . get_option('blogdescription');
        }
    }

    if ($paged > 1) {
        $html .= _get_delimiter() . '第' . $paged . '页';
    }

    return $html;
}

function _the_head()
{
    _keywords();
    _description();
    _post_views_record();
}
add_action('wp_head', '_the_head');

/**
 * [_keywords SEO关键词优化]
 * @Author   heimao
 * @DateTime 2019-05-28T12:17:48+0800
 * @return   [type]                   [description]
 */
function _keywords()
{
    global $s, $post;

    $keywords = '';
    if (is_singular()) {
        if (get_the_tags($post->ID)) {
            foreach (get_the_tags($post->ID) as $tag) {
                $keywords .= $tag->name . ', ';
            }

        }
        foreach (get_the_category($post->ID) as $category) {
            $keywords .= $category->cat_name . ', ';
        }

        if (get_post_meta($post->ID, 'post_keywords_s', true)) {
            $the = trim(get_post_meta($post->ID, 'keywords', true));
            if ($the) {
                $keywords = $the;
            }

        } else {
            $keywords = substr_replace($keywords, '', -2);
        }

    } elseif (is_home()) {
        $seo_opt  = _blackcat('seo');
        if (empty($seo_opt)){
            $keywords='Blackcat主题';
        }else{
            $keywords = $seo_opt['web_keywords'];
        }
    } elseif (is_tag()) {
        $keywords = single_tag_title('', false);
    } elseif (is_category()) {
        global $wp_query;
       
        $keywords = trim(wp_title('', false));
    } elseif (is_search()) {
        $keywords = esc_html($s, 1);
    } else {
        $keywords = trim(wp_title('', false));
    }
    if ($keywords) {
        echo "<meta name=\"keywords\" content=\"$keywords\">\n";
    }
}
function catch_that_image() {

    global $post, $posts;
     if (has_post_thumbnail($post)) {
        //如果有特色缩略图,则输出缩略图地址
        $image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );
        $post_thumbnail_src = $image[0];
    } else {
        $post_thumbnail_src = '';
        @$output            = preg_match_all('/<img[^>]*src="([^"]*)"[^>]*>/i', $post->post_content, $matches);
        if (!empty($matches[1][0])) {
            global $wpdb;
            $att = $wpdb->get_row($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid LIKE '%s'", $matches[1][0]));
            if ($att) {
                $post_thumbnail_src = $att->ID;
            } else {
                $post_thumbnail_src = $matches[1][0];
            }
        } else {
            $post_thumbnail_src = _the_theme_thumb();
        }
    }
    return $post_thumbnail_src;
}
    
/**
 * [_description SEO描述优化]
 * @Author   heimao
 * @DateTime 2019-05-28T12:18:02+0800
 * @return   [type]                   [description]
 */
function _description()
{
    global $s, $post;
    $description = '';
    $blog_name   = get_bloginfo('name');
    if (is_singular()) {
        if (!empty($post->post_excerpt)) {
            $text = $post->post_excerpt;
        } else {
            $text = $post->post_content;
        }
        $description = trim(str_replace(array("\r\n", "\r", "\n", " ", " "), " ", str_replace("\"", "'", strip_tags($text))));
        if (!($description)) {
            $description = $blog_name . "-" . trim(wp_title('', false));
        }
    } elseif (is_home()) {
        $seo_opt     = _blackcat('seo');
        if (empty($seo_opt)){
            $description='Blackcat主题';
        }else{
            $description = $seo_opt['web_description'];
        }
    } elseif (is_tag()) {
        $description = trim(strip_tags(tag_description()));
    } elseif (is_category()) {
        global $wp_query;
        $description = trim(wp_title('', false));
    } elseif (is_archive()) {
        $description = $blog_name . "-" . trim(wp_title('', false));
    } elseif (is_search()) {
        $description = $blog_name . ": '" . esc_html($s, 1) . "' " . __('的搜索結果', 'haoui');
    } else {
        $description = $blog_name . "'" . trim(wp_title('', false)) . "'";
    }
    $description = mb_substr($description, 0, _get_description_max_length(), 'utf-8');
    echo "<meta name=\"description\" content=\"$description\">\n";
}
function blackcat_entry_header( $options = array(),$authen='' ) {
  $options = array_merge( array( 'outside_loop' => false, 'container' => 'header', 'tag' => 'h2', 'link' => true, 'white' => false, 'author' => false, 'category' => false, 'date' => false, 'comment' => false, 'like' => false ), $options );
  $queried_object = get_queried_object();
  $post_id = $options['outside_loop'] ? $queried_object->ID : get_the_ID();
  $categories = get_the_category( $post_id ); ?>
  <?php echo '<' . $options['container'] . ' class="entry-header' . esc_attr( $options['white'] ? ' white' : '' ) . '">'; ?>
    <?php if ( $options['author'] || $options['category'] || $options['date'] || $options['comment'] || $options['like'] ) : ?>
      <div class="entry-meta">
        <?php if ( $options['author'] ) :
          $author_id = get_post_field( 'post_author', $post_id ); ?>
        <?php endif;
        if ( $categories && $options['category'] ) : ?>
            <?php foreach ( $categories as $key=>$category ) :
              if ($key == 3) {break;}
            ?>
            <?php endforeach; ?>
        <div class="d-none d-lg-block text-xs mb-1 ">
        <?php
        //无限分类cms
            if(_blackcat('cate-mode')=='catone'){
        ?>
            <!--第一种分类样式-->
        <div class="d-inline-block mx-1 mx-md-2">
            <i class="text-primary">—</i></div> 
            <a href="<?php echo esc_url( get_category_link( $category->term_id ) ); ?>" class="text-muted"><?php echo esc_html( $category->name ); ?>
            </a>
        <?php }else{ ?>
        <!--第二种分类样式-->
        <div class="d-inline-block mx-1 mx-md-2 new-cat">
            <i class="text-primary">#</i>
            <a href="<?php echo esc_url( get_category_link( $category->term_id ) ); ?>" class="text-muted"><?php echo esc_html( $category->name ); ?>
        </a>
        </div> 
        <?php } ?>
        <!--第二种分类样式结束-->
        <span class="post-date fr"><?php echo timeago((get_the_time('Y-m-d G:i:s')) )?></span>
        </div>

      
        <div class="list-body pl-3 pr-3">
        
        <a class="list-title text-sm  text-hidden" title="<?php echo get_the_title(); ?>" href="<?php echo get_permalink(); ?>">
            <span class="badge badge-primary"><?php if ( is_sticky() ) {echo "推荐";}?></span><?php echo get_the_title(); ?>
        </a>
        
        </div>
        <div class="mb-2 mb-md-3 pl-3 pr-3 post-width">
            <div class="d-flex flex-fill align-items-center text-muted text-xs">
                    <div class="d-inline-block ml-md-2">
                        <?php echo get_avatar(get_the_author_meta('ID')); ?>
                        <a href="<?php echo get_author_posts_url(get_the_author_meta('ID')); ?>" title="由<?php the_author(); ?>发布" rel="author">
                            <?php the_author(); ?>
                        </a>
                    </div>
                    <div class="flex-fill"></div>
                    </div>
                    <div class="d-flex d-flex-middle order-3 text-muted text-xs"><div class="d-flex-full"></div> 
                    <div class="d-flex text-nowrap d-flex-middle ">
                        <span class="mr-2">
                        <i class="heimao hm-eyepageview"></i>
                        <?php echo _get_post_views()?>      
                        </span>
                        <span class="mr-2">
                        <?php echo _get_post_comments()?>
                        </span> 
                        <span class="mr-2">
                        <i class="heimao hm-aixin-"></i>
                        <?php  global $post;if (get_post_meta($post->ID, 'bigfa_ding', true)) { echo get_post_meta($post->ID, 'bigfa_ding', true);
                        }else {echo '0'; } ?>                                                          
                        </span>
                        </div>
                        </div>
                    </div>
        <?php endif;
        if ( $options['date'] ) : ?>
          <span class="meta-date">
            <a<?php echo _target_blank();?> href="<?php echo esc_url( get_the_permalink( $post_id ) ); ?>">
              <time datetime="<?php echo esc_attr( get_the_date( 'c', $post_id ) ); ?>">
                <?php
                  // echo esc_html( get_the_date( null, $post_id ) );
                  echo _timeago( get_gmt_from_date(get_the_time('Y-m-d G:i:s')) );;
                ?>
              </time>
            </a>
          </span>
        <?php endif;
        
        if ( $options['comment'] && ! post_password_required( $post_id ) && ( comments_open( $post_id ) || get_comments_number( $post_id ) ) ) : ?>
          <span class="meta-comment">
            <a<?php echo _target_blank();?> href="<?php echo esc_url( get_the_permalink( $post_id ) . '#comments' ); ?>">
              <?php printf( _n( '%s 评论', '%s 评论', esc_html( get_comments_number( $post_id ) ), 'blackcat' ), esc_html( number_format_i18n( get_comments_number( $post_id ) ) ) ); ?>
            </a>
          </span>
        <?php endif;?>
      </div>
    <?php endif; ?>

  <?php echo '</' . $options['container'] . '>';
}
// 获取图片高度
function blackcat_entry_media( $options = array() ) {
  global $post;
  $ratio = blackcat_thumbnail_ratio(); ?>
  <div class="entry-media">
    <div class="placeholder">
    <?php  if (('blackcat_widget_pay')==true) { 
       global $post;
        $post_id = $post->ID;
        $user_id = is_user_logged_in() ? wp_get_current_user()->ID : 0;
        // 判断是否资源文章 blackcat_status
        if (get_post_meta($post->ID, 'blackcat_status', true)) { 
        $blackcat_price       = get_post_meta($post_id, 'blackcat_price', true);
        $blackcat_jifen_status = get_post_meta($post_id, 'blackcat_jifen_status', true);
        $blackcat_jifen_price = get_post_meta($post_id, 'blackcat_jifen_price', true);
        $blackcat_vip_rate    = get_post_meta($post_id, 'blackcat_vip_rate', true);
        $blackcat_downurl     = get_post_meta($post_id, 'blackcat_downurl', true);
        $blackcat_pwd         = get_post_meta($post_id, 'blackcat_pwd', true);
        $blackcat_demourl     = get_post_meta($post_id, 'blackcat_demourl', true);
        $blackcat_paynum      = get_post_meta($post_id, 'blackcat_paynum', true);
        $blackcat_info        = get_post_meta($post_id, 'blackcat_info', true);
        $blackcat_close_bonus = get_post_meta($post_id, 'blackcat_close_bonus', true);
        $blackcat_price_str = $blackcat_price;
        $blackcatUser = new blackcatUser($user_id);
        $PostPay = new PostPay($user_id, $post_id);
        if(!empty($blackcat_price)) {
            $blackcat_this_am = ($blackcat_price * $blackcat_vip_rate);
        }
        }?>
        <?php if($blackcat_price || $blackcat_jifen_price && _blackcat('grid_is_vip')==true) {
            echo'<span class="badge label-primary">VIP</span>';
        }elseif($blackcat_price=='0' || $blackcat_jifen_price == '0' && _blackcat('grid_is_vip')==true){
            echo'<span class="badge label-primary">免费</span>';
       } elseif( is_sticky($post_ID)){
            echo'<span class="badge label-primary">原创</span>';
       }
       }?>
    <a<?php echo _target_blank();?> class="media-pic"  href="<?php echo esc_url( get_permalink() ); ?>">
    <?php echo _get_post_thumbnail()?>     
    </a>
    </div>
    <?php get_template_part( 'template-parts/entry-format' ); ?>
  </div>
<?php 
}
// 获取APP图片高度
function blackcatc_entry_media( $options = array() ) {
    global $post;
    $ratio = blackcat_thumbnail_ratio(); ?>
   
  <img src="<?php echo catch_that_image()?>" alt="">
  
      <?php get_template_part( 'template-parts/entry-format' ); ?>

  <?php 
  }
// 收藏文章
function _blackcat_add_follow_post($uid='',$to_post='')
{
    $_meta_key ='follow_post';
    $to_post= (int)$to_post;
    if (get_post_status($to_post)===false) return 'false';
    
    $old_follow = get_user_meta($uid,$_meta_key,true) ; # 获取...

    if (is_array($old_follow)) {
        $new_follow = $old_follow;
    }else{
        $new_follow = array(0);
    }
    if (!in_array($to_post, $new_follow)){
        // 新关注 开始处理
        array_push($new_follow,$to_post);
    }
    return update_user_meta($uid,$_meta_key,$new_follow);
}
// 取消收藏文章
function _blackcat_del_follow_post($uid='',$to_post='')
{
    $_meta_key ='follow_post';
    $to_post= (int)$to_post;
    if (get_post_status($to_post)===false) return 'false';
    $follow_users = get_user_meta($uid,$_meta_key,true) ; # 获取...
    if (!is_array($follow_users)) {
        return false;
    }
    if (!in_array($to_post, $follow_users)){
       return false;
    }
    foreach ($follow_users as $key => $user_id) {
        if ($user_id == $to_post) {
            unset($follow_users[$key]);
            break;
        }
    }
    return update_user_meta($uid,$_meta_key,$follow_users);
}


//x=修复默认文章无侧边栏问题
function blackcat_sidebar() {
    if ( is_singular( 'post' ) || ( is_page()) ) {
      global $post;
        $sidebar = get_post_meta($post->ID, 'post_style', true);
        if ($sidebar == 'no_sidebar') {
          $sidebar = 'none';
        }else{
          $sidebar = 'right';
        }
        return $sidebar;
    } elseif ( is_archive() || is_search() ) {
        return 'none';
    } elseif ( is_home() ) {
        return _blackcat( 'sidebar_home', 'none' );
    }
    return 'none';
}

function blackcat_column_classes( $sidebar ) {
    $content_column_class = 'content-column col-lg-9';
    $sidebar_column_class = 'sidebar-column col-lg-3';

    if ( $sidebar == 'none' ) {
        $content_column_class = 'col-lg-12';
    }

    return array( $content_column_class, $sidebar_column_class );
}


function blackcat_side_thumbnail() {
  if ( ( is_singular( 'post' ) || is_page() ) && has_post_thumbnail() ) {
    $image_location = 'mixed';
    $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'full' );

    if ( ( ( $image_location == 'mixed' && $featured_image[2] > $featured_image[1] ) || $image_location == 'side' ) && ! get_post_format() ) {
      return true;
    }
  }

  return false;
}



function blackcat_show_hero() {

  global $post;
  if (is_singular( 'post' ) || is_page()) {
      $post_style = get_post_meta($post->ID, 'post_hero', true);
      if ($post_style) {
        return true;
      }

  }
  return false;
}

function blackcat_is_gif() {
  if ( has_post_thumbnail() ) {
    $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'full' );
    $featured_image = $featured_image[0];

    $path_parts = pathinfo( $featured_image );
    $extension = $path_parts['extension'];

    return $extension == 'gif' ? true : false;
  }

  return false;
}



/**
 * [blackcat_oauth_page_rewrite_rules OAuth登录处理页路由(/oauth)]
 * @Author   heimao
 * @DateTime 2019-05-26T00:04:32+0800
 * @param    [type]                   $wp_rewrite [description]
 * @return   [type]                               [description]
 * (qq|weibo|weixin|...)
 */
function blackcat_oauth_page_rewrite_rules($wp_rewrite)
{
    if ($ps = get_option('permalink_structure')) {
        $new_rules['oauth/([A-Za-z]+)$']          = 'index.php?oauth=$matches[1]';
        $new_rules['oauth/([A-Za-z]+)/callback$'] = 'index.php?oauth=$matches[1]&oauth_callback=1';
        $wp_rewrite->rules                        = $new_rules + $wp_rewrite->rules;
    }
}
add_action('generate_rewrite_rules', 'blackcat_oauth_page_rewrite_rules');

/**
 * [blackcat_add_oauth_page_query_vars 自定义的Action页添加query_var白名单]
 * @Author   heimao
 * @DateTime 2019-05-26T00:06:55+0800
 * @param    [type]                   $public_query_vars [description]
 * @return   [type]                                      [description]
 */
function blackcat_add_oauth_page_query_vars($public_query_vars)
{
    if (!is_admin()) {
        $public_query_vars[] = 'oauth'; // 添加参数白名单oauth,代表是各种OAuth登录处理页
        $public_query_vars[] = 'oauth_callback'; // OAuth登录最后一步,整合WP账户,自定义用户名
    }
    return $public_query_vars;
}
add_filter('query_vars', 'blackcat_add_oauth_page_query_vars');

/**
 * [blackcat_oauth_page_template OAuth登录处理页模板]
 * @Author   heimao
 * @DateTime 2019-05-26T00:07:35+0800
 * @return   [type]                   [description]
 */
function blackcat_oauth_page_template()
{
    $oauth          = strtolower(get_query_var('oauth')); //转换为小写
    $oauth_callback = get_query_var('oauth_callback');
    if ($oauth) {
        if (in_array($oauth, array('qq','qqagent','weixin', 'weixinagent', 'weibo','weiboagent'))):
            global $wp_query;
            $wp_query->is_home = false;
            $wp_query->is_page = true; //将该模板改为页面属性,而非首页
            $template          = $oauth_callback ? TEMPLATEPATH . '/modules/oauth/'.$oauth.'/callback.php' : TEMPLATEPATH . '/modules/oauth/'.$oauth.'/login.php';
            load_template($template);
            exit;
        else:
            // 非法路由处理
            unset($oauth);
            return;
        endif;
    }
}
add_action('template_redirect', 'blackcat_oauth_page_template', 5);



if (_blackcat('is_close_wpreg') || _blackcat('is_close_wplogin')) {
    // 移除原生登录注册
    add_action('login_head', 'redirect_login_form_register');
    function redirect_login_form_register() {
        wp_redirect(home_url());
        exit(); 
    }

    // 禁止非管理员登录后台
    add_action('admin_init', 'redirect_non_admin_users');
    function redirect_non_admin_users() {
        if (!is_super_admin() && empty($_REQUEST)) {
            wp_redirect(home_url());
            exit;
        }
    }
}

/**
 * [getQrcode 生产二维码]
 * @Author   heimao
 * @DateTime 2019-05-28T13:17:10+0800
 * @param    [type]                   $url [description]
 * @return   [type]                        [description]
 */
function getQrcode($url)
{
    //引入phpqrcode类库
    require_once get_template_directory() . '/modules/class/qrcode.class.php';
    $errorCorrectionLevel = 'L'; //容错级别
    $matrixPointSize      = 6; //生成图片大小
    ob_start();
    QRcode::png($url, false, $errorCorrectionLevel, $matrixPointSize, 2);
    $data = ob_get_contents();
    ob_end_clean();

    $imageString = base64_encode($data);
    header("content-type:application/json; charset=utf-8");
    return 'data:image/jpeg;base64,'.$imageString;
}


/*
Gravatar 自定义头像 Hook
 */
function blackcat_avatar_hook($avatar, $id_or_email, $size, $default, $alt,$str='img')
{


// update_user_meta(1, 'user_avatar_type','weixin');

    $user = false;
    if (is_numeric($id_or_email)) {
        $id   = (int) $id_or_email;
        $user = get_user_by('id', $id);
    } elseif (is_object($id_or_email)) {
        if (!empty($id_or_email->user_id)) {
            $id   = (int) $id_or_email->user_id;
            $user = get_user_by('id', $id);
        }
    } else {
        $user = get_user_by('email', $id_or_email);
    }
    if ($user && is_object($user)) {

        $uid = $user->data->ID;
        $user_email = $user->data->user_email;
        $_qqAvatarAPI = 'https://q.qlogo.cn/qqapp/';
        $_gravatarAPI = 'https://cn.gravatar.com/avatar/';
        $_user_avatar_type = (get_user_meta($uid, 'user_avatar_type', true));

        // 判断头像类型
        switch ($_user_avatar_type){
            case 'gravatar':
                $user_custom_avatar = get_user_meta($uid, 'user_custom_avatar', true );
                $avatar_url = ($user_custom_avatar) ? $user_custom_avatar : _the_theme_avatar() ;
                break;
            case 'qq':
                $qqConfig = _blackcat('oauth_qq');
                $avatar_url = $_qqAvatarAPI . $qqConfig['appid'] . '/' . get_user_meta($uid, 'open_qq_openid', true ) . '/100';
                // $avatar_url = set_url_scheme(get_user_meta($uid, 'open_qq_avatar', true ));
                break;
            case 'weibo':
                $avatar_url = set_url_scheme(get_user_meta($uid, 'open_weibo_avatar', true ));
                break;
            case 'weixin':
                $avatar_url = set_url_scheme(get_user_meta($uid, 'open_weixin_avatar', true ));
                break;
            case 'custom':
                $avatar_url = set_url_scheme(get_user_meta($uid, 'user_custom_avatar', true ));
            default:
                $avatar_url = _the_theme_avatar();
        }
        if ($str =='img') {
            if (is_admin()) {
                $avatar = "<img alt='{$alt}' src='{$avatar_url}' class='avatar avatar-{$size} photo {$_user_avatar_type}' height='{$size}' width='{$size}' />";
            }else{
               $avatar = "<img alt='{$alt}' src='data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==' data-src='{$avatar_url}'  class='avatar avatar-{$size} photo {$_user_avatar_type}' height='{$size}' width='{$size}' />"; 
            }
            
        }else{
            $avatar = $avatar_url;
        }
        
    }

    return $avatar;
}
add_filter('get_avatar', 'blackcat_avatar_hook', 1, 5);




function _the_theme_avatar()
{
    return get_template_directory_uri() . '/assets/images/avatar/1.png';
}

function _is_bind_openid($type = 'qq')
{
    global $current_user;
    $uid = $current_user->ID;
    $_bind = (int)get_user_meta($uid, 'open_' . $type . '_bind', true);
    return ($_bind) ? true : false ;
}

//社交登录按钮
function _the_open_oauth_login_btn()
{
    if (_blackcat('is_oauth_qq') || _blackcat('is_oauth_weixin') || _blackcat('is_oauth_weibo')) {
        $oauthArr = array('qq','weixin','weibo');
         echo '<div class="or-text"><span>or</span></div>'; 
        echo '<div class="open-oauth  text-center">';
            foreach ($oauthArr as $value) {
                if (_blackcat('is_oauth_'.$value)) {
                    if($value == 'qq'){
                        echo '<a href="'.esc_url(home_url('/oauth/'.$value)).'" class="btn btn-'.$value.'"><i class="fa fa-'.$value.'"></i>QQ登录</a>';
                    }else if($value == 'weixin'){
                        echo '<a href="'.esc_url(home_url('/oauth/'.$value)).'" class="btn btn-'.$value.'"><i class="fa fa-'.$value.'"></i>微信登录</a>';
                    }else{
                        echo '<a href="'.esc_url(home_url('/oauth/'.$value)).'" class="btn btn-'.$value.'"><i class="fa fa-'.$value.'"></i>微博登录</a>';
                    }
                }
            }
        echo '</div>';
           
    }
}

//获取用户社交登录按钮
function _the_open_oauth_btn()
{
    $oauthArr = array('qq','weixin','weibo');
    foreach ($oauthArr as $value) {
        switch ($value) {
            case 'qq':
                $opname = 'QQ';
                break;
            case 'weixin':
                $opname = '微信';
                break;
            case 'weibo':
                $opname = '微博';
                break;
        }
        if (_blackcat('is_oauth_'.$value)) {
            if (_is_bind_openid($value)) {
                echo '<a href="javascript: void(0);" class="btn btn--link btn--secondary btn--auto unset-bind" data-id="'.$value.'"><i class="fa fa-'.$value.'"></i> 解绑'.$opname.'</a>';
            }else{
                echo '<a href="'.esc_url(home_url('/oauth/'.$value)).'" class="btn btn--link btn--auto"><i class="fa fa-'.$value.'"></i> 绑定'.$opname.'</a>';
            }
        }
    }
}
//获取用户头像地址 根据类型
function _get_user_avatar_url($type = 'gravatar',$user_id=0,$cat_ID=0)
{   


    if ($user_id>0) {
        $uid = $user_id; 
    }else{
        global $current_user;
        $uid = $current_user->ID;
    }
    
    
    $user = get_user_by('id', $uid);
    $user_email = $user->data->user_email;
    $_user_avatar_type = (get_user_meta($uid, 'user_avatar_type', true));

    if ($type=='user') {
       $this_type= $_user_avatar_type;
    }else{
        $this_type =$type;
    }

    $_qqAvatarAPI = 'https://q.qlogo.cn/qqapp/';
    $_gravatarAPI = 'https://cn.gravatar.com/avatar/';

    // 判断头像类型
    switch ($this_type){
        case 'gravatar':
            $user_custom_avatar = get_user_meta($uid, 'user_custom_avatar', true );
            $avatar_url = ($user_custom_avatar) ? $user_custom_avatar : _the_theme_avatar() ;
            break;
        case 'usercover':
            $avatar_url = get_user_meta($uid, 'user_cover', true )?:'/wp-content/themes/blackcat/assets/images/banner.jpg';
            break;
        case 'qq':
            $qqConfig = _blackcat('oauth_qq');
            $avatar_url = $_qqAvatarAPI . $qqConfig['appid'] . '/' . get_user_meta($uid, 'open_qq_openid', true ) . '/100';
            break;
        case 'weibo':
            $avatar_url = set_url_scheme(get_user_meta($uid, 'open_weibo_avatar', true ));
            break;
        case 'weixin':
            $avatar_url = set_url_scheme(get_user_meta($uid, 'open_weixin_avatar', true ));
            break;
        case 'custom':
            $avatar_url = set_url_scheme(get_user_meta($uid, 'user_custom_avatar', true ));
        default:
            $avatar_url = _the_theme_avatar();
    }
    
    return $avatar_url;

}

/**
 * [_get_user_avatar 获取头像]
 * @Author   heimao
 * @DateTime 2019-05-28T12:17:13+0800
 * @param    string                   $user_email [description]
 * @param    boolean                  $src        [description]
 * @param    integer                  $size       [description]
 * @return   [type]                               [description]
 */
function _get_user_avatar($user_email = '', $src = false, $size = 50)
{
    global $current_user;
    if (!$user_email) {
        $user_email = $current_user->user_email;
    }
   
    $avatar = get_avatar($user_email, $size);
    if ($src) {
        return $avatar;
    }else{
        return $avatar;
    }

}


function _the_post_star_btn()
{
    global $post,$current_user;
    $uid = is_user_logged_in() ? $current_user->ID : 0;
    $post_id = $post->ID;

    // echo '<span class="entry--star">';
    if (is_user_logged_in()) {
        $blackcatFavorite = new blackcatFavorite;
        if ($blackcatFavorite->is_fav($uid,$post_id)) {
            return '<a href="javascript:void(0);" title="收藏" class="ok" etap="post_star" data-id="'.get_the_ID().'" data-tap="2"><i class="fa fa-star"></i></a>';
        }else{
            return '<a href="javascript:void(0);" title="收藏" etap="post_star" data-id="'.get_the_ID().'" data-tap="1"><i class="fa fa-star"></i></a>';
        }
    }else{
        return '<a href="javascript:void(0);" data-toggle="modal" data-target="#signupModule"><i class="fa fa-star"></i></a>';
    }
    // echo '</span>';
    
}

// 签到
function _blackcat_user_is_qiandao($users_id=0)
{
    global $current_user;
    if (!is_user_logged_in()) {
        return false;
    }
    $uid = (!$users_id) ? $current_user->ID : $users_id;
    $_meta_key ='blackcat_qiandao_time';
    // 会员当前签到时间
    $this_user_qiandao_time = (get_user_meta($uid, $_meta_key, true) > 0) ? get_user_meta($uid, $_meta_key, true) : 0;
    
    // 自动更新时间
    $getTime  = getTime();
    
    $thenTime = time();
    // 获取用户结束时间
    if ( $getTime['star'] < $this_user_qiandao_time && $getTime['end'] > $this_user_qiandao_time ) {
        return true;
    }
     return false;
}
 
/**
 * [getTime 获取今天的开始和结束时间]
 * @Author   heimao
 * @DateTime 2019-05-28T12:25:26+0800
 * @return   [type]                   [description]
 */
function getTime()
{
    $str          = date("Y-m-d", time()) . "0:0:0";
    $data["star"] = strtotime($str);
    $str          = date("Y-m-d", time()) . "24:00:00";
    $data["end"]  = strtotime($str);
    return $data;
}

function _the_post_favbtn()
{
    global $post,$current_user;
    $uid = is_user_logged_in() ? $current_user->ID : 0;
    $post_id = $post->ID;

    $blackcatFavorite = new blackcatFavorite;
    if ($blackcatFavorite->is_fav($uid,$post_id)) {
        echo '<a href="javascript:void(0);" etap="delete_fav" data-id="'.get_the_ID().'" class="edit--btn"><i class="fa fa-star"></i> 取消收藏</a>';
    }else{
        echo '<a href="javascript:void(0);" etap="add_fav" data-id="'.get_the_ID().'" class="edit--btn"><i class="fa fa-star"></i> 收藏</a>';
    }
}



// 文章是否资源文章
function _get_post_shop_status()
{
    global $post;
    $post_ID = $post->ID;
    if (get_post_meta($post_ID, 'blackcat_status', true)) {
        return true;
    }
    return false;
}

//文章资源价格
function _get_post_price()
{
    global $post;
    $post_ID = $post->ID;
    $price   = get_post_meta($post_ID, 'blackcat_price', true);
    $priceVal = ($price) ? $price : '0' ;
    // $after = _blackcat('site_money_ua');
    return $priceVal;
}


//文章分类信息
function _get_post_cat()
{
    global $post;
    $post_ID = $post->ID;
    $category = get_the_category($post->ID);
    $cat_neme=$category[0]->cat_name;
    $cat_links=get_category_link($category[0]->cat_ID);
    return '<a href="'.$cat_links.'">'.$cat_neme.'</a>';
}



/**
 * post 文章阅读次数
 */
function _post_views_record()
{
    if (is_singular()) {
        global $post;
        $post_ID = $post->ID;
        if ($post_ID) {
            $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);
            }
        }
    }
}


function _get_post_views($before = '', $after = '')
{
    global $post;
    $post_ID = $post->ID;
    $views   = (int) get_post_meta($post_ID, 'views', true);
    if ($views >= 1000) {
        $views = round($views / 1000, 2) . 'K';
    }
    return $before . $views . $after;
}


/**
 * [_set_postthumbnail 自动设置文章缩略图]
 * @Author   heimao
 * @DateTime 2019-05-28T12:27:23+0800
 */
if (_blackcat('set_postthumbnail') && !function_exists('_set_postthumbnail')):
    function _set_postthumbnail()
{
        global $post;
        if (empty($post)) {
            return;
        }

        $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);
                }
            }
        }
    }

    // add_action('the_post', '_set_postthumbnail');
    add_action('save_post', '_set_postthumbnail');
    add_action('draft_to_publish', '_set_postthumbnail');
    add_action('new_to_publish', '_set_postthumbnail');
    add_action('pending_to_publish', '_set_postthumbnail');
    add_action('future_to_publish', '_set_postthumbnail');
endif;

/**
 * [_the_theme_thumb 默认缩略图]
 * @Author   heimao
 * @DateTime 2019-05-29T10:35:28+0800
 * @return   [type]                   [description]
 */
function _the_theme_thumb()
{
    return _blackcat('post_default_thumb')['url'] ? _blackcat('post_default_thumb')['url'] : get_template_directory_uri() . '/assets/images/blog/grid/1.jpg';
}

/**
 * [_get_post_thumbnail_url 输出缩略图地址]
 * @Author   heimao
 * @DateTime 2019-05-28T12:16:30+0800
 * @param    [type]                   $post [post]
 * @return   [type]                         [description]
 */
function _get_post_thumbnail_url($post = null)
{
    if ($post === null) {
        global $post;
    }
    // blackcat_is_gif()
    if (has_post_thumbnail($post)) {
        //如果有特色缩略图,则输出缩略图地址
        $image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );
        if(empty($image)){//查看是否oss
            global $wpdb;
            $row = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = '%s'", get_post_thumbnail_id($post->ID)));
            $post_thumbnail_src = $row->guid;
        }else{
            $post_thumbnail_src = $image[0];
        }
    } else {
        $post_thumbnail_src = '';
        @$output            = preg_match_all('/<img[^>]*src="([^"]*)"[^>]*>/i', $post->post_content, $matches);
        if (!empty($matches[1][0])) {
            global $wpdb;
            $att = $wpdb->get_row($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid LIKE '%s'", $matches[1][0]));
            if ($att) {
                $post_thumbnail_src = $att->ID;
            } else {
                $post_thumbnail_src = $matches[1][0];
            }
        } else {
            $post_thumbnail_src = _the_theme_thumb();
        }
    }
    return $post_thumbnail_src;
}

/**
 * [_timthumb 图像裁切]
 * @Author   heimao
 * @DateTime 2019-05-28T12:16:48+0800
 * @param    [type]                   $src  [description]
 * @param    [type]                   $size [description]
 * @param    [type]                   $set  [description]
 * @return   [type]                         [description]
 */
function _timthumb($src, $size = null, $set = null)
{
    $modular = _blackcat('thumbnail_handle');
    if (is_numeric($src)) {
        if ($modular == 'timthumb_mi') {
            // $src = image_downsize( $src, $size['w'].'-'.$size['h'] );
            $src = image_downsize($src, 'thumbnail');
        } else {
            $src = image_downsize($src, 'full');
        }
        $src = $src[0];
    }
    if ($set == 'original') {
        return $src;
    }
    if ($modular == 'timthumb_php' || empty($modular) || $set == 'tim') {
        if(substr($src,0,5)=='data:'){ 
            return $src;
        }else{
            return $src;
        }
    } else {
        return $src;
    }

}
define('DEFAULT_AVATAR_URL', get_template_directory_uri() . '/assets/images/avatar/1.png'); //默认头像
function no_gravatars( $avatar ) {
    return preg_replace( "/http.*?gravatar\.com[^\']*/", DEFAULT_AVATAR_URL, $avatar );
}
add_filter( 'get_avatar', 'no_gravatars' );
/**
 * [_get_post_thumbnail 获取缩略图代码]
 * @Author   heimao
 * @DateTime 2019-05-28T12:16:54+0800
 * @return   [type]                   [description]
 */
 
function _get_post_thumbnail($w='',$h='')
{
    $thum_px = _blackcat('thumbnail-px');
    if ($w && $h) {
        $img_w = $w;
        $img_h = $h;
    }else{
        $img_w   = ($thum_px) ? $thum_px['width'] : '360';
        $img_h   = ($thum_px) ? $thum_px['height'] : '240';
    }
    $src     = _timthumb(_get_post_thumbnail_url(), array('w' => $img_w, 'h' => $img_h));
    return '<img height="'.$img_h.'" width="'.$img_w.'" src="'._blackcat('post_default_thumb')['url'].'" data-src="' . $src . '"  class="thumb" alt="' . get_the_title() . '">';
}


/**
 * [_str_cut description]
 * @Author   heimao
 * @DateTime 2019-05-28T12:15:45+0800
 * @param    [type]                   $str        [description]
 * @param    [type]                   $start      [description]
 * @param    [type]                   $width      [description]
 * @param    [type]                   $trimmarker [description]
 * @return   [type]                               [description]
 */
function _str_cut($str, $start, $width, $trimmarker)
{
    $output = preg_replace('/^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,' . $start . '}((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,' . $width . '}).*/s', '\1', $str);
    return $output . $trimmarker;
}
function _excerpt_length($length)
{
    return 200;
}
add_filter('excerpt_length', '_excerpt_length');

/**
 * [_get_excerpt 截取文章摘要]
 * @Author   heimao
 * @DateTime 2019-05-28T12:15:48+0800
 * @param    integer                  $limit [长度]
 * @param    string                   $after [description]
 * @return   [type]                          [description]
 */
function _get_excerpt($limit = 40, $after = '...')
{
    $excerpt = get_the_excerpt();
    if (mb_strlen($excerpt) > $limit) {
        return _str_cut(strip_tags($excerpt), 0, $limit, $after);
    } else {
        return $excerpt;
    }
}

/**
 * [_get_post_comments 文章评论]
 * @Author   heimao
 * @DateTime 2019-05-28T12:20:33+0800
 * @param    string                   $before [description]
 * @param    string                   $after  [description]
 * @return   [type]                           [description]
 */
function _get_post_comments($before = '<i class="heimao hm-pinglun5"></i> ', $after = '')
{
    return $before . get_comments_number('0', '1', '%') . $after;
}

/**
 * [_get_post_time 文章时间]
 * @Author   heimao
 * @DateTime 2019-05-28T12:18:48+0800
 * @return   [type]                   [description]
 */
function _get_post_time()
{
    return (time() - strtotime(get_the_time('Y-m-d'))) > 86400 ? get_the_date() : get_the_time();
}



//评论表单
function blackcat_theme_from_comments()
{
    $commenter = wp_get_current_commenter();
    $req       = get_option('require_name_email');
    $aria_req  = ($req ? " aria-required='true'" : '');
    $fields    = array(
        'author' => '<div class="col-xs-12 col-sm-12 col-md-6"><div class="form-group"><input type="text" class="form-control" id="author" placeholder="昵称*" name="author" value="' . esc_attr($commenter['comment_author']) . '"' . $aria_req . '></div></div>',
        'email'  => '<div class="col-xs-12 col-sm-12 col-md-6"><div class="form-group"><input type="text" class="form-control" id="email" placeholder="邮箱*" name="email" value="' . esc_attr($commenter['comment_author_email']) . '"' . $aria_req . '></div></div>',
    );
    $args = array(
        'fields'               => $fields,
        'title_reply'          => null,
        'label_submit'         => '发布评论',
        'class_submit' => 'go-comment',
        'comment_field'        => '<div class="col-xs-12 col-sm-12 col-md-12"><div class="form-group">
        <div class="ivu-input-wrapper ivu-input-wrapper-default ivu-input-type-textarea">
        <textarea class="ivu-input" id="comment" placeholder="说些什么吧...." name="comment" rows="4"></textarea>
        </div></div></div>'.'<div class="position">
 <a href="javascript:;" id="comment-smiley" title="表情"><b><i class="fa fa-smile-o"></i></b></a>
 <a href="javascript:" id="font-color" title="颜色"><b><i class="fa fa-font"></i></b></a>
 <a href="javascript:SIMPALED.Editor.strong()" title="粗体"><b><i class="fa fa-bold"></i></b></a>
 <a href="javascript:SIMPALED.Editor.em()" title="斜体"><b><i class="fa fa-italic"></i></b></a>
 <a href="javascript:SIMPALED.Editor.quote()" title="引用"><b><i class="fa fa-quote-left"></i></b></a>
 <a href="javascript:SIMPALED.Editor.del()" title="删除线"><b><i class="fa fa-strikethrough"></i></b></a>
 <a href="javascript:SIMPALED.Editor.underline()" title="下划线"><b><i class="fa fa-underline"></i></b></a>
 </div> ',
        'comment_notes_before' => false,
    );
    comment_form($args);
}

//评论列表
function blackcat_theme_list_comments($comment, $args, $depth)
{
    $GLOBALS['comment'] = $comment;
    global $commentcount, $wpdb, $post;
    if (!$commentcount) {
        $comments = get_comments(['post_id' => $post->ID]);
        $cnt      = count($comments);
        $page     = get_query_var('cpage');
        $cpp      = get_option('comments_per_page');
        if (ceil($cnt / $cpp) == 1 || ($page > 1 && $page == ceil($cnt / $cpp))) {
            $commentcount = $cnt + 1;
        } else {
            $commentcount = $cpp * $page + 1;
        }
    }
    ?>
<li id="comment-<?php comment_ID()?>" class="comment-body">
    <div id="div-comment-<?php comment_ID()?>" class="comment-wrapper u-clearfix">
        <div class="avatar">
            <?php echo _get_user_avatar($comment); ?>
        </div>
        <div class="comment">
            <h6><?php comment_author_link();?></h6>    
            <?php echo user_level($comment->user_id); ?>
            <?php 
            $blackcatUser = new blackcatUser($comment->user_id);
               if ($blackcatUser->vip_status()) {
                        echo '
  
        <div class="dev-user-info-detail-vip"> <img src="/wp-content/themes/blackcat/assets/images/vip-header.png"> <span>'.$blackcatUser->vip_name().'</span></div>';
                    }else{
                        echo '<div class="dev-user-info-detail-vip"> <img src="/wp-content/themes/blackcat/assets/images/user-header.png"> <span>'.$blackcatUser->vip_name().'</span></div>
                    ';
                    
                    }
                 ?>
            <?php comment_reply_link(array_merge($args, array('depth' => $depth, 'max_depth' => $args['max_depth'], 'reply_text' => '<i class="heimao hm-pinglun"></i> 回复')))?>
            <?php comment_text()?>
            <div class="date"><?php echo timeago(get_comment_date('Y-m-d G:i:s')); ?>
</div>
            <?php if ($comment->comment_approved == '0'): ?>
                <font style="color:#C00; font-style:inherit">您的评论正在等待审核中...</font>
            <?php endif;?>
        </div>
    </div>
</li>
<?php }

function get_author_class($comment_author_email,$user_id){

    global $wpdb;

    $adminEmail = get_option('admin_email');

    $author_count  =  count($wpdb->get_results(

    "SELECT comment_ID as author_count FROM  $wpdb->comments WHERE comment_author_email = '$comment_author_email' "));
}
/**
 * [_posts_related 相关文章获取]
 * @Author   heimao
 * @DateTime 2019-05-28T12:22:24+0800
 * @param    integer                  $limit [description]
 * @return   [type]                          [description]
 */
function _posts_related($limit = 3)
{
    global $post;

    $exclude_id = $post->ID;
    $posttags   = get_the_tags();
    $i          = 0;

    if ($posttags) {
        $tags = '';
        foreach ($posttags as $tag) {
            $tags .= $tag->name . ',';
        }

        $args = array(
            'post_status'         => 'publish',
            'tag_slug__in'        => explode(',', $tags),
            'post__not_in'        => explode(',', $exclude_id),
            'ignore_sticky_posts' => 1,
            // 'orderby'             => 'comment_date',
            'posts_per_page'      => $limit,
        );
        query_posts($args);
        while (have_posts()) {
            the_post();
            get_template_part('template-parts/item');

            $exclude_id .= ',' . $post->ID;
            $i++;
        }
        ;
        wp_reset_query();
    }
    if ($i < $limit) {
        $cats = '';foreach (get_the_category() as $cat) {
            $cats .= $cat->cat_ID . ',';
        }

        $args = array(
            'category__in'        => explode(',', $cats),
            'post__not_in'        => explode(',', $exclude_id),
            'ignore_sticky_posts' => 1,
            // 'orderby'             => 'comment_date',
            'posts_per_page'      => $limit - $i,
        );
        query_posts($args);
        while (have_posts()) {
            the_post();
            if ($i >= $limit) {
                break;
            }
            get_template_part('template-parts/item');
            $i++;
        }
        ;
        wp_reset_query();
    }
    if ($i == 0) {
        return false;
    }

}
/**
 * [_get_post_thumbnail 获取缩略图代码]
 * @Author   heimao
 * @DateTime 2019-05-28T12:16:54+0800
 * @return   [type]                   [description]
 */
function _get_post_timthumb_src()
{
  $thum_px = _blackcat('thumbnail-px');
  $img_w   = ($thum_px) ? $thum_px['width'] : '300';
  $img_h   = ($thum_px) ? $thum_px['height'] : '200';
  $src     = timthumb(_get_post_thumbnail_url(), array('w' => $img_w, 'h' => $img_h));
  return $src;
}




/**
 * [blackcat_breadcrumbs 添加面包屑导航]
 * @Author   heimao
 * @DateTime 2019-05-29T11:20:48+0800
 * @return   [type]                   [description]
 * @link     https://www.wpdaxue.com/wordpress-add-a-breadcrumb.html
 */
function blackcat_breadcrumbs()
{
    $delimiter = '/'; // 分隔符
    $before    = '<span class="active">'; // 在当前链接前插入
    $after     = '</span>'; // 在当前链接后插入
    if (!is_home() && !is_front_page() || is_paged()) {
        echo '<ol itemscope itemtype="http://schema.org/WebPage" class="breadcrumb" id="crumbs">';
        global $post;
        $homeLink = home_url();
        echo ' <a itemprop="breadcrumb" href="' . $homeLink . '">' . __('首页', 'cmp') . '</a> ' . $delimiter . ' ';
        if (is_category()) {
            // 分类 存档
            global $wp_query;
            $cat_obj   = $wp_query->get_queried_object();
            $thisCat   = $cat_obj->term_id;
            $thisCat   = get_category($thisCat);
            $parentCat = get_category($thisCat->parent);
            if ($thisCat->parent != 0) {
                $cat_code      = get_category_parents($parentCat, true, ' ' . $delimiter . ' ');
                echo $cat_code = str_replace('<a', '<a itemprop="breadcrumb"', $cat_code);
            }
            echo $before . '' . single_cat_title('', false) . '' . $after;
        } elseif (is_day()) {
            // 天 存档
            echo '<a itemprop="breadcrumb" href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
            echo '<a itemprop="breadcrumb"  href="' . get_month_link(get_the_time('Y'), get_the_time('m')) . '">' . get_the_time('F') . '</a> ' . $delimiter . ' ';
            echo $before . get_the_time('d') . $after;
        } elseif (is_month()) {
            // 月 存档
            echo '<a itemprop="breadcrumb" href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
            echo $before . get_the_time('F') . $after;
        } elseif (is_year()) {
            // 年 存档
            echo $before . get_the_time('Y') . $after;
        } elseif (is_single() && !is_attachment()) {
            // 文章
            if (get_post_type() != 'post') {
                // 自定义文章类型
                $post_type = get_post_type_object(get_post_type());
                $slug      = $post_type->rewrite;
                echo '<a itemprop="breadcrumb" href="' . $homeLink . '/' . $slug['slug'] . '/">' . $post_type->labels->singular_name . '</a> ' . $delimiter . ' ';
                echo $before . get_the_title() . $after;
            } else {
                // 文章 post
                $cat           = get_the_category();
                $cat           = $cat[0];
                $cat_code      = get_category_parents($cat, true, ' ' . $delimiter . ' ');
                echo $cat_code = str_replace('<a', '<a itemprop="breadcrumb"', $cat_code);
                echo $before . get_the_title() . $after;
            }
        } elseif (!is_single() && !is_page() && !is_tag() && get_post_type() != 'post') {
            $post_type = get_post_type_object(get_post_type());
            echo $before . $post_type->labels->singular_name . $after;
        } elseif (is_attachment()) {
            // 附件
            $parent = get_post($post->post_parent);
            $cat    = get_the_category($parent->ID);
            $cat    = $cat[0];
            echo '<a itemprop="breadcrumb" href="' . get_permalink($parent) . '">' . $parent->post_title . '</a> ' . $delimiter . ' ';
            echo $before . get_the_title() . $after;
        } elseif (is_page() && !$post->post_parent) {
            // 页面
            echo $before . get_the_title() . $after;
        } elseif (is_page() && $post->post_parent) {
            // 父级页面
            $parent_id   = $post->post_parent;
            $breadcrumbs = array();
            while ($parent_id) {
                $page          = get_page($parent_id);
                $breadcrumbs[] = '<a itemprop="breadcrumb" href="' . get_permalink($page->ID) . '">' . get_the_title($page->ID) . '</a>';
                $parent_id     = $page->post_parent;
            }
            $breadcrumbs = array_reverse($breadcrumbs);
            foreach ($breadcrumbs as $crumb) {
                echo $crumb . ' ' . $delimiter . ' ';
            }

            echo $before . get_the_title() . $after;
        } elseif (is_search()) {
            // 搜索结果
            echo $before;
            printf(__('搜索结果: %s', 'cmp'), get_search_query());
            echo $after;
        } elseif (is_tag()) {
            //标签 存档
            echo $before;
            printf(__('标签: %s', 'cmp'), single_tag_title('', false));
            echo $after;
        } elseif (is_author()) {
            // 作者存档
            global $author;
            $userdata = get_userdata($author);
            echo $before;
            printf(__('作者: %s', 'cmp'), $userdata->display_name);
            echo $after;
        } elseif (is_404()) {
            // 404 页面
            echo $before;
            _e('没有找到', 'cmp');
            echo $after;
        }
        if (get_query_var('paged')) {
            // 分页
            if (is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author()) {
                echo sprintf(__('( 第 %s 页)', 'cmp'), get_query_var('paged'));
            }

        }
        echo '</div>';
    }
}

/**
 * [_paging 分页导航]
 * @Author   heimao
 * @DateTime 2019-05-29T11:35:44+0800
 * @return   [type]                   [description]
 */
if (!function_exists('_paging')):

    function _paging()
    {
        global $wp_query;

        $total = $wp_query->max_num_pages;
        $big = 999999999;
        
        if ( $total > 1 ) {
          if ( ! $current_page = get_query_var( 'paged' ) ) {
            $current_page = 1;
          }
        
          if ( get_option( 'permalink_structure' ) ) {
            $format = 'page/%#%/';
          } else {
            $format = '&paged=%#%';
          }
        
          echo '<div class="col-12"><div class="numeric-pagination">';
          echo paginate_links( array(
            'base'      => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
            'format'    => $format,
            'current'   => max( 1, get_query_var( 'paged' ) ),
            'total'     => $total,
            'mid_size'  => 3,
            'type'      => 'list',
            'prev_text' => '<i class="ivu-icon ivu-icon-ios-arrow-back"></i>',
            'next_text' => '<i class="ivu-icon ivu-icon-ios-arrow-forward"></i>',
          ) );
          echo '</div></div>';
        }
    }

endif;


/**
 * [blackcat_the_pagenavi 分页自定义]
 * @Author   heimao
 * @DateTime 2019-06-06T09:58:21+0800
 * @param    [type]                   $total_count     [总数]
 * @param    integer                  $number_per_page [每页数量]
 * @param    integer                  $paged           [当前页数]
 * @param    [type]                   $the_url         [当前页面]
 * @return   [type]                                    [htm]
 */
function blackcat_the_pagenavi($total_count, $number_per_page=15,$paged,$the_url){

    $current_page = $paged;
    $base_url = add_query_arg($_GET,$the_url);
    $total_pages    = ceil($total_count/$number_per_page);

    $first_page_url = $base_url.'&amp;paged=1';
    $last_page_url  = $base_url.'&amp;paged='.$total_pages;
    if($current_page > 1 && $current_page < $total_pages){
        $prev_page      = $current_page-1;
        $prev_page_url  = $base_url.'&amp;paged='.$prev_page;

        $next_page      = $current_page+1;
        $next_page_url  = $base_url.'&amp;paged='.$next_page;
    }elseif($current_page == 1){
        $prev_page_url  = '#';
        $first_page_url = '#';
        if($total_pages > 1){
            $next_page      = $current_page+1;
            $next_page_url  = $base_url.'&amp;paged='.$next_page;
        }else{
            $next_page_url  = '#';
            $class = 'class="disabled"';
        }
    }elseif($current_page == $total_pages){
        $prev_page      = $current_page-1;
        $prev_page_url  = $base_url.'&amp;paged='.$prev_page;
        $next_page_url  = '#';
        $last_page_url  = '#';
    }
    ?>
    <div class="blackcat-pagination pagination-area">
        <nav aria-label="Page navigation">
          <ul class="pagination blackcat-pagination">
            <!-- <li><span>共<?php //echo $total_count;?>条</span></li> -->
            <li>
              <a href="<?php echo $first_page_url;?>" aria-label="Previous">
                <span aria-hidden="true">&laquo;</span>
              </a>
            </li>
            <li><a href="<?php echo $prev_page_url;?>">上一页</a></li>
            <li><span>第<?php echo $current_page;?>页,共<?php echo $total_pages; ?>页</span></li>
            <li><a href="<?php echo $next_page_url;?>">下一页</a></li>
            <li>
              <a href="<?php echo $last_page_url;?>" aria-label="Next">
                <span aria-hidden="true">&raquo;</span>
              </a>
            </li>
          </ul>
        </nav>

    </div>
    <?php
}


function blackcat_admin_pagenavi($total_count, $number_per_page = 20)
{

    $current_page = isset($_GET['paged']) ? $_GET['paged'] : 1;

    if (isset($_GET['paged'])) {
        unset($_GET['paged']);
    }

    $base_url = add_query_arg($_GET, admin_url('admin.php'));

    $total_pages = ceil($total_count / $number_per_page);

    $first_page_url = $base_url . '&amp;paged=1';
    $last_page_url  = $base_url . '&amp;paged=' . $total_pages;

    if ($current_page > 1 && $current_page < $total_pages) {
        $prev_page     = $current_page - 1;
        $prev_page_url = $base_url . '&amp;paged=' . $prev_page;

        $next_page     = $current_page + 1;
        $next_page_url = $base_url . '&amp;paged=' . $next_page;
    } elseif ($current_page == 1) {
        $prev_page_url  = '#';
        $first_page_url = '#';
        if ($total_pages > 1) {
            $next_page     = $current_page + 1;
            $next_page_url = $base_url . '&amp;paged=' . $next_page;
        } else {
            $next_page_url = '#';
        }
    } elseif ($current_page == $total_pages) {
        $prev_page     = $current_page - 1;
        $prev_page_url = $base_url . '&amp;paged=' . $prev_page;
        $next_page_url = '#';
        $last_page_url = '#';
    }
    ?>
    <div class="tablenav">
        <div class="tablenav-pages">
            <span class="displaying-num ">每页 <?php echo $number_per_page; ?> 共 <?php echo $total_count; ?></span>
            <span class="pagination-links">
                <a class="first-page button <?php if ($current_page == 1) {
        echo 'disabled';
    }
    ?>" title="前往第一页" href="<?php echo $first_page_url; ?>">«</a>
                <a class="prev-page button <?php if ($current_page == 1) {
        echo 'disabled';
    }
    ?>" title="前往上一页" href="<?php echo $prev_page_url; ?>">‹</a>
                <span class="paging-input ">第 <?php echo $current_page; ?> 页,共 <span class="total-pages"><?php echo $total_pages; ?></span> 页</span>
                <a class="next-page button <?php if ($current_page == $total_pages) {
        echo 'disabled';
    }
    ?>" title="前往下一页" href="<?php echo $next_page_url; ?>">›</a>
                <a class="last-page button <?php if ($current_page == $total_pages) {
        echo 'disabled';
    }
    ?>" title="前往最后一页" href="<?php echo $last_page_url; ?>">»</a>
            </span>
        </div>
        <br class="clear">
    </div>
    <?php
}



// 下载管理
// 

// 添加路由重写,每次修改完记得在wp-admin后台"设置"-》"固定链接"=》"保存"才能生效
add_action('init', 'download_functionality_urls');
function download_functionality_urls()
{
    add_rewrite_rule('^download', 'index.php?download=1', 'top');
}

// 添加下载路由 download
add_action('query_vars', 'download_add_query_vars');
function download_add_query_vars($public_query_vars)
{
    $public_query_vars[] = 'download';
    return $public_query_vars;
}


//下载路由模板载入规则 shangche
add_action("template_redirect", 'download_template_redirect');
function download_template_redirect()
{
    global $wp;
    global $wp_query;
    $shangche_page     = strtolower(get_query_var('download')); //转换为小写
    if ($shangche_page == '1') {
        $template = TEMPLATEPATH . '/modules/download.php';
        load_template($template);
        exit;
    }
}

// 下载文件缓存
function _download_file($file_dir)
{
    // 远程文件异步下载 直接跳转URL
    if (substr($file_dir, 0, 7) == 'http://' || substr($file_dir, 0, 8) == 'https://' || substr($file_dir, 0, 10) == 'thunder://' || substr($file_dir, 0, 7) == 'magnet:' || substr($file_dir, 0, 5) == 'ed2k:') {
        $file_path = chop($file_dir);
        echo "<script type='text/javascript'>window.location='$file_path';</script>";
        exit;
    }
    // 本地缓冲下载文件
    $file_dir = ABSPATH . '/' . chop($file_dir);
    if (!file_exists($file_dir)) {
        header('HTTP/1.1 404 NOT FOUND');
        return false;
    }
    $pathinfoarr = pathinfo($file_dir);
    $file_name = time().mt_rand(1000,9999).'.'.$pathinfoarr['extension'];
    //以只读和二进制模式打开文件
    $file = fopen ( $file_dir,"rb" );
    header('Content-Description: File Transfer');
    //告诉浏览器这是一个文件流格式的文件
    Header ( "Content-type: application/octet-stream" );
    //请求范围的度量单位
    Header ( "Accept-Ranges: bytes" );
    //Content-Length是指定包含于请求或响应中数据的字节长度
    Header ( "Accept-Length: " . filesize ( $file_dir ) );
    //用来告诉浏览器,文件是可以当做附件被下载,下载后的文件名称为$file_name该变量的值。
    Header ( "Content-Disposition: attachment; filename=" . $file_name );
    //读取文件内容并直接输出到浏览器    
    echo fread ( $file, filesize ( $file_dir) );
    fclose ( $file );
    exit();
}



/**
 * [blackcat_get_referral_link 生成推广链接]
 * @Author   heimao
 * @DateTime 2019-06-11T16:43:08+0800
 * @param    integer                  $user_id   [description]
 * @param    string                   $base_link [description]
 * @return   [type]                              [description]
 */
function blackcat_get_referral_link($user_id = 0, $base_link = ''){
    
    $str = 'invite';
    if(!$base_link) $base_link = home_url();
    if(!$user_id) $user_id = get_current_user_id();
    return add_query_arg(array($str => $user_id), $base_link);
}


/**
 * [blackcat_retrieve_referral_keyword 捕获链接中的推广者]
 * @Author   heimao
 * @DateTime 2019-06-11T16:45:37+0800
 * @return   [type]                   [description]
 */
function blackcat_retrieve_referral_keyword() {
    if(isset($_REQUEST['$str'])) {
        $ref = absint($_REQUEST['$str']);
        session_start();
        $from_user_id = $ref;
        $_SESSION['blackcat_from_user_id'] = $from_user_id;
    }else{
        $ref = 0;
    }
    return $ref;
}
add_action('template_redirect', 'blackcat_retrieve_referral_keyword');
add_action('admin_menu', 'blackcat_retrieve_referral_keyword');



// 发放佣金 根据当前用户计算推荐人
function add_to_user_bonus($this_user_id =0,$charge_money=0)
{
    if (!$this_user_id) {
        return false;
    }
    // 查询上级id
    $form_uid = get_user_meta($this_user_id, 'blackcat_ref_from', true);
    $blackcat_ref_from_uid = ($form_uid) ? (int)$form_uid : 0 ;
    // 有推介人 发放
    if ($blackcat_ref_from_uid) {
        // 计算应发金额
        // 获取后台佣金比例
        $site_novip_ref_float = _blackcat('site_novip_ref_float');
        $site_vip_ref_float = _blackcat('site_vip_ref_float');
        $blackcatUser = new blackcatUser($blackcat_ref_from_uid);
        if ($blackcatUser->vip_status()) {
            $amount = sprintf('%0.2f', $charge_money*$site_vip_ref_float);
        }else{
            $amount = sprintf('%0.2f', $charge_money*$site_novip_ref_float);
        }
        // 
        $Reflog = new Reflog($blackcat_ref_from_uid);
        $Reflog->add_total_bonus($amount); //添加佣金 .
    }


    return;
}


/**
 * [_the_ads 自定义广告代码]
 * @Author   heimao
 * @DateTime 2019-05-28T12:14:38+0800
 * @param    string                   $name  [description]
 * @param    string                   $class [description]
 * @return   [type]                          [description]
 */
function _the_blackcat_ads($name = '', $class = '')
{
    if (!_blackcat($name . '_s')) {
        return;
    }
    echo '<div class="site-ads ads-' . $class . '">' . _blackcat($name) . '</div>';
}

function blackcat_thumbnail_ratio() {
    // $thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id(), $image_size );
    $thumbnail = _blackcat('thumbnail-px');
    if ( $thumbnail['width'] && $thumbnail['height']) {
        return $thumbnail['height'] / $thumbnail['width'] * 100 . '%';
    } else {
        return 200/300* 100 . '%';   
    }
}
/**
 * [_target_blank 链接新窗口打开]
 * @Author   heimao
 * @DateTime 2019-05-28T12:28:35+0800
 * @return   [type]                   [description]
 */
function _target_blank()
{
    return _blackcat('target_blank') ? ' target="_blank"' : '';
}

function is_get_post_fav($post_id)
{
    $user_id = get_current_user_id();
    if (!$user_id) {
        return false;
    }
    $old_follow = get_user_meta($user_id,'follow_post',true) ; # 获取...
     if (empty($old_follow) || !is_array($old_follow)) {
        return false;
    }
    if (in_array($post_id, $old_follow)){
        return true;
    }else{
        return false;
    }
}

//检测文章是否付费查看内容
function _get_post_shop_hide()
{
  global $post;
  if( has_shortcode( $post->post_content, 'bkhide') ){
    return true;
  }
  return false;
}
/**
 * [shop_shortcode 付费查看部分内容]
 * @Author   Dadong2g
 * @DateTime 2019-05-28T13:10:24+0800
 * @param    [type]                   $atts    [description]
 * @param    [type]                   $content [description]
 * @return   [type]                            [description]
 */
function shop_shortcode($atts, $content)
{
    global $post, $wpdb;
    $user_id = is_user_logged_in() ? wp_get_current_user()->ID : 0;
    $atts    = shortcode_atts(array(
        'id' => 0,
    ), $atts, 'bkhide');
    $post_id = $post->ID;
    if ($atts['id']) {
        $post_id = $atts['id'];
    }

    $blackcatUser = new blackcatUser($user_id);
    $PostPay = new PostPay($user_id, $post_id);

    // meta init
    $blackcat_price       = get_post_meta($post_id, 'blackcat_price', true);
    $blackcat_jifen_price       = get_post_meta($post_id, 'blackcat_jifen_price', true);
    $blackcat_vip_rate    = get_post_meta($post_id, 'blackcat_vip_rate', true);
    $blackcat_pwd         = get_post_meta($post_id, 'blackcat_pwd', true);
    $blackcat_paynum      = get_post_meta($post_id, 'blackcat_paynum', true);
    $blackcat_info        = get_post_meta($post_id, 'blackcat_info', true);
    $blackcat_close_bonus = get_post_meta($post_id, 'blackcat_close_bonus', true);
    $blackcat_is_boosvip  = get_post_meta($post_id, 'blackcat_is_boosvip', true);
    $site_vip_name = _blackcat('site_vip_name');
    $site_money_ua = _blackcat('site_money_ua');
    if ($blackcatUser->vip_status()) {
        $blackcat_this_am = intval($blackcat_price) * intval($blackcat_vip_rate);
    } else {
        $blackcat_this_am = $blackcat_price . $site_money_ua;
    }

    // 优惠信息
    switch ($blackcat_vip_rate) {
        case 1:
            $rate_text = '暂无优惠';
            break;
        case 0:
            $rate_text = $site_vip_name . '免费';
            break;
        default:
            $rate_text = $site_vip_name . '价 ' . ($blackcat_vip_rate * 10) . ' 折';
    }
    if ($blackcat_is_boosvip) {
        $rate_text = $rate_text.' 永久'.$site_vip_name.'免费';
    }
    if (!is_user_logged_in()) {
        $do_shortcode ='<div class="content-hidden"><div class="content-hidden-before"><i class="ivu-icon ivu-icon-md-lock"></i></div>';
        $do_shortcode .= '<div class="content-hidden-info">
        <div class="content-hidden-info-title">隐藏内容,您需要满足以下条件方可查看</div>
        <div class="content-show-roles bk-mark" style="background: none; min-height: auto;">
        <div class="content-cap">
        <div class="content-cap-title"><span>以下方式可查看</span></div>
        <div class="content-cap-info content-user-lv">
        <span class="lv-icon user-vip">
            <i class="ivu-icon ivu-icon-logo-vimeo"></i>' . $rate_text . '</span>
            <span class="lv-icon user-vip user-price">
            <i class="ivu-icon ivu-icon-logo-usd"></i>' . $blackcat_this_am . '</span>
        </div>';
        // 最新付费查看
        $do_shortcode .= '<div class="pc-button content-cap">';
        $do_shortcode .= '<button type="button" class="login-btn btn-popup ivu-btn ivu-btn-primary" data-toggle="modal" data-target="#signupModule"><i class="fa fa-user"></i> 登录购买</button>';
        $do_shortcode .= '</div></div></div></div></div>';
      
    } elseif ($PostPay->isPayPost()) {
        $do_shortcode = '<div class="content-hidden"><div class="content-hidden-before"><i class="ivu-icon ivu-icon-md-unlock"></i></div>';
        $do_shortcode .= '<div class="content-hidden-info">';
        $do_shortcode .= do_shortcode($content); //原始内容
        $do_shortcode .= '</div></div>';
    } else {
        $create_nonce = wp_create_nonce('blackcatpay-' . $user_id);
        // 最新付费查看er
        $do_shortcode ='<div class="content-hidden"><div class="content-hidden-before"><i class="ivu-icon ivu-icon-md-lock"></i></div>';
        $do_shortcode .= '<div class="content-hidden-info">
        <div class="content-hidden-info-title">隐藏内容,您需要满足以下条件方可查看</div>
        <div class="content-show-roles bk-mark" style="background: none; min-height: auto;"><div class="content-cap">
        <div class="content-cap-title"><span>以下方式可查看</span></div>
        <div class="content-cap-info content-user-lv">
        <span class="lv-icon user-vip">
            <i class="ivu-icon ivu-icon-logo-vimeo"></i>' . $rate_text . '</span>
            <span class="lv-icon user-vip user-price">
            <i class="ivu-icon ivu-icon-logo-usd"></i>' . $blackcat_this_am . '</span>
            <span class="lv-icon user-vip user-price">
            <i class="ivu-icon ivu-icon-logo-usd"></i>' . $blackcat_jifen_price . '积分</span>
        </div>';
        if ($blackcat_is_boosvip && is_boosvip_status($user_id)) {
            $do_shortcode .= '<button type="button" class="click-pay btn btn--secondary" data-postid="' . $post_id . '" data-nonce="' . $create_nonce . '" data-price="0' . $site_money_ua . '"> 永久'.$site_vip_name.'免费查看</button>';
        }else{
            $do_shortcode .= '<button type="button" class="click-pay btn btn--secondary" data-postid="' . $post_id . '" data-nonce="' . $create_nonce . '" data-price="' . $blackcat_this_am . '"><i class="ivu-icon ivu-icon-ios-download-outline"></i> 立即购买</button>';
        }
        $do_shortcode .= '</div></div></div></div>';
    }

    return $do_shortcode;

}
add_shortcode('bkhide', 'shop_shortcode');
//检测文章是否有设置视频
function _get_post_video_url()
{
  global $post;
  $video_url = get_post_meta($post->ID, 'video_url', true);
  if( $video_url != ''){
    return $video_url;
  }
  return false;
}


function wpdiary_user_guanzhu(){
    global $current_user;
    $user_id = $current_user->ID;
    if(!get_current_user_id()){
        exit(json_encode(['msg'=>'请登录!']));
    }
    if( $_POST['user']==get_current_user_id()){
        exit(json_encode(array('status' => '0','msg'=>'你不能关注自己!')));
    }
 
    $user = $_POST['user'];
    $meta     = get_user_meta(get_current_user_id(),'guanzhu',true);
    $bguanzhu1 = explode(',',get_user_meta($user,'bguanzhu',true)); 
    $bguanzhu = array_filter($bguanzhu1);   
    $guanzhu1  = explode(',',get_user_meta(get_current_user_id(),'guanzhu',true));
    $guanzhu = array_filter($guanzhu1);
    if(in_array($user,$guanzhu)){
 
        foreach($guanzhu as $k=>$v){
            if($v==$user){
                unset($guanzhu[$k]);
            }
        }
 
        foreach($bguanzhu as $k=>$v){
            if($v==get_current_user_id()){
                unset($bguanzhu[$k]);
            }
        }
        if ($user_id) {
            $blackcatUser   = new blackcatUser($user_id);
            $blackcatlog    = new blackcatlog();
            $old_money = $blackcatUser->get_balance();
            $new_money = $old_money ;
            $note      = '取消关注ID为'.$user.'的用户';
            $blackcatlog->addlog($user_id, $old_money, $old_money, $new_money, 'other', $note);
        }
        update_user_meta(get_current_user_id(),'guanzhu',implode(",",$guanzhu));
        update_user_meta($user,'bguanzhu',implode(",",$bguanzhu));
        $jifenold = get_user_meta($user_id,'blackcat_jifen')[0];
        if($numGuanzhu = count(get_user_meta(get_current_user_id(),'guanzhu')) <= _blackcat('jifen_guanzhu_limit')){
            update_user_meta(get_current_user_id(),'blackcat_jifen',$jifenold-_blackcat('jifen_guanzhu'));
            $noteguanzhu = '扣除积分'._blackcat('jifen_guanzhu');
            $blackcatlog->addlog($user_id, $old_money, $old_money, $new_money, 'other', $noteguanzhu);
        }
        $jifenoldb = get_user_meta($user,'blackcat_jifen')[0];
        if($twobGuanzhu = count(get_user_meta($user,'bguanzhu')) <= _blackcat('jifen_beguanzhu_limit')){
            update_user_meta($user,'blackcat_jifen',$jifenoldb-_blackcat('jifen_beguanzhu'));
            $noteBeguanzhu = '扣除积分'._blackcat('jifen_beguanzhu');
            $blackcatlog->addlog($user, $old_money, $old_money, $new_money, 'other', $noteBeguanzhu);
        }

        exit(json_encode(array('status' => '2','msg'=>'取消成功!')));
    }else{
        array_push($guanzhu,$user);
        array_push($bguanzhu,get_current_user_id());
        update_user_meta(get_current_user_id(),'guanzhu',implode(",",$guanzhu));
        update_user_meta($user,'bguanzhu',implode(",",$bguanzhu));
        $jifenold = get_user_meta($user_id,'blackcat_jifen')[0];
        if ($user_id) {
            $blackcatUser   = new blackcatUser($user_id);
            $blackcatlog    = new blackcatlog();
            $old_money = $blackcatUser->get_balance();
            $new_money = $old_money ;
            $note      = '关注ID为'.$user.'的用户';
            $blackcatlog->addlog($user_id, $old_money, $old_money, $new_money, 'other', $note);
        }
        if($numGuanzhu = count(get_user_meta(get_current_user_id(),'guanzhu')) <= _blackcat('jifen_guanzhu_limit')){
            update_user_meta(get_current_user_id(),'blackcat_jifen',$jifenold+_blackcat('jifen_guanzhu'));
            $noteguanzhu = '获得积分'._blackcat('jifen_guanzhu');
            $blackcatlog->addlog($user_id, $old_money, $old_money, $new_money, 'other', $noteguanzhu);
        }
        $jifenoldb = get_user_meta($user,'blackcat_jifen')[0];
        if($twobGuanzhu = count(get_user_meta($user,'bguanzhu')) <= _blackcat('jifen_beguanzhu_limit')){
            update_user_meta($user,'blackcat_jifen',$jifenoldb+_blackcat('jifen_beguanzhu'));
            $noteBeguanzhu = '获得积分'._blackcat('jifen_beguanzhu');
            $blackcatlog->addlog($user, $old_money, $old_money, $new_money, 'other', $noteBeguanzhu);
        }

        exit(json_encode(array('status' => '1','msg'=>'关注成功!')));
    }
 
}
 
add_action('wp_ajax_guanzhu','wpdiary_user_guanzhu');
add_action('wp_ajax_nopriv_guanzhu','wpdiary_user_guanzhu');
//获取指定用户关注数量
function get_wpdiary_guanzhu_count($authorID){
    $meta  = get_user_meta($authorID,'guanzhu',true);
    if($meta){
        $guanzhu = explode(",",get_user_meta($authorID,'guanzhu',true));
        return count($guanzhu);
    }else{
        return 0;
    }
 
}
//获取指定用户被关注数量
function get_wpdiary_bguanzhu_count($authorID){
    $meta  = get_user_meta($authorID,'bguanzhu',true);
    if($meta){
        $bguanzhu = explode(",",get_user_meta($authorID,'bguanzhu',true));
        return count($bguanzhu);
    }else{
        return 0;
    }
 
}
//自定义用户个人资料信息

function wpdaxue_add_contact_fields( $contactmethods ) {
$contactmethods['user_fanc'] = '粉丝'; //粉丝,记下关注者的ID
$contactmethods['user_follow'] = '关注别人'; //关注别人,记下被关注者的ID
$contactmethods['user_jifen'] = '积分';
$contactmethods['user_views'] = '总浏览量';
return $contactmethods;
}
add_filter( 'user_contactmethods', 'wpdaxue_add_contact_fields' );

//获取作者关注 的数
function get_guanzu($uid){
$author_follow = get_user_meta($uid,'user_follow'); //关注
if(empty($author_follow)){
$num1 = 0;
}else{
if($author_follow[0]==''){
$num1 = 0;
}else{
$follows = explode(",",$author_follow[0]);
$num1 = !empty($follows) ? count($follows) : 0;
}
}
return $num1;
}

//获取作者粉丝数
function get_fanc($uid){
$author_follow = get_user_meta($uid,'user_fanc'); //关注
if(empty($author_follow)){
$num1 = 0;
}else{
if($author_follow[0]==''){
$num1 = 0;
}else{
$follows = explode(",",$author_follow[0]);
$num1 = !empty($follows) ? count($follows) : 0;
}
}
return $num1;
}

//获取作者积分
function get_jefen($uid){
$user_jifen = get_user_meta($uid,'blackcat_jifen');
if(empty($user_jifen)){
$num = 0;
}else{
$num = ($user_jifen[0]=='') ? 0 : $user_jifen[0];
}
return $num;
}

//获取作者文章总浏览量
function get_post_views($uid){
$user_views = get_user_meta($uid,'user_views');
if(empty($user_views)){
$num = 0;
}else{
$num = ($user_views[0]=='') ? 0 : $user_views[0];
}
return $num;
}


//每天前xxx次评论 给 积分
function add_comment_difen( $commentdata ) {

global $wpdb;
$currentUser = wp_get_current_user();
$uid = $currentUser->ID;
$sql = "SELECT comment_date FROM {$wpdb->comments} WHERE user_id={$uid} ORDER BY comment_date DESC LIMIT 1";
$last_post = $wpdb->get_var($sql);
// 间隔120秒,才能再次评论
if ( current_time('timestamp') - strtotime($last_post) < 120 ){

wp_die("<script>alert('您评论也太勤快了吧,先歇会儿!'); history.back(); </script>");

}

if(!empty($currentUser->roles)) {

$date = date("Y-m-d",time());
$sql = "SELECT COUNT(comment_ID) FROM {$wpdb->comments}
WHERE user_id={$uid} AND (DATE_FORMAT(comment_date,'%Y-%m-%d') = '{$date}')";
$num = $wpdb->get_var($sql); //获取当前用户的评论次数

$author_commen_num = _blackcat('jifen_commont_limit'); //后台设置 每天评论获几次积分
if($num < $author_commen_num){ //如果当天评论次数 < 11

$jifen = get_jefen($uid); //获取当前用户积分
update_user_meta($uid,'blackcat_jifen',$jifen+_blackcat('jifen_commont')); //

}

      }
return $commentdata;

}
add_action( 'preprocess_comment' , 'add_comment_difen', 20);



 function num_of_author_posts($authorID=''){ //根据作者ID获取该作者的文章数量
 global $current_user;
    $authorID = $current_user->ID;
     if ($authorID) {
         $author_query = new WP_Query( 'posts_per_page=-1&author='.$authorID );
         $i=0;
         while ($author_query->have_posts()) : $author_query->the_post(); ++$i; endwhile; wp_reset_postdata();
         return $i;
     }
     return false;
 }


function user_registered_date(){
    $userinfo=get_userdata(get_current_user_id());
    $authorID= $userinfo->ID;
    $user = get_userdata( $authorID );
    $registered = $user->user_registered;
    echo  date( 'Y年m月d日', strtotime( $registered ) );
}

require get_template_directory() . '/poster/poster.php';
function zfunc_comments_users($postid=0,$which=0) {
    $comments = get_comments('status=approve&type=comment&post_id='.$postid); //获取文章的所有评论
    if ($comments) {
        $i=0; $j=0; $commentusers=array();
        foreach ($comments as $comment) {
            ++$i;
            if ($i==1) { $commentusers[] = $comment->comment_author_email; ++$j; }
            if ( !in_array($comment->comment_author_email, $commentusers) ) {
                $commentusers[] = $comment->comment_author_email;
                ++$j;
            }
        }
        $output = array($j,$i);
        $which = ($which == 0) ? 0 : 1;
        return $output[$which]; //返回评论人数
    }
    return 0; //没有评论返回0
}

function performance( $visible = true ) {
    $stat = sprintf( '%d 次查询 | 用时 %.3f 秒',
    get_num_queries(),
    timer_stop( 0, 3 ),
    memory_get_peak_usage() / 1024 / 1024
    );
    echo $visible ? $stat : "<!-- {$stat} -->" ;
    }


    function timeago( $ptime ) {
        $ptime = strtotime($ptime);
        $etime = time() - $ptime;
        if($etime < 1) return '刚刚';
        $interval = array (
            12 * 30 * 24 * 60 * 60  =>  '年前',
            30 * 24 * 60 * 60       =>  '个月前 ',
            7 * 24 * 60 * 60        =>  '周前 ',
            24 * 60 * 60            =>  '天前',
            60 * 60                 =>  '小时前',
            60                      =>  '分钟前',
            1                       =>  '秒前'
        );
        foreach ($interval as $secs => $str) {
            $d = $etime / $secs;
            if ($d >= 1) {
                $r = round($d);
                return $r . $str;
            }
        };
    }
    
    
 function get_user_id($user=''){
 $user="'".$user."'";
 global $wpdb;
 $user_ids = $wpdb->get_col("SELECT ID FROM $wpdb->users WHERE user_login = $user ORDER BY ID");
 foreach($user_ids as $user_id){
 return $user_id;
 }
}

function _the_theme_thumb_full()
{
    return get_template_directory_uri() . '/assets/images/thumb/full.jpg';
}

$labels = array(   
        'name' => '专题',    
        'singular_name' => 'special',   
        'search_items' =>  '搜索' ,   
        'popular_items' => '热门' ,   
        'all_items' => '所有' ,   
        'parent_item' => null,   
        'parent_item_colon' => null,   
        'edit_item' => '编辑' ,    
        'update_item' => '更新' ,   
        'add_new_item' => '添加' ,   
        'new_item_name' => '专题名称',   
        'separate_items_with_commas' => '按逗号分开' ,   
        'add_or_remove_items' => '添加或删除',   
        'choose_from_most_used' => '从经常使用的类型中选择',   
        'menu_name' => '专题',   
    );    
    register_taxonomy(   
        'special',
        array('post'),
        array(   
            'hierarchical' => true,   
            'labels' => $labels,   
            'show_ui' => true,   
            'query_var' => true,   
            'rewrite' => array( 'slug' => 'special' ),   
        )   
    );

    /**
 * [get_category_root_id description]
 * @Author   heimao
 * @DateTime 2019-08-15T09:57:46+0800
 * @param    [type]                   $cat [description]
 * @return   [type]                        [通过子分类id获取父分类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; // 返回根分类的id号
}


function get_category_deel($cat)
{
    
    $categories = get_terms('category', array('hide_empty' => 0,'parent' => 0));//获取所有主分类
    $get_term_children = get_term_children($cat_ID, 'category'); //获取当前分类的子分类
}

    /**
 * [_get_category_tags 获取文章标签 10条]
 * @Author   heimao
 * @DateTime 2019-05-28T12:20:43+0800
 * @param    [type]                   $args [description]
 * @return   [type]                         [description]
 */
function _get_category_tags($args)
{
    global $wpdb;
    $tags = $wpdb->get_results
        ("
        SELECT DISTINCT terms2.term_id as tag_id, terms2.name as tag_name
        FROM
            $wpdb->posts as p1
            LEFT JOIN $wpdb->term_relationships as r1 ON p1.ID = r1.object_ID
            LEFT JOIN $wpdb->term_taxonomy as t1 ON r1.term_taxonomy_id = t1.term_taxonomy_id
            LEFT JOIN $wpdb->terms as terms1 ON t1.term_id = terms1.term_id,

            $wpdb->posts as p2
            LEFT JOIN $wpdb->term_relationships as r2 ON p2.ID = r2.object_ID
            LEFT JOIN $wpdb->term_taxonomy as t2 ON r2.term_taxonomy_id = t2.term_taxonomy_id
            LEFT JOIN $wpdb->terms as terms2 ON t2.term_id = terms2.term_id
        WHERE
            t1.taxonomy = 'category' AND p1.post_status = 'publish' AND terms1.term_id IN (" . $args['categories'] . ") AND
            t2.taxonomy = 'post_tag' AND p2.post_status = 'publish'
            AND p1.ID = p2.ID
        ORDER by tag_name LIMIT 10
    ");
    $count = 0;

    if ($tags) {
        foreach ($tags as $tag) {
            $mytag[$count] = get_term_by('id', $tag->tag_id, 'post_tag');
            $count++;
        }
    } else {
        $mytag = null;
    }

    return $mytag;
}

// 分类图片上传
if (!defined('Z_PLUGIN_URL'))
define('Z_PLUGIN_URL', untrailingslashit(plugins_url('', __FILE__)));
define('Z_IMAGE_PLACEHOLDER', get_bloginfo("template_url")."/assets/images/hero/hero.jpg");
// l10n
load_plugin_textdomain('zci', FALSE, 'categories-images/languages');
add_action('admin_init', 'z_init');
function z_init() {
$z_taxonomies = get_taxonomies();
if (is_array($z_taxonomies)) {
$zci_options = get_option('zci_options');
if (empty($zci_options['excluded_taxonomies']))
$zci_options['excluded_taxonomies'] = array();
   foreach ($z_taxonomies as $z_taxonomy) {
if (in_array($z_taxonomy, $zci_options['excluded_taxonomies']))
continue;
       add_action($z_taxonomy.'_add_form_fields', 'z_add_texonomy_field');
add_action($z_taxonomy.'_edit_form_fields', 'z_edit_texonomy_field');
add_filter( 'manage_edit-' . $z_taxonomy . '_columns', 'z_taxonomy_columns' );
add_filter( 'manage_' . $z_taxonomy . '_custom_column', 'z_taxonomy_column', 10, 3 );
   }
}
}
function z_add_style() {
echo '<style type="text/css" media="screen">
th.column-thumb {width:60px;}
.form-field img.taxonomy-image {border:1px solid #eee;max-width:300px;max-height:300px;}
.inline-edit-row fieldset .thumb label span.title {width:48px;height:48px;border:1px solid #eee;display:inline-block;}
.column-thumb span {width:48px;height:48px;border:1px solid #eee;display:inline-block;}
.inline-edit-row fieldset .thumb img,.column-thumb img {width:48px;height:48px;}
</style>';
}
// add image field in add form
function z_add_texonomy_field() {
if (get_bloginfo('version') >= 3.5)
wp_enqueue_media();
else {
wp_enqueue_style('thickbox');
wp_enqueue_script('thickbox');
}
echo '<div class="form-field">
<label for="taxonomy_image">' . __('图像', 'zci') . '</label>
<input type="text" name="taxonomy_image" id="taxonomy_image" value="" />
<br/>
<button class="z_upload_image_button button">' . __('上传/添加图像', 'zci') . '</button>
</div>'.z_script();
}
// add image field in edit form
function z_edit_texonomy_field($taxonomy) {
if (get_bloginfo('version') >= 3.5)
wp_enqueue_media();
else {
wp_enqueue_style('thickbox');
wp_enqueue_script('thickbox');
}
if (z_taxonomy_image_url( $taxonomy->term_id, NULL, TRUE ) == Z_IMAGE_PLACEHOLDER)
$image_text = "";
else
$image_text = z_taxonomy_image_url( $taxonomy->term_id, NULL, TRUE );
echo '<tr class="form-field">
<th scope="row" valign="top"><label for="taxonomy_image">' . __('图像', 'zci') . '</label></th>
<td><img class="taxonomy-image" src="' . z_taxonomy_image_url( $taxonomy->term_id, NULL, TRUE ) . '" style="width:400px;"/><br/><input type="text" name="taxonomy_image" id="taxonomy_image" value="'.$image_text.'" /><br />
<button class="z_upload_image_button button">' . __('上传/添加图像', 'zci') . '</button>
<button class="z_remove_image_button button">' . __('删除图像', 'zci') . '</button>
</td>
</tr>'.z_script();
}
// upload using wordpress upload
function z_script() {
return '<script type="text/javascript">
   jQuery(document).ready(function($) {
var wordpress_ver = "'.get_bloginfo("version").'", upload_button;
$(".z_upload_image_button").click(function(event) {
upload_button = $(this);
var frame;
if (wordpress_ver >= "3.5") {
event.preventDefault();
if (frame) {
frame.open();
return;
}
frame = wp.media();
frame.on( "select", function() {
// Grab the selected attachment.
var attachment = frame.state().get("selection").first();
frame.close();
if (upload_button.parent().prev().children().hasClass("tax_list")) {
upload_button.parent().prev().children().val(attachment.attributes.url);
upload_button.parent().prev().prev().children().attr("src", attachment.attributes.url);
}
else
$("#taxonomy_image").val(attachment.attributes.url);
});
frame.open();
}
else {
tb_show("", "media-upload.php?type=image&amp;TB_iframe=true");
return false;
}
});
$(".z_remove_image_button").click(function() {
$("#taxonomy_image").val("");
$(this).parent().siblings(".title").children("img").attr("src","' . Z_IMAGE_PLACEHOLDER . '");
$(".inline-edit-col :input[name=\'taxonomy_image\']").val("");
return false;
});
if (wordpress_ver < "3.5") {
window.send_to_editor = function(html) {
imgurl = $("img",html).attr("src");
if (upload_button.parent().prev().children().hasClass("tax_list")) {
upload_button.parent().prev().children().val(imgurl);
upload_button.parent().prev().prev().children().attr("src", imgurl);
}
else
$("#taxonomy_image").val(imgurl);
tb_remove();
}
}
$(".editinline").live("click", function(){
   var tax_id = $(this).parents("tr").attr("id").substr(4);
   var thumb = $("#tag-"+tax_id+" .thumb img").attr("src");
if (thumb != "' . Z_IMAGE_PLACEHOLDER . '") {
$(".inline-edit-col :input[name=\'taxonomy_image\']").val(thumb);
} else {
$(".inline-edit-col :input[name=\'taxonomy_image\']").val("");
}
$(".inline-edit-col .title img").attr("src",thumb);
   return false;
});
   });
</script>';
}
// save our taxonomy image while edit or save term
add_action('edit_term','z_save_taxonomy_image');
add_action('create_term','z_save_taxonomy_image');
function z_save_taxonomy_image($term_id) {
    if(isset($_POST['taxonomy_image']))
        update_option('z_taxonomy_image'.$term_id, $_POST['taxonomy_image']);
}
// get attachment ID by image url
function z_get_attachment_id_by_url($image_src) {
    global $wpdb;
    $query = "SELECT ID FROM {$wpdb->posts} WHERE guid = '$image_src'";
    $id = $wpdb->get_var($query);
    return (!empty($id)) ? $id : NULL;
}
// get taxonomy image url for the given term_id (Place holder image by default)
function z_taxonomy_image_url($term_id = NULL, $size = NULL, $return_placeholder = FALSE) {
if (!$term_id) {
if (is_category())
$term_id = get_query_var('cat');
elseif (is_tax()) {
$current_term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy'));
$term_id = $current_term->term_id;
}
}
    $taxonomy_image_url = get_option('z_taxonomy_image'.$term_id);
    if(!empty($taxonomy_image_url)) {
   $attachment_id = z_get_attachment_id_by_url($taxonomy_image_url);
   if(!empty($attachment_id)) {
   if (empty($size))
   $size = 'full';
   $taxonomy_image_url = wp_get_attachment_image_src($attachment_id, $size);
   $taxonomy_image_url = $taxonomy_image_url[0];
   }
}
    if ($return_placeholder)
return ($taxonomy_image_url != '') ? $taxonomy_image_url : Z_IMAGE_PLACEHOLDER;
else
return $taxonomy_image_url;
}
function z_quick_edit_custom_box($column_name, $screen, $name) {
if ($column_name == 'thumb')
echo '<fieldset>
<div class="thumb inline-edit-col">
<label>
<span class="title"><img src="" alt="Thumbnail"/></span>
<span class="input-text-wrap"><input type="text" name="taxonomy_image" value="" class="tax_list" /></span>
<span class="input-text-wrap">
<button class="z_upload_image_button button">' . __('上传/添加图像', 'zci') . '</button>
<button class="z_remove_image_button button">' . __('删除图像', 'zci') . '</button>
</span>
</label>
</div>
</fieldset>';
}
/**
 * Thumbnail column added to category admin.
 *
 * @access public
 * @param mixed $columns
 * @return void
 */
function z_taxonomy_columns( $columns ) {
$new_columns = array();
$new_columns['cb'] = $columns['cb'];
$new_columns['thumb'] = __('图像', 'zci');
unset( $columns['cb'] );
return array_merge( $new_columns, $columns );
}
/**
 * Thumbnail column value added to category admin.
 *
 * @access public
 * @param mixed $columns
 * @param mixed $column
 * @param mixed $id
 * @return void
 */
function z_taxonomy_column( $columns, $column, $id ) {
if ( $column == 'thumb' )
$columns = '<span><img src="' . z_taxonomy_image_url($id, NULL, TRUE) . '" alt="' . __('Thumbnail', 'zci') . '" class="wp-post-image" /></span>';
return $columns;
}
// change 'insert into post' to 'use this image'
function z_change_insert_button_text($safe_text, $text) {
    return str_replace("Insert into Post", "Use this image", $text);
}
// style the image in category list
if ( strpos( $_SERVER['SCRIPT_NAME'], 'edit-tags.php' ) > 0 ) {
add_action( 'admin_head', 'z_add_style' );
add_action('quick_edit_custom_box', 'z_quick_edit_custom_box', 10, 3);
add_filter("attribute_escape", "z_change_insert_button_text", 10, 2);
}
// New menu submenu for plugin options in Settings menu
add_action('admin_menu', 'z_options_menu');
function z_options_menu() {
add_options_page(__('分类图像设置', 'zci'), __('分类图像', 'zci'), 'manage_options', 'zci-options', 'zci_options');
add_action('admin_init', 'z_register_settings');
}
// Register plugin settings
function z_register_settings() {
register_setting('zci_options', 'zci_options', 'z_options_validate');
add_settings_section('zci_settings', __('', 'zci'), 'z_section_text', 'zci-options');
add_settings_field('z_excluded_taxonomies', __('排除的分类', 'zci'), 'z_excluded_taxonomies', 'zci-options', 'zci_settings');
}
// Settings section description
function z_section_text() {
echo '<p>'.__('', 'zci').'</p>';
}
// Excluded taxonomies checkboxs
function z_excluded_taxonomies() {
$options = get_option('zci_options');
$disabled_taxonomies = array('nav_menu', 'link_category', 'post_format');
foreach (get_taxonomies() as $tax) : if (in_array($tax, $disabled_taxonomies)) continue; ?>
<input type="checkbox" name="zci_options[excluded_taxonomies][<?php echo $tax ?>]" value="<?php echo $tax ?>" <?php checked(isset($options['excluded_taxonomies'][$tax])); ?> /> <?php echo $tax ;?><br />
<?php endforeach;
}
// Validating options
function z_options_validate($input) {
return $input;
}
// Plugin option page
function zci_options() {
if (!current_user_can('manage_options'))
wp_die(__( 'You do not have sufficient permissions to access this page.', 'zci'));
$options = get_option('zci_options');
?>
<div class="wrap">
<?php screen_icon(); ?>
<h2><?php _e('分类图像设置', 'zci'); ?></h2>
<form method="post" action="options.php">
<?php settings_fields('zci_options'); ?>
<?php do_settings_sections('zci-options'); ?>
<?php submit_button(); ?>
</form>
</div>
<?php
}






add_filter( 'author_link', 'yundanran_author_link', 10, 2 );
function yundanran_author_link( $link, $author_id) {
    global $wp_rewrite;
    $author_id = (int) $author_id;
    $link = $wp_rewrite->get_author_permastruct();
 
    if ( empty($link) ) {
        $file = home_url( '/' );
        $link = $file . '?author=' . $author_id;
    } else {
        $link = str_replace('%author%', $author_id, $link);
        $link = home_url( user_trailingslashit( $link ) );
    }
 
    return $link;
}

add_filter( 'request', 'yundanran_author_link_request' );
function yundanran_author_link_request( $query_vars ) {
    if ( array_key_exists( 'author_name', $query_vars ) ) {
        global $wpdb;
        $author_id=$query_vars['author_name'];
        if ( $author_id ) {
            $query_vars['author'] = $author_id;
            unset( $query_vars['author_name'] );    
        }
    }
    return $query_vars;
}

/**
 * [is_boosvip_status description]
 * @Author   heimao
 * @DateTime 2019-08-16T10:29:40+0800
 * @param    [type]                   $user_id [description]
 * @return   boolean                           [是否永久会员]
 */
function is_boosvip_status($user_id)
{
    $vip_type     = get_user_meta($user_id, 'blackcat_user_type', true);
    $vip_end_date = get_user_meta($user_id, 'blackcat_vip_end_time', true);
    if ($vip_type == 'vip' && $vip_end_date == '9999-09-09') {
        return true;
    }
    return false;
}

//添加代码插入按钮
add_action('admin_init', 'insert_code_button');
function insert_code_button(){
    if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages') ) {
            return;
    }
}
add_filter( 'mce_buttons', 'register_highlight_button' );
function register_highlight_button( $buttons ) {
    array_push( $buttons, "|", "highlight" );
    return $buttons;
}

// 每周更新的文章数量
    function get_month_post_count(){
    $date_query = array(
    array(
    'after'=>'1 month ago'
    )
    );$args = array(
    'post_type' => 'post',
    'post_status'=>'publish',
    'date_query' => $date_query,
    'no_found_rows' => true,
    'suppress_filters' => true,
    'fields'=>'ids',
    'posts_per_page'=>-1
    );
    $query = new WP_Query( $args );
    echo $query->post_count;
    }
    
/*
==================================================
fancybox图片灯箱效果
==================================================
*/
add_filter('the_content', 'fancybox1');
// add_filter('the_content', 'fancybox2');
function fancybox1($content){ 
    global $post;
    $pattern = "/<img(.*?)src=('|')([^>]*).(bmp|gif|jpeg|jpg|png|swf)('|')(.*?)>/i";
    $replacement = '<a$1href=$2$3.$4$5 data-fancybox="images"><img$1src=$2$3.$4$5$6></a>';
    $content = preg_replace($pattern, $replacement, $content);
    return $content;
}
// function fancybox2($content){ 
//   global $post;
//  $pattern = "/<a(.*?)href=('|')([^>]*).(bmp|gif|jpeg|jpg|png|swf)("|")(.*?)>(.*?)</a>/i";
//  $replacement = '<a$1href=$2$3.$4$5 data-fancybox="images"$6>$7</a>';
//  $content = preg_replace($pattern, $replacement, $content);
//  return $content;nt;
// }

function mo_paging() {
    $p = 3;
    if ( is_singular() ) return;
    global $wp_query, $paged;
    $max_page = $wp_query->max_num_pages;
    if ( $max_page == 1 ) return; 
    echo '<div class="pagination"><ul>';
    if ( empty( $paged ) ) $paged = 1;
    echo '<li class="prev-page">'; previous_posts_link('上一页'); echo '</li>';
    if ( $paged > $p + 1 ) _paging_link( 1, '<li>第一页</li>' );
    if ( $paged > $p + 2 ) echo "<li><span>···</span></li>";
    for( $i = $paged - $p; $i <= $paged + $p; $i++ ) { 
        if ( $i > 0 && $i <= $max_page ) $i == $paged ? print "<li class=\"active\"><span>{$i}</span></li>" : _paging_link( $i );
    }
    if ( $paged < $max_page - $p - 1 ) echo "<li><span> ... </span></li>";
    echo '<li class="next-page">'; next_posts_link('下一页'); echo '</li>';
    echo '<li><span>共 '.$max_page.' 页</span></li>';
    echo '</ul></div>';
}

function _paging_link( $i, $title = '' ) {
    if ( $title == '' ) $title = "第 {$i} 页";
    echo "<li><a href='", esc_html( get_pagenum_link( $i ) ), "'>{$i}</a></li>";
}

add_action('init', 'my_custom_init');
function my_custom_init(){ 
    $labels = array( 'name' => '公告',
    'singular_name' => '公告', 
    'add_new' => '发布公告', 
    'add_new_item' => '发布公告',
    'edit_item' => '编辑公告', 
    'new_item' => '新公告',
    'view_item' => '查看公告',
    'search_items' => '搜索公告', 
    'not_found' => '暂无公告',
    'not_found_in_trash' => '没有已遗弃的公告',
    'parent_item_colon' => '', 'menu_name' => '公告' );
    $args = array( 'labels' => $labels,
    'public' => true, 
    'publicly_queryable' => true,
    'show_ui' => true,
    'show_in_menu' => true, 
    'exclude_from_search' =>true,
    'query_var' => true, 
    'rewrite' => true, 
    'capability_type' => 'post',
    'show_in_rest'        => true,
    'has_archive' => true, 
    'hierarchical' => false, 
    'menu_position' => null, 
    'menu_icon' =>'dashicons-megaphone',
    'supports' => array('editor','author','title', 'custom-fields') );
    register_post_type('announcement',$args); 
}

//非管理员不允许进入后台
if ( is_admin() && ( !defined( 'DOING_AJAX' ) || !DOING_AJAX ) ) {
$current_user = wp_get_current_user(); //获取当前登录用户的信息
if($current_user->roles[0] == get_option('default_role')) { //如果不是管理
wp_safe_redirect( home_url() ); //就安全地重定向到网站的首页
exit();
}
}



add_action( 'init', 'post_type_bubble' );
function post_type_bubble() {
    $labels = array(
        'name'               => '冒泡', 'post type general name', 'your-plugin-textdomain',
        'singular_name'      => '冒泡', 'post type singular name', 'your-plugin-textdomain',
        'menu_name'          => '冒泡', 'admin menu', 'your-plugin-textdomain',
        'name_admin_bar'     => '冒泡', 'add new on admin bar', 'your-plugin-textdomain',
        'add_new'            => '发布冒泡', 'bubble', 'your-plugin-textdomain',
        'add_new_item'       => '发布新冒泡', 'your-plugin-textdomain',
        'new_item'           => '新冒泡', 'your-plugin-textdomain',
        'edit_item'          => '编辑冒泡', 'your-plugin-textdomain',
        'view_item'          => '查看冒泡', 'your-plugin-textdomain',
        'all_items'          => '所有冒泡', 'your-plugin-textdomain',
        'search_items'       => '搜索冒泡', 'your-plugin-textdomain',
        'parent_item_colon'  => 'Parent 冒泡:', 'your-plugin-textdomain',
        'not_found'          => '你还没有发布冒泡。', 'your-plugin-textdomain',
        'not_found_in_trash' => '回收站中没有冒泡。', 'your-plugin-textdomain'
    );
    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite' => true,
        'show_in_rest'        => true,
        'capability_type'    => 'post',
        'menu_icon'          => 'dashicons-heart',
        'has_archive'        => false,
        'hierarchical'       => false,
        'supports'           => array( 'title', 'editor', 'author', 'excerpt', 'comments', 'thumbnail', 'revisions', 'custom-fields' ),
        'taxonomies' => array('bubblecate' ),
    );
    register_post_type( 'bubble', $args );
}

// 冒泡分类
add_action( 'init', 'create_bubble_taxonomies', 0 );
function create_bubble_taxonomies() {
    $labels = array(
        'name'              => '冒泡分类目录', 'taxonomy general name',
        'singular_name'     => '冒泡分类', 'taxonomy singular name',
        'search_items'      => '搜索冒泡目录',
        'all_items'         => '所有冒泡目录',
        'parent_item'       => '父级目录',
        'parent_item_colon' => '父级目录:',
        'edit_item'         => '编辑冒泡目录',
        'update_item'       => '更新冒泡目录',
        'add_new_item'      => '添加新冒泡目录',
        'new_item_name'     => 'New Genre Name',
        'menu_name'         => '冒泡分类',
    );
    $args = array(
        'hierarchical' => true,
        'labels' => $labels,
        'show_ui' => true,
        'query_var' => true,
        'show_in_rest'      => true,
    );
    register_taxonomy( 'bubblecate', array( 'bubble' ), $args );
}

// 友情链接新版
add_action( 'init', 'post_type_links' );
function post_type_links() {
    $labels = array(
        'name'               => '友链', 'post type general name', 'your-plugin-textdomain',
        'singular_name'      => '友链', 'post type singular name', 'your-plugin-textdomain',
        'menu_name'          => '友链', 'admin menu', 'your-plugin-textdomain',
        'name_admin_bar'     => '友链', 'add new on admin bar', 'your-plugin-textdomain',
        'add_new'            => '发布友链', 'links', 'your-plugin-textdomain',
        'add_new_item'       => '发布新友链', 'your-plugin-textdomain',
        'new_item'           => '新友链', 'your-plugin-textdomain',
        'edit_item'          => '编辑友链', 'your-plugin-textdomain',
        'view_item'          => '查看友链', 'your-plugin-textdomain',
        'all_items'          => '所有友链', 'your-plugin-textdomain',
        'search_items'       => '搜索友链', 'your-plugin-textdomain',
        'parent_item_colon'  => 'Parent 友链:', 'your-plugin-textdomain',
        'not_found'          => '你还没有发布友链。', 'your-plugin-textdomain',
        'not_found_in_trash' => '回收站中没有友链。', 'your-plugin-textdomain'
    );
    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite' => true,
        'show_in_rest'        => true,
        'capability_type'    => 'post',
        'menu_icon'          => 'dashicons-share-alt',
        'has_archive'        => false,
        'hierarchical'       => false,
        'supports'           => array( 'title', 'editor', 'author', 'excerpt', 'comments', 'thumbnail', 'revisions', 'custom-fields' ),
        'taxonomies' => array('linkscate' ),
    );
    register_post_type( 'links', $args );
}

// 友情链接分类
add_action( 'init', 'create_links_taxonomies', 0 );
function create_links_taxonomies() {
    $labels = array(
        'name'              => '友链分类目录', 'taxonomy general name',
        'singular_name'     => '友链分类', 'taxonomy singular name',
        'search_items'      => '搜索友链目录',
        'all_items'         => '所有友链目录',
        'parent_item'       => '父级目录',
        'parent_item_colon' => '父级目录:',
        'edit_item'         => '编辑友链目录',
        'update_item'       => '更新友链目录',
        'add_new_item'      => '添加新友链目录',
        'new_item_name'     => 'New Genre Name',
        'menu_name'         => '友链分类',
    );
    $args = array(
        'hierarchical'      => true,
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'show_in_rest'      => true,
        'query_var'         => true,

    );
    register_taxonomy( 'linkscate', array( 'links' ), $args );
}
// 新建演示网站字段
add_action( 'add_meta_boxes', 'original_web' );
function original_web() {
    add_meta_box(
        'original_web',
        '网站地址',
        'original_web_meta_box',
        'links',
        'side',
        'low'
    );
}
function original_web_meta_box($post) {
    // 创建临时隐藏表单,为了安全
    wp_nonce_field( 'original_web_meta_box', 'original_web_meta_box_nonce' );
    // 获取之前存储的值
    $value = get_post_meta( $post->ID, '_original_web', true );
    ?>
    <label for="original_web">网站地址</label>
       <input style="width:400px" type="text" id="original_web" name="original_web" value="<?php echo esc_attr( $value ); ?>" placeholder="以http://或者https://开头">
    <?php
}
add_action( 'save_post', 'original_web_save_meta_box' );
function original_web_save_meta_box($post_id){
    if ( ! isset( $_POST['original_web_meta_box_nonce'] ) ) {
        return;
    }
    if ( ! wp_verify_nonce( $_POST['original_web_meta_box_nonce'], 'original_web_meta_box' ) ) {
        return;
    }
    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        return;
    }
    if ( ! isset( $_POST['original_web'] ) ) {
        return;
    }
    $original_web = sanitize_text_field( $_POST['original_web'] );
    update_post_meta( $post_id, '_original_web', $original_web );
}
//自定义表情路径和名称
function custom_smilies_src($src, $img){return get_bloginfo('template_directory').'/assets/images/smilies/' . $img;}
add_filter('smilies_src', 'custom_smilies_src', 10, 2);
    if ( !isset( $wpsmiliestrans ) ) {
        $wpsmiliestrans = array(
        ':cy:' => 'f1.png',
        ':hanx:' => 'f2.png',
        ':huaix:' => 'f3.png',
        ':tx:' => 'f4.png',
          ':se:' => 'f5.png',
          ':wx:' => 'f6.png',
          ':zk:' => 'f7.png',
           ':shui:' => 'f8.png',
           ':kuk:' => 'f9.png',
           ':lh:' => 'f10.png',
           ':ku:' => 'f12.png',
           ':kel:' => 'f13.png',
           ':yiw:' => 'f14.png',
           ':yun:' => 'f15.png',
           ':jy:' => 'f16.png',
           ':dy:' => 'f17.png',
           ':gg:' => 'f18.png',
           ':fn:' => 'f19.png',
           ':fendou:' => 'f20.png',
          
        );
    }
    
class wp_baidu_record{
function __construct(){    
    function baidu_check($url, $post_id){
        $baidu_record  = get_post_meta($post_id,'baidu_record',true);
        if( $baidu_record != 1){
            $url='http://www.baidu.com/s?wd='.$url;
                $curl=curl_init();
                curl_setopt($curl,CURLOPT_URL,$url);
                curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
                $rs=curl_exec($curl);
                curl_close($curl);
        if(!preg_match_all('/提交网址/u',$rs,$match) && preg_match_all('/百度为您找到相关结果/u',$rs,$match)){
                   update_post_meta($post_id, 'baidu_record', 1) || add_post_meta($post_id, 'baidu_record', 1, true);
                   return 1;
                } else {  
                   return 0;
                }
        } else {
            return 1;
        }
}

add_filter('plugin_action_links', 'wp_baidu_record_plugin_action_links', 10, 3);
function wp_baidu_record_plugin_action_links($action_links, $plugin_file, $plugin_info) {
  $this_file = basename(__FILE__);
  if(substr($plugin_file, -strlen($this_file))==$this_file) {
    $new_action_links = array(
      "<a href='options-general.php?page=baidu_record'>设置</a>"
         );
    foreach($action_links as $action_link) {
      if (stripos($action_link, '>Edit<')===false) {
        if (stripos($action_link, '>Deactivate<')!==false) {
          $new_action_links[] = $action_link;
        } else {
          $new_action_links[] = $action_link;
        }
      }
    }
    return $new_action_links;
  }
  return $action_links;
}

function baidu_record() {
    global $wpdb;
    $post_id = ( null === $post_id ) ? get_the_ID() : $post_id;
    if(get_option('baidu_open_set')=="is_open"){
        if(baidu_check(get_permalink($post_id), $post_id) == 1){
            return '<a target="_blank" title="点击查看" rel="external nofollow" href="http://www.baidu.com/s?wd='.get_the_title().'">百度已收录</a>';
        } else {
            return '<a style="color:red;" rel="external nofollow" title="点击提交,谢谢您!" target="_blank" href="http://zhanzhang.baidu.com/sitesubmit/index?sitename='.get_permalink().'">百度未收录</a>';
        } 
    } else if (is_user_logged_in()) {
        if(baidu_check(get_permalink($post_id), $post_id) == 1){
            return '<a target="_blank" title="点击查看" class="is_sl" rel="external nofollow" href="http://www.baidu.com/s?wd='.get_the_title().'"><i class="heimao hm-icon_baidulogo"></i>百度已收录</a>';
        } else {
            return '<a style="color:red;" rel="external nofollow" title="点击可以手动提交到百度" target="_blank" href="http://zhanzhang.baidu.com/sitesubmit/index?sitename='.get_permalink().'"><i class="heimao hm-icon_baidulogo"></i>百度未收录</a>';
                }        
            }
        }
    }
}
new wp_baidu_record();

remove_action( 'admin_print_scripts',   'print_emoji_detection_script');
remove_action( 'admin_print_styles',    'print_emoji_styles');
remove_action( 'wp_head',       'print_emoji_detection_script', 7);
remove_action( 'wp_print_styles',   'print_emoji_styles');
remove_filter( 'the_content_feed',  'wp_staticize_emoji');
remove_filter( 'comment_text_rss',  'wp_staticize_emoji');
remove_filter( 'wp_mail',       'wp_staticize_emoji_for_email');


function remove_open_sans_from_wp_core() {

wp_deregister_style( 'open-sans');

wp_register_style( 'open-sans', false );

wp_enqueue_style('open-sans','');

}

add_action( 'init', 'remove_open_sans_from_wp_core');



function ludou_get_cat_postcount($id) { 
   // 获取当前分类信息 
   $cat = get_category($id); 
   // 当前分类文章数 
   $count = (int) $cat->count; 
   // 获取当前分类所有子孙分类 
   $tax_terms = get_terms('category', array('child_of' => $id)); 
   foreach ($tax_terms as $tax_term) { 
      // 子孙分类文章数累加 
      $count +=$tax_term->count; 
   } 
   return $count; 
}

// short code
function toz($atts, $content=null){
    return '<div id="sc_notice" class="tips">'.$content.'</div>';
}
add_shortcode('v_notice','toz');
function toa($atts, $content=null){
    return '<div id="sc_error" class="tips">'.$content.'</div>';
}
add_shortcode('v_error','toa');
function toc($atts, $content=null){
    return '<div id="sc_warn" class="tips">'.$content.'</div>';
}
add_shortcode('v_warn','toc');
function tod($atts, $content=null){
    return '<div id="sc_blue" class="tips">'.$content.'</div>';
}
add_shortcode('v_blue','tod');

// 文章目录
if(_blackcat('post-list-show')){
function article_index($content) {
    $matches = array();
    $ul_li = '';
    //匹配出 h2、h3 标题
    $rh = "/<h[23]>(.*)<\/h[23]>/im";
    $h2_num = 0;
    $h3_num = 0;
    //判断是否是文章页
    if(is_single()){
         if(preg_match_all($rh, $content, $matches)) {
            // 找到匹配的结果
            foreach($matches[1] as $num => $title) {
                $hx = substr($matches[0][$num], 0, 3);      //前缀,判断是 h2 还是 h3
                $start = stripos($content, $matches[0][$num]);  //匹配每个标题字符串的起始位置
                $end = strlen($matches[0][$num]);       //匹配每个标题字符串的结束位置
                if($hx == "<h2"){
                    $h2_num += 1; //记录 h2 的序列,此效果请查看百度百科中的序号,如 1.1、1.2 中的第一位数
                    $h3_num = 0;
                    // 文章标题添加 id,便于目录导航的点击定位
                    $content = substr_replace($content, '<h2 id="h2-'.$num.'">'.$title.'</h2>',$start,$end);
                    $title = preg_replace('/<.+>/', "", $title); //将 h2 里面的 a 链接或者其他标签去除,留下文字
                    $ul_li .= '<li class="h2_nav"><a href="#h2-'.$num.'" class="tooltip" title="'.$title.'">'.$title."</a></li>\n";
                            $content =  $content . "<div class=\"post_nav\"><p class='post-lcate'>文章目录</p><ul class=\"post_nav_content\">\n" . $ul_li . "</ul></div>\n";

                }else if($hx == "<h3"){
                    $h3_num += 1; //记录 h3 的序列,此熬过请查看百度百科中的序号,如 1.1、1.2 中的第二位数
                    $content = substr_replace($content, '<h3 id="h3-'.$num.'">'.$title.'</h3>',$start,$end);
                    $title = preg_replace('/<.+>/', "", $title); //将 h3 里面的 a 链接或者其他标签去除,留下文字
                    $ul_li .= '<li class="h3_nav"><a href="#h3-'.$num.'" class="tooltip" title="'.$title.'" >'.$title."</a></li>\n";
                            $content =  $content . "<div class=\"post_nav\"><p class='post-lcate'>文章目录</p><ul class=\"post_nav_content\">\n" . $ul_li . "</ul></div>\n";

                }   
            }
        }
        // 将目录拼接到文章
        return $content;
    }else{
        return $content;
    }
}
add_filter( "the_content", "article_index" );
}

// category limit VIP
function limited_access(){
    global $current_user;
    $blackcatUser = new blackcatUser($current_user->ID);
    $limitvip = _blackcat('vip_limit');
    $hello = explode(',',$limitvip);
    if(in_category($hello) && !is_home() && !$blackcatUser->vip_status() )
    {
        get_header();
        echo '<section class="no-results not-found vip-const">
                <div class="empty-page"><img src="wp-content/themes/blackcat/assets/images/un-login.png">
        <h2>该分类仅限VIP用户查看</h2></div>
        </section>';
        get_footer();
        exit;
    }
}
add_action( 'template_redirect', 'limited_access', 0 );

function par_pagenavi($range = 5){

    if ( is_singular() ) return; // 文章与插页不用
    global $wp_query, $paged;
    $max_page = $wp_query->max_num_pages;
    if ( $max_page == 1 ) return; // 只有一页不用
    if ( empty( $paged ) ) $paged = 1;
    global $paged, $wp_query;
    if ( !$max_page ) {$max_page = $wp_query->max_num_pages;}
    if($max_page > 1){
    if(!$paged){$paged = 1;}
    next_posts_link('加载更多');
    }
}

// 新增区域
function liangshare_widgets_init() {
    register_sidebar( array(
        'name' => __( '首页博客左侧', 'liangshare' ),
        'id' => 'portal-tools-left',
        'description' => __( '首页博客左侧', 'liangshare' ),
        'before_widget' => '<aside id="%1$s" class="widget %2$s">',
        'after_widget' => '</aside>',
        'before_title' => '<h3 class="widget-title">',
        'after_title' => '</h3>',
    ) );
    }
add_action( 'widgets_init', 'liangshare_widgets_init' );



// 新增区域
function liangshare_widgets_init_right() {
    register_sidebar( array(
        'name' => __( '首页博客右侧', 'blog_right' ),
        'id' => 'portal-tools-right',
        'description' => __( '首页博客右侧', 'blog_right' ),
        'before_widget' => '<div id="%1$s" class="widget %2$s">',
        'after_widget' => '</div>',
        'before_title' => '<div  class="widget--title"><h2>',
        'after_title' => '</h2></div>',
    ) );
    }
add_action( 'widgets_init', 'liangshare_widgets_init_right' );
// 筛选条件 搜索框
// 
function blackcat_only_selected_category($query)
{
    //is_search判断搜索页面  !is_admin排除后台  $query->is_main_query()只影响主循环
    if (!is_admin() && $query->is_main_query()) {
        // 排序:
        $order = !empty($_GET['sort']) ? $_GET['sort'] : null;
        $cat      = !empty($_GET['cat']) ? (int) $_GET['cat'] : null;
        $bk_type = !empty($_GET['bk']) ?  $_GET['bk'] : null;
        $custom_meta_arr = !empty($_GET) ? $_GET : null;
        $priceo = isset($_GET['priceo']) ? floatval($_GET['priceo']) : 0;
        $pricet = isset($_GET['pricet']) ? floatval($_GET['pricet']) : 0;
        $key_word = isset($_GET['key_word']) ? stripslashes($_GET['key_word']) : '';
        if(!empty($key_word)){
            $query->set('s', $key_word);
        }

        if ($order) {
            if ($order == 'hot') {
                $query->set( 'meta_key', 'views' );
                $query->set( 'orderby', 'meta_value_num');
                $query->set( 'order', 'DESC' );
            }else{
                $query->set('orderby', $order);
            }
        }
        //有cat值传入
        if ($cat) {
            $term_id = (int) $cat;
            $tax_query = array(
                array(
                    'taxonomy' => 'category', //可换为自定义分类法
                    'field'    => 'term_id',
                    'operator' => 'IN',
                    'terms'    => array($term_id),
                ),
            );
            $query->set('tax_query', $tax_query);
        }

        $custom_meta_query =  array();
        if ($bk_type) {
            switch ($bk_type) {
                case 'free':
                    $_type_meta_key = 'blackcat_price';
                    $_type_value = '0';
                    $_type_compare = '=';
                    break;
                case 'money':
                    $_type_meta_key = 'blackcat_price';
                    $_type_value = '0';
                    $_type_compare = '>';
                    break;
                case 'vipfree':
                    $_type_meta_key = 'blackcat_vip_rate';
                    $_type_value = '0';
                    $_type_compare = '=';
                    break;
                case 'vips':
                    $_type_meta_key = 'blackcat_vip_rate';
                    $_type_value = '1';
                    $_type_compare = '!=';
                    break;
                default:
                    break;
            }

            $type_meta_query =  array(
                array(
                    'key'     => $_type_meta_key,
                    'value'   => $_type_value,
                    'compare' => $_type_compare,
                )
            );
            array_push($custom_meta_query,$type_meta_query);
        }
        if($priceo>0||$pricet>0){
            array_push($custom_meta_query,array('key'=>'blackcat_price','value'=>$priceo,'compare'=>'>='));
            if($pricet>0){
                array_push($custom_meta_query,array('key'=>'blackcat_price','value'=>$pricet,'compare'=>'<='));
            }
        }
 
        if ($custom_meta_arr && _blackcat('is_custom_post_meta_opt', '0') && _blackcat('custom_post_meta_opt', '0')) {
            $custom_post_meta_opt = _blackcat('custom_post_meta_opt', '0');
            foreach ($custom_post_meta_opt as $filter) {
                $_meta_key = $filter['meta_ua'];
                if(array_key_exists($_meta_key,$custom_meta_arr) && $_GET[$_meta_key] != 'all'){
                     $opt_meta_query =  array(
                        array(
                            'key'     => $_meta_key,
                            'value'   => $_GET[$_meta_key],
                            'compare' => '=',
                        )
                    );
                    array_push($custom_meta_query,$opt_meta_query);
                }
            }
            
        }

        $query->set('meta_query', $custom_meta_query);

    }
    return $query;
}
add_filter('pre_get_posts', 'blackcat_only_selected_category');

function get_today_posts($uid,$post_type ='post') {

    global $wpdb;
    $date = date("Y-m-d",time());
    $sql = "SELECT COUNT(ID) FROM {$wpdb->posts} WHERE post_status='publish' AND post_author={$uid} AND post_type='post' AND (DATE_FORMAT(post_date,'%Y-%m-%d') = '{$date}')";
    //return $sql;
    $numposts = $wpdb->get_var($sql);
    return $numposts;

}
function title_change_page(){
    $nowUrl = home_url( add_query_arg( array() ) );
    if (strpos($nowUrl, 'task')  != false) {
        echo '任务积分 - ';
    }else if(strpos($nowUrl, 'message')  != false){
        echo '个人通知 - ';
    }else if(strpos($nowUrl, 'wallet')  != false){
        echo '我的钱包 - ';
    }else if(strpos($nowUrl, 'write')  != false){
        echo '发布文章 - ';
    }else if(strpos($nowUrl, 'chat')  != false){
        echo '私信中心 - ';
    }else if(strpos($nowUrl, 'ver')  != false){
        echo '认证管理 - ';
    }else if(strpos($nowUrl, 'svip')  != false){
        echo '会员开通 - ';
    }else if(strpos($nowUrl, 'setting')  != false){
        echo '个人设置 - ';
    }else if(strpos($nowUrl, 'editpost')  != false){
        echo '编辑文章 - ';
    }
}

function user_level($user_level_id){
    $jifen = get_user_meta($user_level_id,'blackcat_jifen')[0];
    $level = _blackcat('level_modal');
        $level1 = $level['level_one'];
        $level2 = $level['level_two'];
        $level3 = $level['level_three'];
        $level4 = $level['level_four'];
        $level5 = $level['level_five'];
        $level6 = $level['level_six'];
        $level7 = $level['level_seven'];
    if($jifen >= $level1 && $jifen < $level2) {
        echo '<img src='.get_template_directory_uri().'/assets/images/svg/level1.svg'.' class="user_level_set">';
    }else if($jifen >= $level2 && $jifen < $level3){
        echo '<img src='.get_template_directory_uri().'/assets/images/svg/level2.svg'.' class="user_level_set">';
    }else if($jifen >= $level3 && $jifen < $level4){
        echo '<img src='.get_template_directory_uri().'/assets/images/svg/level3.svg'.' class="user_level_set">';
    }else if($jifen >= $level4 && $jifen < $level5){
        echo '<img src='.get_template_directory_uri().'/assets/images/svg/level4.svg'.' class="user_level_set">';
    }else if($jifen >= $level5 && $jifen < $level6){
        echo '<img src='.get_template_directory_uri().'/assets/images/svg/level5.svg'.' class="user_level_set">';
    }else if($jifen >= $level6 && $jifen < $level7){
        echo '<img src='.get_template_directory_uri().'/assets/images/svg/level6.svg'.' class="user_level_set">';
    }else if($jifen >= $level7){
        echo '<img src='.get_template_directory_uri().'/assets/images/svg/level7.svg'.' class="user_level_set">';
    }else{
        echo '<img src='.get_template_directory_uri().'/assets/images/svg/level0.svg'.' class="user_level_set">';
    }

}


function one_images() {
    global $post, $posts;
    if (has_post_thumbnail($post)) {
        //如果有特色缩略图,则输出缩略图地址
        $image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );
        $post_thumbnail_src = $image[0];
    } else {
        $post_thumbnail_src = '';
        @$output            = preg_match_all('/<img[^>]*src="([^"]*)"[^>]*>/i', $post->post_content, $matches);
        if (!empty($matches[1][0])) {
            global $wpdb;
            $att = $wpdb->get_row($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid LIKE '%s'", $matches[1][0]));
            if ($att) {
                $post_thumbnail_src = $att->ID;
            } else {
                $post_thumbnail_src = $matches[1][0];
            }
        } else {
            $post_thumbnail_src = _the_theme_thumb();
        }
    }
    return $post_thumbnail_src;
}

function themtuts_plyr_css_and_js_files() {
    wp_enqueue_style('plyr-css', get_template_directory_uri() . '/assets/css/plyr.css', array(), '', 'all');
}
add_action( 'wp_footer', 'themtuts_plyr_css_and_js_files' );
//短代码
function themetuts_plyr_player($atts, $content=null) {
    extract(shortcode_atts(array("poster" => ''), $atts));
    $return = '<div class="plyr">';
    $return .= '<video poster="'.$poster.'" controls>';
    $return .= '<source src="'.$content.'" type="video/mp4">';
    $return .= '</video>';
    $return .= '</div> ';
    return $return;
}
add_shortcode('plyr' , 'themetuts_plyr_player' );

function email_all($message){
    global $current_user;
    $all= '
            <style>
        * {
            box-sizing: border-box;
        }
        body {
            font-family: "PingFang SC","Helvetica Neue","Helvetica","STHeitiSC-Light","Arial","Microsoft yahei","\005fae\008f6f\0096c5\009ed1",Verdana,sans-serif;
            font-weight: 400;
            font-size: 14px;
            line-height: 1.6;
            color: #333333;
            background: #f2f5f8;
        }
        a {
            color: #3292ff;
            text-decoration: none;
            border-bottom-style: dotted;
            border-bottom-width: 1px;
        }
        a:hover{
            text-decoration:none !important;
            border-bottom-style: solid;
        }
        h1,h2,h3,h4,h5,h6{
            font-weight: 500;
            line-height: 1.5;
            margin-bottom: 20px;
        }
        p {
            padding: 10px 0;
            margin-bottom: 10px;
        }
        .btn {
            font-weight: 500;
            border-radius: 4px;
            padding: 16px 30px;
            text-align: center;
            background: #3885ff;
            text-decoration: none;
            color: #fff;
            margin: 15px auto;
            font-size: 16px;
            display: inline-block;
            border: none;
        }
        .btn:hover{
            border: none;
        }
        .btn-success {
            background: #2ecc71
        }
        blockquote {
            border-radius: 3px;
            background: #f5f5f5;
            margin: 10px 0;
            padding: 15px 20px;
            color: #455667;
        }
        .center{
            text-align: center;
        }
    </style>
    <div class="wrapper" style="margin:0;padding:0;">
    <table width="100%" border="0" cellspacing="0" cellpadding="0" align="center">
        <tbody>
        <tr>
            <td class="inner" style="padding:30px 25px 40px 25px;background:#f2f5f8;" bgcolor="#f2f5f8" align="center">
                <table width="750" cellspacing="0" cellpadding="0" border="0">
                    <tbody>
                    <tr>
                        <td width="100%" style="border-radius:4px;background:#ffffff;" bgcolor="#ffffff" align="center">
                            <!-- Header -->
                            <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                <tbody>
                                <tr>
                                   <td width="100%" align="center"><div style="padding: 15px 0 0 20px;"><img src="'._blackcat('logo-light').'"  title="'. get_option('blogname').'" style="display:inline;margin:0;max-height:50px;width: auto;" border="0"></div></td>
                                </tr>
                                </tbody>
                            </table>
                            <!-- Main Body -->
                            <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                <tbody>
                                <tr>
                                    <td width="100%">
                                        <div style="padding:20px 20px 40px;font-size:15px;line-height:1.5;color:#3d464d;">
                                            <!-- Content -->
                                            <style>
                        img{max-width:100%;}
                      </style>
                                            <p> 您好!'.$current_user->display_name.'</p>
                                            <p>'.$message.'</p>
                                        
                                        </div>
                                    </td>
                                </tr>
                                </tbody>
                            </table>
                            <!-- Footer -->
                        </td>
                    </tr>
                    <tr>
                        <!-- Outer Footer -->
                        <td width="100%" align="center" style="font-size:10px;line-height: 1.5;color: #999999;padding: 5px 0;text-align:center;">
                            <p style="margin:10px 0 0;">此为系统自动发送邮件, 请勿直接回复.</p>
                            <p style="margin:10px 0 0;">版权所有 © '. date("Y") . ' ' . get_option('blogname').'</p>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </td>
        </tr>
        </tbody>
    </table>
</div>';
return $all;
}

add_filter('wp_mail_content_type', 'sola520_use_html');
function sola520_use_html( $content_type ) {
if( true )
return 'text/html';
else
return $content_type;
}

onuda silince tema düz beyaz oluyor napacağımı şaşırdım