子目录functions.php文件添加代码

[reply]

<?php
/**
 * GeneratePress child theme functions and definitions.
 *
 * Add your custom PHP in this file.
 * Only edit this file if you have direct access to it on your server (to fix errors if they happen).
 */

/**
 * GeneratePress Child Theme Functions
 * 碎语札记相关功能
 */

// ===== 禁用内容自动转义,修复破折号等字符乱码 =====
remove_filter('the_content', 'wptexturize');
remove_filter('the_excerpt', 'wptexturize');
remove_filter('comment_text', 'wptexturize');

// 修复标题乱码
function fix_document_title_entities($title) {
    if (isset($title)) {
        $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
    }
    return $title;
}
add_filter('document_title', 'fix_document_title_entities');

/**
 * ===== 碎语轻量修复包 =====
 * 只修复必要的问题,不破坏正常结构
 */

// 1. 修复MORE标签锚点(这是必要的)
add_filter('the_content_more_link', 'fix_micropost_more_link');
function fix_micropost_more_link($link) {
    if (get_post_type() == 'micropost') {
        $link = str_replace('#more-', '#post-', $link);
    }
    return $link;
}

// 2. 确保MORE标签在列表页正确截断
add_action('pre_get_posts', 'fix_micropost_archive_display');
function fix_micropost_archive_display($query) {
    if (!is_admin() && $query->is_main_query() && is_post_type_archive('micropost')) {
        add_filter('the_content', function($content) {
            global $more;
            $more = 0;
            return $content;
        }, 5);
    }
}

// 3. 只过滤明显的错误标签,不破坏正常标签云
add_filter('get_the_terms', 'filter_error_micropost_tags', 10, 3);
function filter_error_micropost_tags($terms, $post_id, $taxonomy) {
    // 只处理碎语标签
    if ($taxonomy != 'micropost_tag' || empty($terms) || !is_array($terms)) {
        return $terms;
    }
    
    foreach ($terms as $key => $term) {
        if (is_object($term) && isset($term->name)) {
            // 只删除 more- 开头的错误标签
            if (strpos($term->name, 'more-') !== false) {
                unset($terms[$key]);
            }
            // 注意:不要删除颜色代码标签,让它们正常显示
        }
    }
    
    return $terms;
}
// ===== 自定义碎语 Feed =====
if ( ! function_exists( 'zr_register_suiyu_feed' ) ) {
    function zr_register_suiyu_feed() {
        add_feed( 'suiyu-zhaji-feed', 'zr_suiyu_feed_template' );
    }
    add_action( 'init', 'zr_register_suiyu_feed' );
}

if ( ! function_exists( 'zr_suiyu_feed_template' ) ) {
    function zr_suiyu_feed_template() {
        while ( ob_get_level() ) ob_end_clean();
        add_action( 'pre_get_posts', 'zr_filter_suiyu_feed_query' );
        load_template( ABSPATH . WPINC . '/feed-rss2.php' );
    }
}

if ( ! function_exists( 'zr_filter_suiyu_feed_query' ) ) {
    function zr_filter_suiyu_feed_query( $query ) {
        if ( ! is_admin() && $query->is_main_query() && $query->is_feed( 'suiyu-zhaji-feed' ) ) {
            $query->set( 'post_type', 'micropost' );
            $query->set( 'posts_per_page', 15 );
            $query->set( 'no_found_rows', true );
            add_filter( 'pre_option_rss_use_excerpt', '__return_zero' );
        }
    }
}

// ===== 主 Feed 排除碎语文章 =====
if ( ! function_exists( 'zr_exclude_suiyu_from_main_feed' ) ) {
    function zr_exclude_suiyu_from_main_feed( $query ) {
        if ( ! is_admin() && $query->is_main_query() && $query->is_feed() && ! $query->is_feed( 'suiyu-zhaji-feed' ) ) {
            $types = $query->get( 'post_type' );
            if ( empty( $types ) ) $types = array( 'post' );
            if ( ! is_array( $types ) ) $types = array( $types );
            $types = array_diff( $types, array( 'micropost' ) );
            $query->set( 'post_type', $types );
        }
    }
    add_action( 'pre_get_posts', 'zr_exclude_suiyu_from_main_feed' );
}

