<?php
/**
 * Donovan functions and definitions
 *
 * @package Donovan
 */

/**
 * Donovan only works in WordPress 4.7 or later.
 */
if ( version_compare( $GLOBALS['wp_version'], '4.7-alpha', '<' ) ) {
	require get_template_directory() . '/inc/back-compat.php';
	return;
}


if ( ! function_exists( 'donovan_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 donovan_setup() {

		// Make theme available for translation. Translations can be filed at https://translate.wordpress.org/projects/wp-themes/donovan
		load_theme_textdomain( 'donovan', get_template_directory() . '/languages' );

		// Add default posts and comments RSS feed links to head.
		add_theme_support( 'automatic-feed-links' );

		// Let WordPress manage the document title.
		add_theme_support( 'title-tag' );

		// Enable support for Post Thumbnails on posts and pages.
		add_theme_support( 'post-thumbnails' );

		// Set detfault Post Thumbnail size.
		set_post_thumbnail_size( 1360, 765, true );

		// Register Navigation Menus.
		register_nav_menus( array(
			'primary' => esc_html__( 'Main Navigation', 'donovan' ),
			'social'  => esc_html__( 'Social Icons', 'donovan' ),
		) );

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

		// Set up the WordPress core custom background feature.
		add_theme_support( 'custom-background', apply_filters( 'donovan_custom_background_args', array(
			'default-color' => 'cccccc',
		) ) );

		// Set up the WordPress core custom logo feature.
		add_theme_support( 'custom-logo', apply_filters( 'donovan_custom_logo_args', array(
			'height'      => 60,
			'width'       => 300,
			'flex-height' => true,
			'flex-width'  => true,
		) ) );

		// Set up the WordPress core custom header feature.
		add_theme_support( 'custom-header', apply_filters( 'donovan_custom_header_args', array(
			'header-text' => false,
			'width'       => 2560,
			'height'      => 500,
			'flex-width'  => true,
			'flex-height' => true,
		) ) );

		// Add extra theme styling to the visual editor.
		add_editor_style( array( 'assets/css/editor-style.css' ) );

		// Add Theme Support for Selective Refresh in Customizer.
		add_theme_support( 'customize-selective-refresh-widgets' );

		// Add support for responsive embed blocks.
		add_theme_support( 'responsive-embeds' );
	}
endif;
add_action( 'after_setup_theme', 'donovan_setup' );


/**
 * Set the content width in pixels, based on the theme's design and stylesheet.
 * Priority 0 to make it available to lower priority callbacks.
 *
 * @global int $content_width
 */
function donovan_content_width() {
	$GLOBALS['content_width'] = apply_filters( 'donovan_content_width', 910 );
}
add_action( 'after_setup_theme', 'donovan_content_width', 0 );


/**
 * Register widget areas and custom widgets.
 *
 * @link http://codex.wordpress.org/Function_Reference/register_sidebar
 */
function donovan_widgets_init() {

	register_sidebar( array(
		'name'          => esc_html__( 'Sidebar', 'donovan' ),
		'id'            => 'sidebar-1',
		'description'   => esc_html_x( 'Sidebar will appear on posts and pages, except with the full width template.', 'widget area description', 'donovan' ),
		'before_widget' => '<section id="%1$s" class="widget %2$s">',
		'after_widget'  => '</section>',
		'before_title'  => '<h4 class="widget-title">',
		'after_title'   => '</h4>',
	) );

}
add_action( 'widgets_init', 'donovan_widgets_init' );


/**
 * Enqueue scripts and styles.
 */
function donovan_scripts() {

	// Get Theme Version.
	$theme_version = wp_get_theme()->get( 'Version' );

	// Register and Enqueue Stylesheet.
	wp_enqueue_style( 'donovan-stylesheet', get_stylesheet_uri(), array(), $theme_version );

	// Register and enqueue navigation.min.js.
	if ( ( has_nav_menu( 'primary' ) || has_nav_menu( 'secondary' ) ) && ! donovan_is_amp() ) {
		wp_enqueue_script( 'donovan-navigation', get_theme_file_uri( '/assets/js/navigation.min.js' ), array(), '20220224', true );
		$donovan_l10n = array(
			'expand'   => esc_html__( 'Expand child menu', 'donovan' ),
			'collapse' => esc_html__( 'Collapse child menu', 'donovan' ),
			'icon'     => donovan_get_svg( 'expand' ),
		);
		wp_localize_script( 'donovan-navigation', 'donovanScreenReaderText', $donovan_l10n );
	}

	// Enqueue svgxuse to support external SVG Sprites in Internet Explorer.
	if ( ! donovan_is_amp() ) {
		wp_enqueue_script( 'svgxuse', get_theme_file_uri( '/assets/js/svgxuse.min.js' ), array(), '1.2.6' );
	}

	// Register Comment Reply Script for Threaded Comments.
	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
		wp_enqueue_script( 'comment-reply' );
	}
}
add_action( 'wp_enqueue_scripts', 'donovan_scripts' );


