• Hi,

    I’m using add_rewrite_rule() function to redirect user to a particular URL.

    Following is the function that I’m using:

    function my_custom_rewrite() {
    	add_rewrite_rule(
    		'^my-custom/([^/]*)/?',
    		'index.php?taxonomy=vehicles&mk=$matches[1]',
    		'top'
    	);
    }
    add_action( 'init', 'my_custom_rewrite' );

    With this code, when someone visits https://example.com/my-custom/ford/ it loads the page and content properly.

    I tried to modify this function in such a way that user can still access same page using https://example.com/my-custom-ford/

    I’ve used following function for that:

    function my_custom_rewrite() {
    	add_rewrite_rule(
    		'^my-custom-([^/]*)/?',
    		'index.php?taxonomy=vehicles&mk=$matches[1]',
    		'top'
    	);
    }
    add_action( 'init', 'my_custom_rewrite' );

    Unfortunately, this function returns a 404 error.

    Any suggestion or feedback how to achieve https://example.com/my-custom-ford/ working would be great.

    TIA

Viewing 3 replies - 1 through 3 (of 3 total)
  • In most cases whenever trying to store a variable in a rewrite rule such as

    mk=$maches[1]

    You need to create a cooresponding query var for WordPress to throw it into:

    /**
     * Custom Query Vars
     * 
     * @param Array $query_vars
     * 
     * @return Array $query_vars
     */
    function wpf11654317_query_vars( $query_vars ) {
    	
    	// Ensure that this query var is unique and not used anywhere else in core, themes, or plugins.
    	return array_merge( $query_vars, array(
    		'mk',
    	) );
    	
    }
    add_filter( 'query_vars', 'wpf11654317_query_vars' );

    Save your permalinks and you should have access to this query_var in the normal methods:

    global $wp_query;
    $foo = $wp_query->get( 'mk' ); // Ford

    use this code in functions.php and successfully redirect your page

    
    function redirect_to_another_page() {
      if(is_page('ford')) {
        wp_redirect(home_url().'/my-custom-ford');
        exit();
      }
    }
    add_action('template_redirect', 'redirect_to_another_page');
    
    
    Moderator Jan Dembowski

    (@jdembowski)

    Forum Moderator and Brute Squad

    @anilankola Why did you report this topic? The “Report this topic” link is reserved for spam, abuse or something broke. That’s not the case here.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Custom URL Rewrite’ is closed to new replies.