add_rewrite_rule works in functions.php but not in plugin
-
Hi folks,
I’m new to WordPress particularly the development side of it, which I’m trying to get to grips with. I cannot seem to resolve an issue with code that works in functions.php but fails to work in a site-specific plugin.The code in functions.php:
add_action('init', function () { add_rewrite_tag('%make_id%', '([0-9]+)'); add_rewrite_rule('api/v1/makes/([0-9]+)/?', 'index.php?make_id=$matches[1]', 'top'); }); // template redirect add_action('template_redirect', function () { global $wp_query; $make_id = $wp_query->get('make_id'); if (!empty($make_id)) { wp_send_json_success([ 'message' => 'hello world' ]); } });
The above works fine after I save changes in Permalink Settings and navigate to the url https://example.com/api/v1/makes/1/
However, when the same code is in the plugin I just get a 404 page.
Plugin code:
<?php /* * Plugin Name: First Plugin * Description: My first WordPress plugin that does nothing. * Version: 1.0.0 * Author: Malcolm Dixon * License: GPLv2 */ // Exit if accessed directly. if (!defined('ABSPATH')) exit; /* CLASS */ if (!class_exists('First_Plugin')) { class First_Plugin { const API_BASE_URL = 'api/v1/'; function __construct() { /* * activate, deactivate, uninstall hooks */ register_activation_hook(__FILE__, [$this, 'activate']); register_deactivation_hook(__FILE__, [$this, 'deactivate']); register_uninstall_hook(__FILE__, [$this, 'uninstall']); } /* METHODS */ /* * Activate the plugin */ function activate() { /* add rewrite tag and rule for custom endpoint */ add_action('init', function () { add_rewrite_tag('%make_id%', '([0-9]+)'); add_rewrite_rule('api/v1/makes/([0-9]+)/?', 'index.php?make_id=$matches[1]', 'top'); }); // template redirect add_action('template_redirect', function () { global $wp_query; $make_id = $wp_query->get('make_id'); if (!empty($make_id)) { wp_send_json_success([ 'message' => 'hello world' ]); } }); // Recreate rewrite rules flush_rewrite_rules(); } /* * Deactivate the plugin */ function deactivate() { //Nothing here yet } /* * Uninstall the plugin */ function uninstall() { // Nothing here yet } } /* MAIN */ function first_plugin() { global $fp; // Instantiate only once. if(!isset($fp)) { $fp = new First_Plugin(); } return $fp; } // Instantiate. first_plugin(); } ?>
I’m probably missing something obvious being new to PHP I wouldn’t be surprised if the code is not even being called.
Any advice appreciated.
Viewing 5 replies - 1 through 5 (of 5 total)
Viewing 5 replies - 1 through 5 (of 5 total)
- The topic ‘add_rewrite_rule works in functions.php but not in plugin’ is closed to new replies.