0

Hi guys hope you can help.

So I have a WP site and an external JSON enpoint (NOT from another WP) and what I want to achieve is to create dynamic "fake" URLs inside wordpress like: example.com/product/{{product_slug}} and upon entering this URL I want to fetch my JSON endpoint with that very slug, something like: externalsite.com/api/v1/product/{{product_slug}} inside a template for example single-product.php

I managed to achieve something like this with add_filter('template_inclide') and watching the url but this is so hackish.

I also found out that maybe I should use the add_rewrite_rule() but did not find out how to use it without redirect.

NOTE: I don't want to create custom post types.

If you need any other info on what I am triing to achieve please ask. I don't want you to write the code for me but to put me in the right direction. Thanks in advance.

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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