1

I have following scenario:

my-domain-name.com/google.com

my-domain-name.com/twitter.com

I need a custom permalink structure to pass google.com or twitter.com to domain_name query variable.

I have tried following code:

add_rewrite_tag('%domain_name%', '([^&]+)');
add_rewrite_rule('^/([^/]*)/?','index.php?domain_name=$matches[1]','top'); 

But not working

For better example Check this site: http://currentlydown.com/facebook.com I am trying to do the similar

2

I'm not sure if I should assume that you were issuing your examples inside of the init hook, but if not that is the reason they weren't working for you.

So inside functions.php

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

Then if you wanted to retrieve the query variable to do something with it, you would do something like this in a page template file using the $wp_query global.

$domain_value = $wp_query->query_vars['domain_name'];

Everything you would want to know plus more can also be located by reading all about the Rewrite_API and it has tons of examples of doing other things you might find interesting or relevent.

https://codex.wordpress.org/Rewrite_API

| improve this answer | |
  • Thanks for your answer. I have done the same thing. The rules are inside init hook. – Saurin Dashadia Jan 5 '19 at 8:55
  • But somehow its not working. – Saurin Dashadia Jan 5 '19 at 8:55
  • So did you ever flush the rewrite rules after adding this, goto the permalinks page and save? – rifi2k Jan 5 '19 at 9:03
  • Then next step is just forcing the issue codex.wordpress.org/Class_Reference/WP_Rewrite about 3/4 of the way down there is a section about non-wp rewrite rules, also you can just access the wp_rewrite object and push rules directly to it, but always you need to flush the rewrite rules after making changes because they are cached heavily and need forced into being flushed by saving the permalinks page or using wp-cli – rifi2k Jan 5 '19 at 9:05
  • flush_rewrite_rules( true ); Just don't leave that in your code, immediatly take it back out after loading the frontend one time. – rifi2k Jan 5 '19 at 9:08
1

The problem was solved by just one line of code. I am thankful to @rifi2k for long discussion and proposing different solutions.

Here is the solutions:

Add following code to functions.php

function custom_rewrite_basic() {
    add_rewrite_tag('%domain_name%', '([a-z]{1,60}\.[a-z]{2,})');
}
add_action('init', 'custom_rewrite_basic');

Then from permalink settings, select Custom Structure and add newly created tag by only in our case its /%domain_name%/ save settings.

| improve this answer | |

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.