0

I want to create page where I can show all the category tree and on click on them show child tree of that category.

I have functionality working as short code where i am using query string to pass child slug, but I wan to use it as URL not as query string, I have tried many things like add_rewrite_rule() but it's not helping.

My Main page where i have added sort code is - https://sute.com/systems/

where I pass child as https://sute.com/systems/?machine=acer where machine is a query variable with value acer.

I want to have URL like https://sute.com/systems/machine/acer so it's more SEO friendly.

I tried to use rewrite rule but it only works for main page https://sute.com/systems/, when I click on child slug which goes to URL - https://sute.com/systems/machine/acer it show Page not found.

Query string is not SEO friendly so for search engine any page that uses query string all are same. My main page is system but using slug I want to create each child page URL so I can submit it on search engine.

Please any one have any idea how to accomplice that.

1
  • what changes with the argument "machine" ? maybe it will be more practical to create a custom post type for machines and then wordpress will manage these url. Commented Sep 3, 2024 at 13:10

1 Answer 1

0

To pass the extra variable in the page URL, try the following code:

Step 1: Use the following code to add a Custom Rewrite Rule.

function gs_page_rewrite_rules() {
    add_rewrite_rule(
        '^systems/machine/([^/]*)/?$',  // Custom URL structure
        'index.php?pagename=systems&m_var=$matches[1]',  // Query vars to pass
        'top'
    );
}
add_action('init', 'gs_page_rewrite_rules');

Step 2: Use the following code to register the extra variable with WordPress.

function gs_query_vars($vars) {
    $vars[] = 'm_var';  // Register custom query variable
    return $vars;
}
add_filter('query_vars', 'gs_query_vars');

Step 3: Visit Settings > Permalinks and click Save Changes

Step 4: Clear the Cache

Step 5: Open the https://sute.com/systems/machine/acer URL

**Note: Add the Step 1 and 2 code in the child theme's functions.php file

Use the get_query_var function to retrieve the custom variable in the template, like:

$m_var = get_query_var('m_var');

Optional: If the code given in steps 1 and 2 does not work. Add the additional code given below. After saving the following code, repeat the steps 3, 4 and 5, and remove the Additional code.

add_action('init', 'gs_flush_rewrite_rules');
function gs_flush_rewrite_rules() {
    gs_page_rewrite_rules();
    flush_rewrite_rules();  
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.