How to change page response code (e.g. 404, 301) in custom plugin
-
Hi, I’m trying to develop a custom plugin along with a custom shortcode. The goal is to generate dynamic content based on a query parameter in the page URL.
For example: https://www.example.com/product?id=12345
My shortcode function would decode the $_GET[‘id’] parameter and output something related. I can do that in my plugin like this:
function scode_func() { if (isset($_GET['id'])) { ... } return $output; } add_action( 'init', function() { add_shortcode( 'test', 'scode_func'); });
So the code above does work as I need. Now, I’m trying to figure out how to have this function return an error in the form of a response code like 301 or 404 if ‘id’ is invalid or missing. However, I can’t seem to figure out how to change the response code as the headers have already been written by the time this function fires. For example:
if (!isset($_GET['id']) { header('HTTP/1.1 404 Not Found'); return; }
returns an error that the headers have already been written. I’ve also tried $wp_query->set_404() and also status_header(404, ‘Not found’), but nothing seems to work. Thanks for any suggestions!
- The topic ‘How to change page response code (e.g. 404, 301) in custom plugin’ is closed to new replies.