// ===== 碎语Feed链接显示 =====
add_filter( 'feed_links_show_posts_feed', '__return_true' );
add_action( 'wp_head', 'zr_add_suiyu_feed_link' );
function zr_add_suiyu_feed_link() {
    echo '<link rel="alternate" type="application/rss+xml" title="' . get_bloginfo('name') . ' » 碎语札记 Feed" href="' . get_feed_link( 'suiyu-zhaji-feed' ) . '" />' . "\n";
}

// ===== 修复小工具查询 =====
add_filter('widget_posts_args', 'zr_include_suiyu_in_widget');
function zr_include_suiyu_in_widget($args) {
    $args['post_type'] = array('post', 'micropost');
    return $args;
}

// ===== 最新碎语小工具 =====
add_action('widgets_init', 'zr_register_suiyu_widget');
function zr_register_suiyu_widget() {
    register_widget('ZR_Suiyu_Recent_Widget');
}

class ZR_Suiyu_Recent_Widget extends WP_Widget {
    public function __construct() {
        parent::__construct(
            'zr_suiyu_recent',
            '最新碎语',
            array('description' => '仅显示碎语文章')
        );
    }

    public function widget($args, $instance) {
        $title = !empty($instance['title']) ? $instance['title'] : '最新碎语';
        $number = !empty($instance['number']) ? $instance['number'] : 5;

        $recent = new WP_Query(array(
            'post_type' => 'micropost',
            'posts_per_page' => $number,
            'post_status' => 'publish',
            'no_found_rows' => true
        ));

        if ($recent->have_posts()) {
            echo $args['before_widget'];
            echo $args['before_title'] . esc_html($title) . $args['after_title'];
            echo '<ul class="suiyu-widget-list">';
            while ($recent->have_posts()) {
                $recent->the_post();
                echo '<li>';
                echo '<a href="' . get_permalink() . '">' . get_the_title() . '</a>';
                echo '<span class="post-date">' . get_the_date('m-d') . '</span>';
                echo '</li>';
            }
            echo '</ul>';
            echo $args['after_widget'];
            wp_reset_postdata();
        }
    }

    public function form($instance) {
        $title = !empty($instance['title']) ? $instance['title'] : '最新碎语';
        $number = !empty($instance['number']) ? $instance['number'] : 5;
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>">标题:</label>
            <input type="text" id="<?php echo $this->get_field_id('title'); ?>" 
                   name="<?php echo $this->get_field_name('title'); ?>" 
                   value="<?php echo esc_attr($title); ?>" class="widefat">
        </p>
        <p>
            <label for="<?php echo $this->get_field_id('number'); ?>">显示数量:</label>
            <input type="number" id="<?php echo $this->get_field_id('number'); ?>" 
                   name="<?php echo $this->get_field_name('number'); ?>" 
                   value="<?php echo esc_attr($number); ?>" min="1" max="20">
        </p>
        <?php
    }

    public function update($new_instance, $old_instance) {
        $instance = array();
        $instance['title'] = sanitize_text_field($new_instance['title']);
        $instance['number'] = intval($new_instance['number']);
        return $instance;
    }
}

// ===== 动态去重碎语Feed =====
add_filter('posts_results', 'syzj_deduplicate_feed_posts', 10, 2);
function syzj_deduplicate_feed_posts($posts, $query) {
    if ($query->is_feed('suiyu-zhaji-feed') && !is_admin()) {
        $unique = array();
        $titles = array();
        
        foreach ($posts as $post) {
            if (!in_array($post->post_title, $titles)) {
                $unique[] = $post;
                $titles[] = $post->post_title;
            }
        }
        return $unique;
    }
    return $posts;
}

// ===== 在碎语单页禁用 Post Footer Info 插件(修复版) =====
add_action( 'wp', 'suiyu_disable_post_footer_info' );
function suiyu_disable_post_footer_info() {
    if ( is_singular( 'micropost' ) ) {
        add_filter( 'the_content', 'suiyu_remove_footer_info', 999 );
    }
}

