0

I created a Custom Post Type in my plugin. I added an argument with rewrite:

'rewrite' => array('slug' => 'foo/bar/%baz%', 'with_front' => false),

Then I added a method to replace %baz%:

public function customPermalinks($post_link, $post)
{
    if (is_object($post) && $post->post_type == 'test') {
        $terms = wp_get_object_terms($post->ID, 'baz');
        if ($terms) {
            return str_replace('%baz%', $terms[0]->slug, $post_link);
        }
    }
    return $post_link;
}

On __construct() I added this filter:

add_filter('post_type_link', [$this, 'customPermalinks'], 1, 2);

And... My CPT works only when I don't use dynamic variables (%baz%). When I remove %baz% from rewrite attribute, it works... Otherwise, I get a 404 message when I want to go to a single post. How to fix it?

I will add that before each change I manually refresh rewrite rules.

Here is my plugin file structure:

class PluginName
{
    public function __construct()
    {
        $this->createPostType();
        add_filter('post_type_link', [$this, 'customPermalinks'], 1, 2);
    }

    private function createPostType()
    {
        // arguments to my CPT
    }

    public function customPermalinks($post_link, $post)
    {
        // replace dynamic data from $post_link
    }
}

$pluginName = new PluginName();
  • Does baz belong to a registered object, or did you add baz to the list of valid query vars? – Milo Feb 9 at 18:11
  • @Milo baz is registered custom taxonomy. Variable $post_link returns a valid rewrite with baz value, ex. foo/bar/lorem-ipsum/custom-post-title but when I go at this address (the_permalink) it shows error with no post. – Brick Feb 9 at 18:39
  • @Milo I forgot about add_rewrite_tag('%baz%', '([^&/]+)');. Problem solved! – Brick Feb 9 at 19:04
0

Well... I didn't know that the expressions in the rewrite attribute of CPT must be registered in advance:

add_rewrite_tag('%baz%', '([^&/]+)');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.