要在WordPress的自定义帖子类型循环之前和之后插入HTML代码,可以通过以下几种方法实现:
pre_get_posts
钩子pre_get_posts
钩子允许你在查询执行之前修改主查询。你可以使用这个钩子来检查当前查询是否是你想要修改的自定义帖子类型,并相应地插入HTML代码。
function insert_custom_html_before_after_loop( $query ) {
// 只在前端和主WordPress查询中运行此调整
if ( ! is_admin() && $query->is_main_query() ) {
// 检查当前查询是否是自定义帖子类型
if ( is_post_type_archive( 'your_custom_post_type' ) || is_singular( 'your_custom_post_type' ) ) {
// 在循环之前插入HTML
echo '<div class="before-loop">这是循环之前的内容</div>';
// 在循环之后插入HTML
add_action( 'loop_end', function() {
echo '<div class="after-loop">这是循环之后的内容</div>';
});
}
}
}
add_action( 'pre_get_posts', 'insert_custom_html_before_after_loop' );
the_post
和 rewind_posts
钩子另一种方法是在每个帖子循环开始之前和结束之后插入HTML代码。这可以通过 the_post
和 rewind_posts
钩子来实现。
function insert_html_before_after_each_post() {
// 检查是否在自定义帖子类型的循环中
if ( is_singular( 'your_custom_post_type' ) || is_post_type_archive( 'your_custom_post_type' ) ) {
// 在每个帖子之前插入HTML
add_action( 'the_post', function() {
echo '<div class="before-post">这是每个帖子之前的内容</div>';
});
// 在每个帖子之后插入HTML
add_action( 'rewind_posts', function() {
echo '<div class="after-post">这是每个帖子之后的内容</div>';
});
}
}
add_action( 'pre_get_posts', 'insert_html_before_after_each_post' );
如果你更喜欢直接编辑模板文件,可以在自定义帖子类型的归档模板(如 archive-your_custom_post_type.php
)或单帖子模板(如 single-your_custom_post_type.php
)中直接插入HTML代码。
// 在 archive-your_custom_post_type.php 或 single-your_custom_post_type.php 文件中
<div class="before-loop">这是循环之前的内容</div>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<!-- 帖子内容 -->
<?php endwhile; ?>
<div class="after-loop">这是循环之后的内容</div>
<?php endif; ?>
通过上述方法,你可以有效地在自定义帖子类型的循环之前和之后插入所需的HTML代码。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云