/**
* Enqueue theme fonts.
*/
function donovan_theme_fonts() {
	$fonts_url = donovan_get_fonts_url();

	// Load Fonts if necessary.
	if ( $fonts_url ) {
		require_once get_theme_file_path( 'inc/wptt-webfont-loader.php' );
		wp_enqueue_style( 'donovan-theme-fonts', wptt_get_webfont_url( $fonts_url ), array(), '20201110' );
	}
}
add_action( 'wp_enqueue_scripts', 'donovan_theme_fonts', 1 );
add_action( 'enqueue_block_editor_assets', 'donovan_theme_fonts', 1 );


/**
 * Retrieve webfont URL to load fonts locally.
 */
function donovan_get_fonts_url() {
	$font_families = array(
		'Raleway:400,400italic,700,700italic',
		'Quicksand:400,400italic,700,700italic',
	);

	$query_args = array(
		'family'  => urlencode( implode( '|', $font_families ) ),
		'subset'  => urlencode( 'latin,latin-ext' ),
		'display' => urlencode( 'swap' ),
	);

	return apply_filters( 'donovan_get_fonts_url', add_query_arg( $query_args, 'https://fonts.googleapis.com/css' ) );
}


/**
 * Add custom sizes for featured images
 */
function donovan_add_image_sizes() {

	add_image_size( 'donovan-list-post', 600, 450, true );

}
add_action( 'after_setup_theme', 'donovan_add_image_sizes' );


/**
 * Make custom image sizes available in Gutenberg.
 */
function donovan_add_image_size_names( $sizes ) {
	return array_merge( $sizes, array(
		'post-thumbnail'    => esc_html__( 'Donovan Single Post', 'donovan' ),
		'donovan-list-post' => esc_html__( 'Donovan List Post', 'donovan' ),
	) );
}
add_filter( 'image_size_names_choose', 'donovan_add_image_size_names' );


/**
 * Add pingback url on single posts
 */
function donovan_pingback_url() {
	if ( is_singular() && pings_open() ) {
		printf( '<link rel="pingback" href="%s">' . "\n", get_bloginfo( 'pingback_url' ) );
	}
}
add_action( 'wp_head', 'donovan_pingback_url' );


/**
 * Include Files
 */

// Include Theme Info page.
require get_template_directory() . '/inc/theme-info.php';

// Include Theme Customizer Options.
require get_template_directory() . '/inc/customizer/customizer.php';
require get_template_directory() . '/inc/customizer/default-options.php';

// Include SVG Icon Functions.
require get_template_directory() . '/inc/icons.php';

// Include Template Functions.
require get_template_directory() . '/inc/template-functions.php';

// Include Template Tags.
require get_template_directory() . '/inc/template-tags.php';

// Include Gutenberg Features.
require get_template_directory() . '/inc/gutenberg.php';

// Include support functions for Theme Addons.
require get_template_directory() . '/inc/addons.php';

//内容页描述和关键词
//
// 添加自定义描述字段
function add_custom_field_meta_boxes() {
    add_meta_box('description-keywords', 'SEO Description & Keywords', 'render_description_keywords_meta_box', 'post', 'normal', 'high');
    add_meta_box('post-tags', 'Tags', 'render_tags_meta_box', 'post', 'normal', 'high');
}
add_action('add_meta_boxes', 'add_custom_field_meta_boxes');
 
// 描述和关键词输入框的回调函数
function render_description_keywords_meta_box($post) {
    // 获取当前文章的描述和关键词
    $description = get_post_meta($post->ID, 'description', true);
    $keywords = get_post_meta($post->ID, 'keywords', true);
    ?>
    <div style="margin-top: 10px;">
        <label for="description">SEO Description:</label><br>
        <textarea name="description" id="description" rows="2" cols="80"><?php echo esc_attr($description); ?></textarea>
        <label for="keywords">SEO Keywords:</label><br>
        <input type="text" name="keywords" id="keywords" value="<?php echo esc_attr($keywords); ?>" size="55">
    </div>
    <?php
}
 
// 标签输入框的回调函数
function render_tags_meta_box($post) {
    $tags = get_the_terms($post->ID, 'post_tag');
    $tags_list = '';
    if (is_array($tags)) {
        foreach ($tags as $tag) {
            $tags_list .= $tag->name . ', ';
        }
        $tags_list = rtrim($tags_list, ', ');
    }
    ?>
    <div style="margin-top: 10px;">
        <label for="tags">Tags:</label><br>
        <input type="text" name="tags" id="tags" value="<?php echo esc_attr($tags_list); ?>" size="55">
    </div>
    <?php
}
 
