
为 WordPress 文章内容页添加展开收缩功能通常可以通过 JavaScript 或 jQuery 来实现。有时候,我们希望在 WordPress 文章内容页中的一些长篇文字或内容中添加展开收缩功能,以提升页面的可读性。
下面是添加展开收缩功能的步骤和示例代码:
1. 创建一个 WordPress 文章模板(Template):
在你的主题文件夹中创建一个自定义的文章模板(例如 template-custom.php),用于替代默认的文章模板。
<?php/*
Template Name: Custom Article Template
*/get_header(); ?><div id="primary" class="content-area">
<main id="main" class="site-main">
<?php
// The WordPress Loop
while (have_posts()) : the_post(); get_template_part('template-parts/content', 'single');
endwhile;
?>
</main>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>2. 修改文章内容模板(content-single.php):
在主题文件夹的 template-parts 目录下找到 content-single.php 文件,添加一个可折叠的 div 包装文章内容。
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php the_title('<h1 class="entry-title">', '</h1>'); ?>
</header>
<div class="entry-content">
<div class="expandable-content">
<?php the_content(); ?>
</div>
<button class="toggle-expand">展开/收缩</button>
</div>
<?php if (get_edit_post_link()) : ?>
<footer class="entry-footer">
<?php
edit_post_link( sprintf(
/* translators: %s: Name of current post */
esc_html__('Edit %s', 'your-theme'),
the_title('<span class="screen-reader-text">"', '"</span>', false)
),
'<span class="edit-link">',
'</span>'
);
?>
</footer>
<?php endif; ?>
</article>3. 添加 JavaScript 或 jQuery 代码:
在主题的 functions.php 文件中添加以下代码,用于加载和执行 JavaScript 文件。
function enqueue_custom_scripts() { if (is_singular() && is_main_query()) {
wp_enqueue_script('custom-scripts',
get_template_directory_uri() . '/js/custom-scripts.js', array('jquery'), null, true);
}
}add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');在主题目录下创建一个名为 custom-scripts.js 的 JavaScript 文件,并添加以下代码:
jQuery(document).ready(function ($) { // 初始状态隐藏内容
$('.expandable-content').hide(); // 切换展开/收缩
$('.toggle-expand').on('click', function () {
$('.expandable-content').slideToggle();
});
});4. 样式调整:
可以在主题的样式文件中添加一些 CSS 样式,以确保展开和收缩按钮的样式符合你的主题风格。
/* 在主题的样式文件中添加以下 CSS 样式 */.expandable-content { margin-bottom: 20px;
}.toggle-expand { background-color: #0073e5; color: #fff; padding: 5px 10px; cursor: pointer; border: none;
}5. 应用自定义文章模板:
在 WordPress 后台编辑文章时,可以选择应用刚才创建的自定义文章模板。在编辑文章页面的右侧找到“模板”选项,并选择你的自定义模板。
注意事项:
1. 请备份你的主题文件和数据库,以防在修改中出现问题。
2. 上述代码和步骤是一个基本示例,具体的样式和交互效果可以根据你的需求进行调整。
3. 请根据你的主题结构和样式进行适度的修改。
4. 为确保功能正常,建议在本地测试或开发环境中进行修改,并在生产环境之前仔细测试。
以上步骤提供了一个基本的展开收缩功能的实现方式,你可以根据实际需求和设计风格进行进一步的定制和优化。




还没有评论,来说两句吧...