0

We have a client that wants to make all post under a certain post_type as draft or return a 404 display. If possible, I would like to do this programmatically instead of a plugin. Is this possible? I tried to search but most of the SO/WSE questions are fixes about error 404 to display the page.

for example:

domain.com/movies
domain.com/movies/movie1
domain.com/movies/movie2
domain.com/movies/movie3


domain.com/articles
domain.com/articles/article1
domain.com/articles/article2
domain.com/articles/article3

make all articles return as 404 when user access them.

Updated to the code to below:

function rr_404_custom_post_types()
{
  global $wp_query;
  if ($wp_query->query['post_type'] && !($wp_query->query['post_type'] == 'movies')) {
    $wp_query->set_404();
    status_header(404);
  } else if ($wp_query->query['pagename']) {
    $wp_query->set_404();
    status_header(404);
  }
}
add_action('wp', 'rr_404_custom_post_types');

The code above will return ALL pages except top page and /movies to 404. though my /login will redirect to /wp-login. I do not want that.

Still trying to fix this.

Note

I know that I can bulk edit the posts from published to draft but there are a lot of pages/post_type that needs to be changed to draft and return a 404. That is why I would like to do this programmatically.

6
  • 1
    When registering the post type, make sure to set 'public' => false if you don't want them to be accessible on the front end. Jul 24, 2023 at 7:40
  • If you've access to WP CLI, you can use the command: wp post list --field=ID --post_type=CPT_NAME --posts_per_page=500 --post_status=publish | xargs wp post update --post_status=draft Ref: gist.github.com/lukecav/888537e8d2e1ddbdc71ef70ba4cc5832
    – Kumar
    Jul 24, 2023 at 7:41
  • @JacobPeattie posts are already registered. Jul 24, 2023 at 7:55
  • @Kumar. thanks. will try this later. Jul 24, 2023 at 7:59
  • @Mr.Kenneth No, when registering the post type. Are you not using register_post_type() somewhere? Jul 24, 2023 at 8:00

1 Answer 1

0

Not tested, but if I have inderstood the question correctly, please try the below solution. Articles post type will return a 404 but posts under movies categories will not.

Code goes in a functions.php of your child theme.

function rr_404_custom_post_types()
        {
          global $wp_query;
          if (is_single() && !($wp_query->post->post_type == 'movies')) {
            $wp_query->set_404();
            status_header(404);
          }
        }
        add_action('template_redirect', 'rr_404_custom_post_types');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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