function suiyu_remove_footer_info( $content ) {
    if ( is_singular( 'micropost' ) ) {
        $content = preg_replace('/<div[^>]*class="[^"]*post-footer-info[^"]*"[^>]*>.*?<\/div>/is', '', $content);
        $content = preg_replace('/<div[^>]*class="[^"]*related-posts[^"]*"[^>]*>.*?<\/div>/is', '', $content);
        $content = preg_replace('/<section[^>]*class="[^"]*related-posts[^"]*"[^>]*>.*?<\/section>/is', '', $content);
        $content = preg_replace('/<div[^>]*class="[^"]*copyright[^"]*"[^>]*>.*?<\/div>/is', '', $content);
    }
    return $content;
}

// ===== JavaScript 修复小工具图片 =====
add_action('wp_footer', 'suiyu_limit_widget_images');
function suiyu_limit_widget_images() {
    if (wp_is_mobile()) {
        ?>
        <script>
        function limitWidgetImages() {
            var images = document.querySelectorAll('.widget img, .suiyu-widget-list img');
            for (var i = 0; i < images.length; i++) {
                var img = images[i];
                if (img.parentElement) {
                    img.style.maxWidth = '100%';
                    img.style.height = 'auto';
                }
            }
        }
        limitWidgetImages();
        setTimeout(limitWidgetImages, 500);
        window.addEventListener('load', limitWidgetImages);
        window.addEventListener('resize', limitWidgetImages);
        </script>
        <?php
    }
}
// ================================
// 碎语视频短代码(电脑竖屏自动变窄版)
// ================================
function suiyu_video_shortcode($atts) {
    $atts = shortcode_atts(array(
        'src' => '',
        'title' => '',
    ), $atts, 'suiyu_video');

    if (empty($atts['src'])) return '';

    ob_start();
    ?>

    <div class="suiyu-video-wrapper">
        <video src="<?php echo esc_url($atts['src']); ?>" 
       controls 
       controlsList="nodownload"
       preload="metadata"
       loading="lazy"
       class="suiyu-video">
        </video>

        <?php if (!empty($atts['title'])): ?>
            <p class="suiyu-video-title">
                <?php echo esc_html($atts['title']); ?>
            </p>
        <?php endif; ?>
    </div>

    <script>
    document.addEventListener("DOMContentLoaded", function() {
        const videos = document.querySelectorAll(".suiyu-video");

        videos.forEach(video => {

            video.addEventListener("loadedmetadata", function() {

                const wrapper = video.closest(".suiyu-video-wrapper");

                const isPortrait = video.videoHeight > video.videoWidth;

                if (window.innerWidth > 1024) {
                    // 电脑端
                    if (isPortrait) {
                        wrapper.style.maxWidth = "450px";  // 竖屏变窄
                    } else {
                        wrapper.style.maxWidth = "800px";  // 横屏
                    }
                } else {
                    // 手机端
                    wrapper.style.maxWidth = "100%";
                }
            });

        });
    });
    </script>

    <style>
    .suiyu-video-wrapper{
        margin:20px auto;
        text-align:center;
    }

    .suiyu-video{
        width:100%;
        height:auto;
        border-radius:6px;
        display:block;
    }

    .suiyu-video-title{
        color:#666;
        font-size:14px;
        margin-top:8px;
    }
    </style>

    <?php
    return ob_get_clean();
}
add_shortcode('suiyu_video', 'suiyu_video_shortcode');
// ================================
// TinyMCE 插入视频按钮
// ================================

function suiyu_add_video_button() {
    add_filter('mce_external_plugins', 'suiyu_video_plugin');
    add_filter('mce_buttons', 'suiyu_register_video_button');
}
add_action('admin_init', 'suiyu_add_video_button');

function suiyu_video_plugin($plugin_array) {
    $plugin_array['suiyu_video_button'] = get_stylesheet_directory_uri() . '/js/suiyu-video-button.js';
    return $plugin_array;
}

function suiyu_register_video_button($buttons) {
    array_push($buttons, 'suiyu_video_button');
    return $buttons;
}
add_filter('wp_get_attachment_image_attributes', function ($attr) {
    $attr['loading'] = 'lazy';
    $attr['decoding'] = 'async';
    return $attr;
});
/**
 * GeneratePress Child主题 - 为经典编辑器添加音乐播放器按钮
 */

