简体   繁体   中英

How to create pretty URL's for category page queries in WordPress?

I am trying to convert category links from queries to Pretty URL's.

For Example, I have category 'ALASKA'. It's URL is https://www.mywebsite.com/category/alaska/

I am getting some queries from the url using following link: https://www.mywebsite.com/category/alaska/?subscriber=1

I want to convert this URL to Pretty URL ( https://www.mywebsite.com/category/alaska/subscriber/ ) and also want to display custom template for it.

I tried this code:

Try 1

function my_template() {
    if ( is_archive() ) {
        if ( isset( $_REQUEST['subscriber'] )  ) {
            $myurl = get_category_link();
            if (substr($myurl) != "/") $myurl .= "/";
            $myurl .= "subscriber/";
            $myurl .= trim( sanitize_title_for_query( $_REQUEST['subscriber'] ) ) . "/";
            exit( wp_redirect( $myurl ) ) ;
        }
    }
}
add_action( 'template_redirect', 'my_template_redirect' );

Above code didn't work for me.

I don't have enough knowledge about URL Rewriting in WordPress.

Please help me.


UPDATE:

Try 2:

As mentioned in comment by Oussama I came up with this code:

function wallpaperinho_subcat_rewrite_rule() {
    add_rewrite_rule('^category/([^/]*)/subscriber/?','index.php?page_id=305965&subscriber=1','top');
}
add_action('init', 'wallpaperinho_subcat_rewrite_rule', 10, 0);

The above function works, but I am not able to detect current category ID on the custom page and in the function. Is there any way to do it? So I can display different data with different categories.

url = "https://www.mywebsite.com/category/alaska/?subscriber=1"
pretty = ""
for char in url: ## Loop through every letter in the 'ugly' URL
    if char in "abcedfghijklmnopqrstuvwxyz./:": ## If the character is allowed
        pretty += char  ## Add it to the Pretty URL

EDIT: Just realised that your code is in PHP ... this code is in Python :( ... I'm working on a PHP version.

我不确定WordPress,您要寻找的是使用.htaccessApache配置重写URL。

You can make the link SEO friendly using .htaccess

RewriteRule ^category/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/?$  category/$1/?subscriber=$2  [NC,L]

And then you can retrieve your var subscriber value using $_GET['subscriber']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM