Function and usage of add_rewrite_rule() in wordpress

Question

Answers ( 1 )

    0
    2024-01-05T12:31:37+00:00

    The add_rewrite_rule() function in WordPress is a powerful tool for developers to create custom URL structures. It adds a new rewrite rule to WordPress's array of rewrite rules, which is used to process pretty permalinks or clean URLs.

    Function:

    add_rewrite_rule( string $regex, string|array $query, string $after = 'bottom' )
    

    Description:

    This function enables you to add a custom rewrite rule that will transform a specific URL structure into a set of query variables. It's primarily used for custom post types, taxonomies, or any custom page structures you might need.

    Parameters:

    1. $regex (string, required): This is the regular expression that the function will use to match the incoming URL. It should be crafted to match the specific structure of the URL that you are trying to rewrite.

    2. $query (string|array, required): This parameter specifies the corresponding query variables for the rewrite rule. It can be a query string or an associative array. This is what WordPress will use to interpret and direct the request internally.

    3. $after (string, optional): This parameter determines the priority of the new rule in the list of all rewrite rules. It accepts either 'top' or 'bottom' as values. If set to 'top', the rule is placed at the top of the rewrite rules, giving it higher priority. If set to 'bottom' (which is the default), the rule is placed at the end of the list.

    Default:

    • $after: 'bottom'

    Sample Usage:

    Let's say you want to add a custom URL structure for a special kind of product in your e-commerce site:

    function custom_rewrite_rule() {
        add_rewrite_rule(
            '^products/([a-z]+)/?',  // Regular expression to match the product URL
            'index.php?product_type=$matches[1]',  // Map to internal query var
            'top'  // Priority
        );
    }
    add_action('init', 'custom_rewrite_rule');
    

    In this example, a URL like http://yourwebsite.com/products/electronics will be internally mapped to http://yourwebsite.com/index.php?product_type=electronics. The rule is added at the top of the rewrite rules, giving it a higher priority over existing rules.

    This function is essential for creating SEO-friendly and user-friendly URLs in WordPress, especially for custom content types and structures.

Leave an answer