如何修改代码实现WordPress posts标签页仅拉取自定义文章类型properties
要实现仅拉取自定义文章类型properties的内容,提供两种可行方案,推荐第一种无需修改模板的方案,避免后续插件更新覆盖自定义代码:
方案一:使用
pre_get_posts钩子过滤查询(推荐) 无需修改插件自带的模板文件,将以下代码添加到你当前使用主题的functions.php文件中即可生效:
add_action( 'pre_get_posts', 'custom_uwp_profile_posts_filter' ); function custom_uwp_profile_posts_filter( $query ) { // 仅对前台UsersWP个人资料页的文章查询生效,避免影响其他页面查询逻辑 if ( ! is_admin() && function_exists( 'uwp_is_profile_page' ) && uwp_is_profile_page() && $query->get( 'post_type' ) === 'post' ) { $query->set( 'post_type', 'properties' ); } }
方案二:直接修改
loop-post.php模板 如果你需要直接修改模板文件,修改后的loop-post.php完整代码如下,posts-post.php无需做任何调整,现有代码已经兼容自定义文章类型展示:
<?php if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } $the_query = isset( $args['template_args']['the_query'] ) ? $args['template_args']['the_query'] : ''; $title = isset( $args['template_args']['title'] ) ? $args['template_args']['title'] : ''; // 新增代码段:修改查询仅返回properties自定义文章类型 if ( $the_query && is_a( $the_query, 'WP_Query' ) ) { $query_args = $the_query->query_vars; $query_args['post_type'] = 'properties'; $the_query = new WP_Query( $query_args ); } ?> <h3><?php echo $title; ?></h3> <div class="uwp-profile-item-block"> <?php // The Loop if ($the_query && $the_query->have_posts()) { echo '<ul class="uwp-profile-item-ul">'; while ($the_query->have_posts()) { $the_query->the_post(); uwp_get_template('posts-post.php', $args); } echo '</ul>'; /* Restore original Post Data */ wp_reset_postdata(); } else { // no posts found echo "<p>".sprintf( __( "No %s found.", 'userswp' ), $title )."</p>"; } do_action('uwp_profile_pagination', $the_query->max_num_pages); ?> </div>
注意:使用方案二时,建议将修改后的
loop-post.php文件复制到当前主题的userswp子目录下,避免后续插件更新时覆盖你修改的内容。
内容的提问来源于stack exchange,提问作者qazidev
相关产品推荐
相关产品推荐

