简体   繁体   中英

How do I turn PHP string into slug in Wordpress

I have a page in wordpress I am using with a slug called Bad-Debt-Recovery-in/ . I am using a custom php query on that page with strings in the URL's like this

Bad-Debt-Recovery-in/?zipcode=55555&location=Chambers%20County+AL

How can I make this url into a slug like this

Bad-Debt-Recovery-in/55555/Chambers-County/AL/

as a rewrite? Any help would be appreciated!

UPDATE: This code is actually what I am using. I also made it simpler and created a third variable named "state". One rewrite is for City and one is for County page:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^Bad-Debt-Recovery-And-Collection-Agencies-Services-In\/([^\/]+)\/([^\/]+)\/([^\/]+)\/? Bad-Debt-Recovery-And-Collection-Agencies-Services-In/?zipcode=$1&city=$2&state=$3 [QSA,L,NC]
RewriteRule ^Bad-Debt-Recovery-And-Collection-Agency-Services-In\/([^\/]+)\/([^\/]+)\/([^\/]+)\/? Bad-Debt-Recovery-And-Collection-Agency-Services-In/?countyid=$1&county=$2&state=$3 [QSA,L,NC]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php

</IfModule>

# END WordPress

You can use the WP function sanitize_title

Combine this with a php loop ie

$url = $_SERVER['REQUEST_URI'];
foreach($_GET as $g){
  $url .= '/'.$g;
}
$url = sanitize_title($url);

What you are asking for, and seeking to accomplish is called: Converting a request path into a query string.

Use .htaccess RewriteRule directive to modify the incoming request

RewriteRule ^Bad-Debt-Recovery-in\/([^\/]+)\/([^\/]+)\/([^\/]+)\/? Bad-Debt-Recovery-in/?a=$1&b=$2&c=$3 [QSA,L,NC]

Each ([^\\/]+) captures path elements into a variables $1,$2,$3...

The ? at the end simply denotes that the last / is optional or else the last match could fail

the \\ simply escape the '/' for literal interpretation

Add as many ([^\\/]+) as needed and capture them in the query

zipcode=$1&location=$2+$3

The modifiers at the end [QSA,L,NC] are called flags

  • QSA appends the query string to the end of the rewrite if any exist
  • L simply says this is the last rewrite
  • NC means not case sensitive

This is your final solution:

RewriteRule ^Bad-Debt-Recovery-in\/([^\/]+)\/([^\/]+)\/([^\/]+)\/? Bad-Debt-Recovery-in/?zipcode=$1&location=$2+$3 [QSA,L,NC]

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