// 保存自定义字段的数据
function save_custom_field_meta_box_data($post_id) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;
 
    // 保存描述和关键词
    update_post_meta($post_id, 'description', sanitize_text_field($_POST['description']));
    update_post_meta($post_id, 'keywords', sanitize_text_field($_POST['keywords']));
 
    // 保存标签
    if (isset($_POST['tags'])) {
        $tags = explode(',', $_POST['tags']);
        $tags = array_map('sanitize_text_field', $tags);
        wp_set_post_tags($post_id, $tags);
    }
}
add_action('save_post', 'save_custom_field_meta_box_data');


//首页的描述和关键词
// 钩子函数，用于替换内容中的字符串
add_filter('the_content', 'replace_content_strings');
 
function replace_content_strings($content) {
    // 要替换的字符串
    $old_string = '一建报考';
    $new_string = '报考';
 
    // 执行替换操作
    $content = str_replace($old_string, $new_string, $content);
 
    return $content;
}



//内容页 关键词 描述
//
add_action( 'wp_head', 'custom_meta_tags' );
function custom_meta_tags() {
    global $post;
 
    if ( is_page( 'your-page-slug' ) ) { // 替换 'your-page-slug' 为你的页面路径
        $description = '这里是页面的描述'; // 设置页面描述
        $keywords = '关键词1, 关键词2'; // 设置页面关键词
 
        echo '<meta name="description" content="' . esc_attr( $description ) . '" />' . "\n";
        echo '<meta name="keywords" content="' . esc_attr( $keywords ) . '" />' . "\n";
    }
}



//手机端



//菜单，域名替换

// 钩子函数，用于修改页面链接
add_filter('page_link', 'replace_domain_in_page_link', 10, 2);
 
// 定义函数，用于替换链接中的域名
function replace_domain_in_page_link($link, $id) {
    // 获取页面数据
    $post = get_post($id);
 
    // 新的域名
    $new_domain = 'http://www.jianzhu69.com/';
 
    // 替换链接中的域名
    $link = str_replace(home_url('/'), $new_domain, $link);
 
    return $link;
}
//友情链接
function register_my_menu() {
  register_nav_menu('footer_menu', __('Footer Menu', 'theme_name'));
}
add_action('init', 'register_my_menu');


//栏目页
function custom_excerpt_length( $length ) {
    return 50; // 返回你想要的内容长度，这里是100字符
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );



function add_custom_query_var_filter( $vars ){
    $vars[] = "ppp"; // ppp 是每页帖子数
    return $vars;
}
add_filter( 'query_vars', 'add_custom_query_var_filter' );

//首页关键词和描述
function add_homepage_meta_tags() {
    if (is_home() || is_front_page()) {
        echo '<meta name="description" content="一建报考网是专业关注报考信息和条件的网站，报考对于一建是需要考核自身条件的选择，报考条件核心就是专业，学历和工作年限。;
        echo '<meta name="keywords" content="一建报考   报考条件   报考时间" />' . "\n";
    }
}
add_action('wp_head', 'add_homepage_meta_tags');

//加入title文件
function theme_slug_setup() {
    add_theme_support( 'title-tag' );
}
add_action( 'after_setup_theme', 'theme_slug_setup' );





/*新的首页*/

/**
 * 获取指定分类目录（ID: 1,3,4,5,8,9,10,11,12）
 * 对应 home.php 中调用的 get_all_categories_flat()
 */
function get_all_categories_flat() {
    // 指定要显示的分类 ID 列表
    $include_ids = array(1, 3, 4, 5, 8, 9, 10, 11, 12);

    $categories = get_categories(array(
        'include'    => $include_ids,
        'orderby'    => 'include',
        'hide_empty' => false,
    ));

    if (empty($categories)) {
        return '<p>没有找到指定分类。</p>';
    }

    $html = '<div class="all-categories-wrapper">';
    $html .= '<h3 class="all-categories-title">📂 全部分类</h3>';
    $html .= '<ul class="all-categories-list">';
    foreach ($categories as $cat) {
        $link = get_category_link($cat->term_id);
        $name = esc_html($cat->name);
        $count = $cat->count;
        $html .= sprintf(
            '<li><a href="%s">%s <span class="cat-count">(%d篇)</span></a></li>',
            esc_url($link),
            $name,
            $count
        );
    }
    $html .= '</ul></div>';
    return $html;
}
?>