Creating custom URLs with template to fetch external JSON

Turns out it was just really Friday for me.

Thanks to @eddiemoya and @matt-keys for their answers on this question.

Their answer helped me a lot. After their explanation I revisited the WordPress documentation and it really wasn’t that hard to comprehend.

The solution I user for my specific question was as follows:

  1. I created a page inside WP. I named it Products (slug: example.com/products)
  2. Created a template in my themes root directory and set a template name for it

    /** 
     * Template Name: My single product page
     */
    
  3. Selected “My single product page” from the Template dropdown inside my Products page admin interface

  4. Copied the page ID (1234)
  5. In the functions.php I wrote the following code:

    funtion product_api_rewrite_tag() {
        add_rewrite_tag('%product_slug%', '([^&]+)');
    }
    
    function product_api_rewrite_rule() {
        add_rewrite_rule('^products/([^/]*)/?','index.php??page_id=1234&product_slug=$matches[1]','top');
    }
    
    add_action('init', 'product_api_rewrite_tag', 10, 0);
    add_action('init', 'product_api_rewrite_rule', 10, 0);
    
  6. Inside “My single product page” I can do something like this:

    global $wp_query;
    $pension_slug = $wp_query->query_vars['pension_slug'];
    
    echo $pension_slug;
    
  7. Upon visitig example.com/products/my_new_product the template will return my_new_product.