add_permastruct()WP 3.0.0

Add permalink structure.

No Hooks.

Return

null. Nothing (null).

Usage

add_permastruct( $name, $struct, $args );
$name(string) (required)
Name for permalink structure.
$struct(string) (required)
Permalink structure.
$args(array)
Arguments for building the rules from the permalink structure, see WP_Rewrite::add_permastruct() for full details.
Default: empty array

Examples

0

#1 Friendly URL structure for book custom post type

Let's say when registering a post type with register_post_type() we specified parameter rewrite=false. And now we want to manually set Friendly URL for this post type, then we may use this code.

add_action( 'init', 'book_post_type_permastruct' );

function book_post_type_permastruct(){
	$post_type = 'book';

	$permastruct = "$post_type/%book%"; // Friendly URL structure

	$args = [
		'with_front'  => true,
		'paged'       => true,
		'ep_mask'     => EP_NONE,
		'feed'        => false,
		'forcomments' => false,
		'walk_dirs'   => false,
		'endpoints'   => false,
	];

	add_permastruct( $post_type, $permastruct, $args );

	// Add a rewrite tag so that add_permastruct() understands it.
	// It will then be replaced by the part of the regular 
	// expression string specified in the second parameter.
	add_rewrite_tag( "%book%", '([^/]+)', "post_type=$post_type&name=" );
}

The third parameter in add_permastruct() can be omitted, then the arguments will be default.

After installing the code, you need to reset the Friendly URL rules, for this you just need to go to Settings > Permalinks in the admin panel. Or run function flush_rewrite_rules():

// flush rewrite rules, if your permalink changed (e.g. on plugin activation):
flush_rewrite_rules();

Notes

Changelog

Since 3.0.0 Introduced.

add_permastruct() code WP 6.4.3

function add_permastruct( $name, $struct, $args = array() ) {
	global $wp_rewrite;

	// Back-compat for the old parameters: $with_front and $ep_mask.
	if ( ! is_array( $args ) ) {
		$args = array( 'with_front' => $args );
	}

	if ( func_num_args() === 4 ) {
		$args['ep_mask'] = func_get_arg( 3 );
	}

	$wp_rewrite->add_permastruct( $name, $struct, $args );
}