add_rewrite_tag()

最后更新于:2021-11-25 19:30:02

add_rewrite_tag( string$tag, string$regex, string$query=”)

Add a new rewrite tag (like %postname%).

参数

$tag

(string) (Required) Name of the new rewrite tag.

$regex

(string) (Required) Regular expression to substitute the tag for in rewrite rules.

$query

(string) (Optional) String to append to the rewritten query. Must end in ‘=’.

Default value: ”

源文件

文件: gc-includes/rewrite.php

function add_rewrite_tag( $tag, $regex, $query = '' ) {
	// Validate the tag's name.
	if ( strlen( $tag ) < 3 || '%' !== $tag[0] || '%' !== $tag[ strlen( $tag ) - 1 ] ) {
		return;
	}

	global $gc_rewrite, $gc;

	if ( empty( $query ) ) {
		$qv = trim( $tag, '%' );
		$gc->add_query_var( $qv );
		$query = $qv . '=';
	}

	$gc_rewrite->add_rewrite_tag( $tag, $regex, $query );
}
// Assign value to %location% rewrite tag
add_filter('post_link', 'my_filter_post_link', 10, 2 );
function my_filter_post_link( $permalink, $post ) {

    // bail if %location% tag is not present in the url:
    if ( false === strpos( $permalink, '%location%'))
        return $permalink;

    $terms = gc_get_post_terms( $post->ID, 'location');
    // set location, if no location is found, provide a default value.
    if ( 0 < count( $terms ))
        $location = $terms[0]->slug;
    else
        $location = 'timbuktu';
    $location = urlencode( $location );
    $permalink = str_replace('%location%', $location , $permalink );
 
    return $permalink;
}