InsideDarkWeb.com

Add a permalink variable onto custom post type URL after post name slug

I have a custom post type mycpt and I’m trying to allow for a variable to be appended onto the end of the URL right after the post name slug, like this:

www.site.com/mycpt/the-name-of-my-post/var-value-here/

I’ve been searching around, and the only examples I can find don’t use the post name/slug in the URL, but rather taxonomies, so I’m not sure what the correct way to do it is. Here is what I’m trying now, but it’s treating the URL with the variable as a separate page type (it’s loading a default template rather than the template my custom post type uses).

add_action( 'init', function() {
    add_rewrite_tag( '%my_var%', '([^/]*)' );
    add_rewrite_rule( '^mycpt/(.*)/([^/]*)/?', 'index.php?post_type=mycpt&my_var=$matches[1]', 'top' );
}, 10, 0 );

I also tried changing $matches[1] to $matches[2] since I thought maybe the wildcard for the post name/slug was the first match, but that didn’t work either.

Can anybody see what I’m doing wrong here?

WordPress Development Asked on November 21, 2021

2 Answers

2 Answers

Here's a complete working example that adds a post type, with extra rule to capture an additional parameter:

function wpd_post_type_and_rule() {
    register_post_type( 'mycpt',
        array(
            'labels' => array(
                'name' => __( 'mycpt' ),
            ),
            'public' => true,
            'rewrite' => array( 'slug' => 'mycpt' ),
        )
    );
    add_rewrite_tag( '%mycpt_var%', '([^/]*)' );
    add_rewrite_rule(
        '^mycpt/([^/]*)/([^/]*)/?$',
        'index.php?mycpt=$matches[1]&mycpt_var=$matches[2]',
        'top'
    );
}
add_action( 'init', 'wpd_post_type_and_rule' );

After adding this and flushing rewrite rules, you'll have both

www.site.com/mycpt/the-name-of-my-post/

and

www.site.com/mycpt/the-name-of-my-post/var-value-here/

You can get the value of mycpt_var in the template with:

echo get_query_var( 'mycpt_var' );

Answered by Milo on November 21, 2021

As a temporary solution you can try using free plugin : https://wordpress.org/plugins/custom-post-type-permalinks/

Answered by Latheesh V M Villa on November 21, 2021

Add your own answers!

Related Questions

Sending current featured image to email

0  Asked on January 26, 2021 by hm-dadou

   

wp_mail doen’t send mails whit attachment

2  Asked on January 25, 2021 by stonesmith

   

How to get category id of current post?

5  Asked on January 24, 2021 by jrcollins

 

preg_replace regex problem

1  Asked on January 23, 2021 by jim-worrall

   

How to display a sidebar only for blog?

1  Asked on January 23, 2021 by johny-j

 

Fill post titles from post content?

1  Asked on January 23, 2021 by cecily

     

Ask a Question

Get help from others!

© 2021 InsideDarkWeb.com. All rights reserved.