0

For many years I have used to following technique to add a /news prefix to my posts URL. I have the following code in the functions.php of a custom plugin:

function my_change_post_object() {
  global $wp_post_types;
  $post = &$wp_post_types['post'];
  $post->has_archive = 'news';
  $post->rewrite = array(
    'slug' => 'news',
    'with_front' => FALSE,
  );
}

add_action( 'init', 'my_change_post_object' );

The above basically allows you to trigger the archive.php template when you browse to /news on the website.

However, since I recently upgraded to 4.9 this functionality has stopped working correctly. I can still browse to the /news URL and view the archive.php template, however, when I log into the Admin, then under the Posts section I can no longer view the Posts. I can only view/modify the Categories and Tags. Also, the Comments section doesn't have any sub-menus anymore either.

It seems that my code is now causing some security/permissions issue within WordPress itself where I have no longer certain permissions (I'm logged in with the Administrator role).

When I disable the code then the Admin works fine but browsing to /news results in a 404. However, browsing directly to a post page works.

I have tried to remove the above code and simply having my permalink structure set to a custom URL, /news/%postname%/, but that results in a 404 when browsing to /news.

How can I trigger the archive.php template when browsing to the /news URL?

2

Here is my solution without changing the post object:

Add a new rewrite rule, look this up if you need to:

add_rewrite_rule("^news/?$", "index.php?post_type=post&category_name=news", "top");

Adding category_name=news triggers the archive.php file to be used. Yes, you need to add the category news to every post but this is no big deal if you set news to the default category in writing settings.

Change post archive link:

function my_post_archive_link( $link, $post_type ) {
    if ( $post_type == 'post' ) {
        $link = site_url( '/news/' );
    }

    return $link;
}
add_filter( 'post_type_archive_link', 'my_post_archive_link', 10, 2 );

This is the best solution I have come up with- without having to hack the post object or create a new custom post type just for news.

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.