0

Lets say I have a archive page with pagination where I use wp_pagenavi for pagination under the URL example.com/articles/news. When the pagination is used, the URL changes to example.com/articles/news/page/2, .../page/3, and so on.

Lets also say I have a custom post type with the slug newsposttype where I have a rewrite rule like this: 'rewrite' => array('slug => 'articles/news'). This is done to produce urls where views will be shown under e.g. articles/news/my-amazing-news-story, instead of newsposttype/my-amazing-news-story.

However, now the rewrite interferes with the pagination. Any URL example.com/articles/news/page/2, .../page/3, .../page/4, and so on, will display a 404 until I remove the rewrite from the custom post type.

One solution is to change either the archive URL or the rewrite on the custom post type. But, since the site has been in production for a fair amout of time, the URLs are indexed by Google. Is there a way to tell the rewrite rule not to apply when the url starts with example.com/articles/news/page/, or any way to work around this issue without changing the URLs?

I've seen the WordPress can add a suffix to differentiate the URLs, here and here, but I don't know if that is what I want. Ideally, I could tell the rewrite not to do anything if the URL has the post bit in it.

0

I solved it. To enable the new rule, save the parmalink structure. Ive tried to follow the example with news from above.

function news_page_rewrite_rule() {
  // Get the URL of the page listing out the news.
  // Here I use the Advanced Custom Fields plugin.
  $news_page_url = get_field('_news_page', 'options');

  if (empty($news_page_url))
    return;

  // Get the id of the page
  $page_id = url_to_postid($news_page_url);

  // Parse the URL and get the URL parts back
  $news_page_url_parts = wp_parse_url($news_page_url);

  // Add the rewrite rule. I remove the starting /. Doesn't work without it.
  add_rewrite_rule('^' . ltrim($news_page_url_parts['path'], '/') . 'page/([0-9]+)/?', 'index.php?paged=$matches[1]&page_id=' . $page_id, 'top');
}
add_action('init', 'news_page_rewrite_rule');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.