0

I could not found a realiable way to create new content type and allow the permalink structure works. Every place where someone wants to let the permalink structure works to a new content type in WordPress I read that the user needs to visit the Settings > Permalinks admin page.

Lots of reference also mentioning the use of the flush_rewrite_rules() to "flush rewrite rules". But until now, none of then worked, I still needs to visit the permalinks page.

Look at the following code that I tried in my new content type plugin. I am putting together at once everything that I read to solve this question. Trying to flush in plugin registering and loading the rewrite rules object and explicity calling functions that supposedly rewrite the rules. Nothing worked.

register_activation_hook( __FILE__, 'my_new_content_type_flushes' );

function my_new_content_type_flushes() {
    flush_rewrite_rules();
    global $wp_rewrite;
    $wp_rewrite->flush_rules();
    $wp_rewrite->init();
}

Maybe I can use some of those flushing functions in another hook, like when creating new content of my new content type. But if so, I can incur in some inefficiency question. Flushing the rewrite rules will run a code that will loop through all my contents, right? And if I have some thousands of contents, it will make no sense to do so even for those contents that already are all ok with its permalink structure, like posts contents.

So, how I can add a new content type and let its permalink structure works without going to the permalinks page?

  • With that rule, you're only going to flush the rewrite rules and permalinks when you activate the plugin. Did you try that? Turning it off and back on again? btw that IS the way a the flushing of rules is supposed to work. You don't want to be flushing all the time: it uses quite bit of resources. More info could be provided if you could detail what you mean by "new content". – rudtek Sep 18 '17 at 15:43
  • If you look to code that I share, you can see that I used the register_activation_hook, and supposedly is where the code run at plugin activation. Unless that is an alternative way to do that, yes, I tried to flush the rewrite rules at plugin activation and did not worked. Is there an alternative way to do that? – danilocgsilva Sep 18 '17 at 17:59
  • No, the code appears to be correct. The question is: did you try to disable the plugin then re-enable it? That's when the flush will happen with this code. – rudtek Sep 18 '17 at 18:01
1

Make sure you register the new post types before flushing! So call the function that registers them not only on init, but also in your activation/flush function.

See very first example here: https://codex.wordpress.org/Function_Reference/flush_rewrite_rules.

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.