function add_music_button_to_generatepress() {
    // 确保是管理员在编辑文章
    if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages') ) {
        return;
    }
    
    // 检查是否在使用经典编辑器
    if ( 'true' == get_user_option('rich_editing') ) {
        // 为经典编辑器添加按钮
        add_filter( 'mce_buttons', 'register_music_button_gp' );
        add_filter( 'mce_external_plugins', 'load_music_button_script_gp' );
    }
}
add_action( 'admin_head', 'add_music_button_to_generatepress' );

/**
 * 注册经典编辑器的按钮
 */
function register_music_button_gp( $buttons ) {
    array_push( $buttons, 'music_player_gp' );
    return $buttons;
}

/**
 * 加载经典编辑器的JavaScript(使用子主题路径)
 */
function load_music_button_script_gp( $plugin_array ) {
    $plugin_array['music_player_gp'] = get_stylesheet_directory_uri() . '/js/classic-music-button.js';
    return $plugin_array;
}
/**
 * 生成音乐播放器HTML(图标+歌名一行,播放器一行)- 纯净版
 */
function generate_music_player_html_gp( $id, $src, $title, $cover = '' ) {
    $player_id = 'gp-music-' . $id;
    
    // 确保标题不为空
    $display_title = !empty($title) ? $title : '未知音乐';
    
    $html = '<div class="gp-music-wrapper" id="' . $player_id . '">';
    $html .= '<div class="gp-music-card">';
    
    // 第一行:图标 + 歌曲名称
    $html .= '<div class="gp-music-title-row">';
    $html .= '<span class="gp-music-icon-small">♪</span>';
    $html .= '<span class="gp-music-title">' . esc_html($display_title) . '</span>';
    $html .= '</div>';
    
    // 第二行:播放器(只有原生控件,没有自定义音量条)
    $html .= '<div class="gp-music-player-row">';
    $html .= '<div class="gp-music-player-container">';
    $html .= '<audio controls preload="metadata" class="gp-music-audio" controlsList="nodownload">';
    $html .= '<source src="' . esc_url($src) . '" type="audio/mpeg">';
    $html .= '您的浏览器不支持音频播放。';
    $html .= '</audio>';
    $html .= '</div>'; // 关闭player-container
    $html .= '</div>'; // 关闭player-row
    $html .= '</div>'; // 关闭music-card
    $html .= '</div>'; // 关闭wrapper
    
    return $html;
}
// ===== 在文件末尾添加这段代码 =====
/**
 * 注册短代码 - 告诉WordPress如何处理[music]短代码
 */
add_shortcode('music', 'music_player_shortcode_handler');

/**
 * 短代码处理函数
 */
function music_player_shortcode_handler($atts) {
    // 提取短代码属性
    $atts = shortcode_atts(array(
        'id' => '',
        'src' => '',
        'title' => '未知音乐',  // 默认值
        'cover' => ''
    ), $atts);
    
    // 检查是否有音频源
    if (empty($atts['src'])) {
        return '<!-- 音乐播放器错误:未指定音频源 -->';
    }
    
    // 调用生成播放器的函数
    return generate_music_player_html_gp($atts['id'], $atts['src'], $atts['title'], $atts['cover']);
}
/**
 * 为碎语添加规范链接,防止重复内容
 */
add_action('wp_head', 'add_suiyu_canonical_url', 1);
function add_suiyu_canonical_url() {
    global $wp;
    
    // 如果是碎语单页
    if (is_singular('micropost')) {
        echo '<link rel="canonical" href="' . esc_url(get_permalink()) . '" />' . "\n";
        return;
    }
    
    // 如果是碎语存档页(列表页)
    if (is_post_type_archive('micropost')) {
        $current_url = home_url(add_query_arg(array(), $wp->request));
        echo '<link rel="canonical" href="' . esc_url($current_url) . '" />' . "\n";
        
        // 分页添加 noindex
        if (is_paged()) {
            echo '<meta name="robots" content="noindex, follow" />' . "\n";
        }
        return;
    }
    
    // 如果是碎语标签页
    if (is_tax('micropost_tag')) {
        if (is_paged()) {
            echo '<meta name="robots" content="noindex, follow" />' . "\n";
        }
    }
}

[/reply]

标签: none

添加新评论