php - 分页不适用于帖子名称固定链接,但适用于普通固定链接
问题描述
我正在尝试遍历名为 blog 的帖子类型。当 Wordpress 永久链接设置为纯文本时,分页工作正常,但是当我将其更改为发布名称并单击继续分页链接时,它会加载 404 错误。
我发现您不能拥有相同的帖子类型和页面名称,因为它会导致 404 错误。我想知道是否有解决方法,因为更改帖子类型的名称会影响博客帖子。
我的页面-blog.php
<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$loop = new WP_Query( array( 'post_type' => 'blog',
'posts_per_page' => 2,
'paged' => $paged,
'has_archive' => false,
'rewrite' => array(
'slug' => '/blog', // if you need slug
'with_front' => false,
),)
);
if ( $loop->have_posts() ):
while ( $loop->have_posts() ) : $loop->the_post();
// Set variables
$title = get_the_title();
$post_date = get_the_date('M j');
$amount_of_time_to_read = get_field('amount_of_time_to_read');
?>
<a href="<?php the_permalink(); ?>" class="post-blog-link">
<div class="post">
<?php $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID), 'thumbnail' ); ?>
<div class="post-image-v2" style="background-image:url('<?php echo $url ?>');">
</div>
<div class="post-content-v2">
<h2 class="post-title"><?php echo $title; ?></h2>
<div class="post-excerpt">
<p><?php echo get_excerpt(); ?></p>
</div>
<p class="post-date"> <span class="caps"><?php echo $post_date; ?></span> | <?php echo $amount_of_time_to_read; ?>min read</p>
</div>
</div>
</a>
<!--
-->
<?php endwhile; ?>
<center>
<div class="pagination mt-25">
<?php pagination_bar( $loop ); ?>
</div>
</center>
<?php wp_reset_postdata();
endif;
?>
我的functions.php
add_action('init', 'custom_rewrite_basic');
function custom_rewrite_basic() {
global $wp_post_types;
foreach ($wp_post_types as $wp_post_type) {
if ($wp_post_type->_builtin) continue;
if (!$wp_post_type->has_archive && isset($wp_post_type->rewrite) && isset($wp_post_type->rewrite['with_front']) && !$wp_post_type->rewrite['with_front']) {
$slug = (isset($wp_post_type->rewrite['slug']) ? $wp_post_type->rewrite['slug'] : $wp_post_type->name);
$page = get_page_by_slug($slug);
if ($page) add_rewrite_rule('^' .$slug .'/page/([0-9]+)/?', 'index.php?page_id=' .$page->ID .'&paged=$matches[1]', 'top');
}
}
}
function get_page_by_slug($page_slug, $output = OBJECT, $post_type = 'page' ) {
global $wpdb;
$page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s AND post_status = 'publish'", $page_slug, $post_type ) );
return ($page ? get_post($page, $output) : NULL);
}
解决方案
必须将此添加到我的functions.php
add_rewrite_rule('^blog/page/([0-9]+)','index.php?pagename=blog&paged=$matches[1]', 'top');
推荐阅读
- echarts - 使用 ngx-echarts 从平行坐标图中获取选定值
- css - 基于背景图片flexbox动态改变高度
- python - 网页抓取动态页面 - 调整代码
- azure-data-factory - 'int' 是原语,不支持嵌套属性:Azure 数据工厂 v2
- sockets - poll返回POLLIN时可以读取多少数据
- c# - 在 VSIX Visual Studio 可扩展性中,如何获取函数的参数是“ref”、“out”还是值类型
- javascript - 如何在没有引导程序的情况下使用客户端接收到的 JSON 表数据对表数据进行分页?
- python - 使用 Docker 容器中的 Flask send_from_directory 返回一个空的 tar.gz 文件
- mysql - 如何使用mysql找出每个用户的每笔交易的时差(当天)
- javascript - 如何让 React Router 仅在导航到时呈现