Using WordPress ‘add_permastruct()’ PHP function

The add_permastruct() WordPress PHP function adds a new permalink structure to your WordPress site.

Usage

Let’s say we want to add a new permalink structure for a custom post type ‘book’. Here is how you would do it:

add_permastruct('book', '/book/%book%');

In this example, ‘/book/%book%’ is the new permalink structure, where ‘%book%’ is the placeholder for the book name.

Parameters

  • $name (string) (Required): This is the name for the permalink structure.
  • $struct (string) (Required): This is the actual permalink structure.
  • $args (array) (Optional): This array includes arguments for building the rules from the permalink structure. Here are the options you can pass in the $args array:
    • with_front (bool): If true, the structure will be prepended with WP_Rewrite::$front. Default is true.
    • ep_mask (int): The endpoint mask defining which endpoints are added to the structure. Default is EP_NONE.
    • paged (bool): If true, archive pagination rules will be added for the structure. Default is true.
    • feed (bool): If true, feed rewrite rules will be added for the structure. Default is true.
    • forcomments (bool): If true, the feed rules will query for a comments feed. Default is false.
    • walk_dirs (bool): If true, the directories making up the structure will be walked over and rewrite rules built for each. Default is true.
    • endpoints (bool): If true, endpoints will be applied to the generated rules. Default is true.

More information

See WordPress Developer Resources: add_permastruct()

Examples

global $wp_rewrite;
$args = array(
 'with_front' => true,
 'ep_mask' => 3,
 'paged' => 1,
 'feed' => 1,
 'forcomments' => 0,
 'walk_dirs' => 1,
 'endpoints' => 1
);
add_permastruct('locations', 'test/%message/', $args);

This changes the permalink structure from ‘/locations/%k7_locations%’ to ‘/test/%message%’.

add_action('init', 'wpdocs_custom_permalink');
function wpdocs_custom_permalinks() {
 add_permastruct('legal', 'legal/%my_slug%', ['ep_mask' => EP_PERMALINK]);
 add_rewrite_tag('%my_slug%', '([^/]+)', "post_type=page&name=");
}

This adds a custom permalink structure ‘/legal/%my_slug%’ where ‘%my_slug%’ is a placeholder for the actual slug.

Adding a Permalink Structure for a Custom Post Type

add_permastruct('book', '/book/%book%');

This adds a new permalink structure for a custom post type ‘book’. The ‘%book%’ is the placeholder for the book name.

$args = array(
 'paged' => true,
 'endpoints' => true
);
add_permastruct('news', '/news/%post_id%/', $args);

This adds a new permalink structure ‘/news/%post_id%/’ with pagination enabled.