• Resolved malcolmdixon

    (@malcolmdixon)


    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)
  • In the functions.php code, you put the rewrite code to run on every init action.
    But in the plugin, you put the init action only when the plugin is activated (clicking on Activate link), so it doesn’t run every time like the other one does.

    Thread Starter malcolmdixon

    (@malcolmdixon)

    Hi Joy,

    Thanks for the reply.

    I was just coming on the forum to make an update to that effect as I realised that after more research.

    TBH I just don’t know how WordPress works yet!

    I now know that the routing code is firing but $make_id has no value hence why I’m not getting any response. I don’t even know how to debug PHP running in my Docker container, so I just used update_option to put values in the database lol. I think I need X-Debug or something like that.

    So, the question is, if it’s routing why isn’t there a value in $make_id?

    EDIT: Rather than hide my embarrassment I will leave the above, but the reason it wasn’t working after I ensured my new init() function was called on instantiation rather than just activation was I was calling the incorrect URL! Forgot my base url of /api/v1, my Homer moment.

    So, it now works but the one puzzling thing is that I still had to manually Save Changes in Permalink settings. I thought the flush_rewrite_rules() during activation took care of that?

    Everything is easy when you know how but hard when you don’t.

    • This reply was modified 3 years, 9 months ago by malcolmdixon. Reason: Being a numb head

    Here is a list of some of the actions during a page request: https://codex.www.ads-software.com/Plugin_API/Action_Reference

    You can enable DEBUG logging https://www.ads-software.com/support/article/editing-wp-config-php/#wp_debug
    and use the error_log function like this to write to the log from your plugin:
    error_log( $x . "\n", 3, dirname(__FILE__). '/../../debug.log');

    Maybe reread about add_rewrite_rule and add_rewrite_tag.
    https://developer.www.ads-software.com/reference/functions/add_rewrite_rule/
    https://developer.www.ads-software.com/reference/functions/add_rewrite_tag/

    • This reply was modified 3 years, 9 months ago by Joy. Reason: forgot a link
    • This reply was modified 3 years, 9 months ago by Joy. Reason: embed gets rid of fragment ID
    Thread Starter malcolmdixon

    (@malcolmdixon)

    Thanks for the actions during a page request link, seen that page on a video recently and thought I need to see that. Been on the other pages loads but thanks anyway. Got it working and your reply confirmed where I was going wrong so I appreciate your time spent.

    I’ll check out the DEBUG logging feature too.

    Thread Starter malcolmdixon

    (@malcolmdixon)

    Resolved

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.