WordPress:不同自定义文章类型展示存档与单篇及permalink修正问题
解决方案
你的问题核心是:查询my-business类型的文章后,WordPress默认会使用该类型的规则生成标题链接,而你需要让未登录用户看到的是business类型的路径。以下是几种实用解决方法:
方法1:手动构建展示链接(模板内直接处理)
在archive-business.php的循环中,跳过默认的get_permalink(),手动拼接business类型的单页URL:
<?php $args = array( 'post_type' => 'my-business', // 其他查询参数(如状态、分类等) ); $business_query = new WP_Query($args); if ($business_query->have_posts()) : while ($business_query->have_posts()) : $business_query->the_post(); // 手动生成business类型的永久链接 $display_permalink = home_url('/business/' . $post->post_name . '/'); // 输出标题与自定义链接 echo '<h2><a href="' . esc_url($display_permalink) . '">' . get_the_title() . '</a></h2>'; // 输出文章摘要或其他内容 the_excerpt(); endwhile; wp_reset_postdata(); endif; ?>
方法2:修改查询结果的post_type(让默认函数自动适配)
在循环开始前,把查询到的my-business文章对象的post_type临时改为business,这样get_permalink()等函数会自动使用business的规则:
<?php $args = array( 'post_type' => 'my-business', // 其他查询参数 ); $business_query = new WP_Query($args); // 批量修改post_type if ($business_query->have_posts()) { foreach ($business_query->posts as &$post) { $post->post_type = 'business'; } unset($post); // 释放引用避免后续冲突 } // 正常循环输出 if ($business_query->have_posts()) : while ($business_query->have_posts()) : $business_query->the_post(); the_title('<h2><a href="' . esc_url(get_permalink()) . '">', '</a></h2>'); the_excerpt(); endwhile; wp_reset_postdata(); endif; ?>
方法3:全局过滤器适配(适合多场景复用)
如果需要在多个页面都实现该转换,可以在主题的functions.php中添加过滤器,自动将未登录用户看到的my-business链接替换为business路径:
add_filter('post_type_link', 'convert_my_business_to_public_url', 10, 2); function convert_my_business_to_public_url($link, $post) { // 仅对未登录用户、my-business类型的文章生效 if ('my-business' === $post->post_type && !is_user_logged_in()) { $link = str_replace('/my-business/', '/business/', $link); } return $link; }
注意事项
- 确保
business自定义文章类型的 rewrite 规则已正确配置,示例如下:
register_post_type('business', array( 'rewrite' => array('slug' => 'business'), // 其他参数(如标签、支持功能等) ));
- 修改规则后,需要到WordPress后台「设置」→「固定链接」页面,随便选择一个选项并保存,刷新 rewrite 规则。
内容的提问来源于stack exchange,提问作者Mike Hosier
相关产品推荐
相关产品推荐

