phpwordpressurl-rewriting

Wordpress build function around query


I need some help with Wordpress rewrite rule and the query. What I want is if the user visit this link https:www.domain.com/catalog

What I do first is making a rewrite rule so the user do not see a 404 error

add_rewrite_rule(
    '^catalog$', 
    'index.php?expage=$matches[0]', 
    'top'
);

add variable "expage" to the query

add_filter('query_vars', function($vars){
    $vars[] = 'expage';     
    return $vars;       
}, 10, 1);

Create a function that returns true or false

function is_catalog(){
    if(get_query_var('expage') == 'catalog'){
        return true;
    }
}

Create function and use this where you want

if(is_catalog()){
    //do something
}

The rewrite does work and I see no 404 error. But the function "is_catalog" does not work.

Is there somebody who can help me a little with this?


Solution

  • You need to set up the rewrite rule to capture the string 'catalog', and then use $matches[1].

    add_action ('init', function() {
        add_rewrite_rule(
            '^(catalog)$', 
            'index.php?expage=$matches[1]', 
            'top'
        );    
    });
    

    Don't forget to flush the permalinks after making this change.