重写自定义POST类型不适用于动态数据

时间:2019-02-09 作者:Brick

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();
1 个回复
SO网友:Brick

好我不知道rewrite CPT属性必须提前注册:

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

相关推荐