htaccess redirect - hundreds of posts - wordpress

Wordpress Redirects
My client has a WP website with a very bad permalinks structure and few hundreds "product" pages that they created as simple posts with bunch of HTML.
For example:
http://www.website.com/article/sony-tv-42-inch
http://www.website.com/article/iphone-5-2-black
http://www.website.com/article/samsung-dvd-player-12455
I am creating a new site from scratch and planning to use custom post types for Products section and organize URLS like:
http://www.website.com/product/sony/tv-42-inch
http://www.website.com/product/apple/iphone-5-black
http://www.website.com/product/samsung/dvd-player-12455
Since he doesnt want to lose any traffic or SEO ratings, i was wondering what would be the simplest solution for htaccess redirect for few hundred posts?
If he only had dozen of them, i could do it manually, but few hundreds...
Also, bare in mind that this is clean WP install with a theme built from scratch (i am working locally and most likely will be importing products via CSV file) so i cant just change the permalinks structure on production website.
Any help would be appreciated

It'd be fairly easy for you to re-write from
http://www.website.com/product/sony-tv-42-inch
to
http://www.website.com/product/sony-tv-42-inch
but that extra / is going to present a problem.
As mentioned by some others you certainly want a 301 for SEO purposes, so here is what I would do.
Step 1 - Get current URLS:
Get a list of all current post permalinks. This SQL query for MySQL by David George should do the trick.
SELECT wpp.post_title,
wpp.guid,
wpp.post_date,
CONCAT
(
wpo_su.option_value,
REPLACE
(
REPLACE
(
REPLACE
(
REPLACE
(
wpo.option_value,
'%year%',
date_format(wpp.post_date,'%Y')
),
'%monthnum%',
date_format(wpp.post_date, '%m')
),
'%day%',
date_format(wpp.post_date, '%d')
),
'%postname%',
wpp.post_name
)
) AS permalink
FROM wp_posts wpp
JOIN wp_options wpo
ON wpo.option_name = 'permalink_structure'
AND wpo.blog_id = 0
JOIN wp_options wpo_su
ON wpo_su.option_name = 'siteurl'
AND wpo_su.blog_id = wpo.blog_id
WHERE wpp.post_type = 'post'
AND wpp.post_status = 'publish'
ORDER BY wpp.post_date DESC
Step 2 - Save it for later:
Now that you have that list dump it into an Excel column for later.
Step 3 - Format it for PHP:
Take all the URLs and dump them into Notepad++ or equivalent. On windows hit cntrl+H to bring up the find/replace function. Make sure to select 'Search Mode' -> 'Extended'
For "Find What" you should put in \r\n and for 'Replace With' you should put in , and hit 'Replace All'.
You should now have a list of all your URLs separated only by a comma.
Step 4 - Create a PHP File:
Create a new PHP file and set:
<?php
$urlString = "http://www.urlsample1.com/article/sony-thing-and-stuff, http://www.urlsample1.com/article/warner-brothers-stuff";
//this will replace the word article with the word product
$newstring = str_replace("article", "product", $urlString);
//turns string into array
$myArray = explode(',', $newstring);
//loops through array to find first case of - and turn it to a /
for ($i = 0; $i < count($myArray); ++$i) {
$haystack = $myArray[$i];
$needle = "-";
$replace = "/";
$pos = strpos($haystack, $needle);
if ($pos !== false) {
$finalstring = substr_replace($haystack, $replace, $pos, strlen($needle));
}
//removes common url elements
$newShort = str_replace("http://www.urlsample1.com", "", $finalstring);
$oldShort = str_replace("http://www.urlsample1.com/product", "/article", $myArray[$i]);
//prints out the old and new url in .htaccess format
print("Redirect 301 " . $oldShort . " " . $newShort . "</br>");
};
?>
Step 5 - .Htaccess
Your output from above should look like:
Redirect 301 /product/sony-thing-and-stuff /product/sony/thing-and-stuff
Redirect 301 /product/warner-brothers-stuff /product/warner/brothers-stuff
and can be put into the .htaccess file.
Note: This method may become slow with Apache and isn't preferable but it is the quickest way I can think of to get your client up and running on the new situation.

For SEO, i suggest you use 301 - redirect in your .htaccess
You can use regexp for redirect.
Example:
RewriteEngine on
RewriteRule ^/users/(.*)$ http://www.example.com/profiles/$1 [R=301,L]

Related

How to get a part of url? (nginx, rewrite, lua)

How to get a part of url?
For example:
have url: /aaa/bbb/ccc?test=123
I need to get part of url /ccc into the nginx variable.
I want to get a variable with a value = "ccc"
I will use the variable in location {}
url = '/abc/def/ghi?test=123'
-- here ^ to here ^ then back 1
q = url :find('?')
head = url :sub( 1, q -1 ) -- /abc/def/ghi
-- reversing is just an easy way to grab what would
-- would be the last delimiter, but is now the first.
head = head :reverse() -- ihg/fed/cba/
slash = head :find('/') -- 1st ^
-- same as above, grab from beginning, to found position -1
folder = head :sub( 1, slash -1 ) -- ihg
folder = folder :reverse() -- ghi
-- reverse again, so it's right-way 'round again.
Commands can be stacked, to make it smaller. Harder
to explain the logic that way, but it's the same thing.
head = url :sub( 1, url :find('?') -1 ) :reverse()
folder = head :sub( 1, head :find('/') -1 ) :reverse()
I would suggest to use a library, available from official OpenResty Package Manager OPM:
opm install bungle/lua-resty-reqargs
This library works for both GET and POST variables:
local get, post, files = require "resty.reqargs"()
if not get then
local ErrorMessage = post
error(ErrorMessage)
end
-- Here you basically have `get' which is a table with:
-- { test = 123 }
The API is a little bit weird because the function returns 3 values.
In case of failure, it will return false, ErrorMessage, false.
In case of success, it will return GetTable, PostTable, FilesTable. Except this, it just works.
You can use it in a location block:
location /aaa/bbb/ccc {
content_by_lua_block {
local get, post, files = require "resty.reqargs"()
if not get then
local ErrorMessage = post
ngx.say(ErrorMessage)
else
ngx.say(string.format("test=%d", get.test))
end
}
}

Replace first character in $args

I would like to replace the first character of $args in rewrite
I have the following:
return 302 https://domain/accounts/registration?_uid=1928&_tag=$request_uri&$args;
if $args are empty I just get a link that ends with a & which is not a big problem but if I have some $args I get something&?arg1 which is wrong since &? is considered as a continuation of the previous parameter.
How can I remove the first letter ( ? ) from $args ?
$request_uri already includes the optional ? and the query string. So your extra ? is coming from $request_uri and not from $args.
You could try using $uri&$args instead of $request_uri which will replace the embedded ? with a &.
For example:
return 302 https://domain/accounts/registration?_uid=1928&_tag=$uri&$args;
However, any percent-encoded characters in $request_uri are fully decoded by the time that $uri is constructed - which may or may not impact your application.
See this document for more.

WooCommerce - Translate a word on the Checkout page

I'm trying to translate a word on the WooCommerce checkout page.
My website is in the Dutch language, but they translated it poorly, so I want to use a different word.
What needs to be translated
It concerns the following line:
"Totaal €469,38 (Inclusief €79,38 Belasting)"
In English this says:
"Total €469,38 (Includes €79,38 tax)"
It's the line that sums up the total amount of the order. And I want to translate the word 'Belasting' to 'BTW'.
What I've tried
Checked out settings in WooCommerce
Installed the plugin Loco translator
Searched for the word with FTP (Adobe Dreamweaver)
As I couldn't find the word 'Belasting' anywhere, I did find the php-file with the element of the line.
This I found in the PHP-document wc-cart-functions.php:
if ( ! empty( $tax_string_array ) ) {
$value .= '<small class="includes_tax">' . sprintf( __( '(Includes %s)', 'woocommerce' ), implode( ', ', $tax_string_array ) ) . '</small>';
}
And this is how the HTML part looks like:
<small class="includes_tax">
(inclusief
<span class="amount">€79,38</span>
Belasting)
</small>
My Question
I presume it does print the word 'Belasting' with the '%s' variable. However I am unable to find the content for that variable anywhere.
So can anybody help me out by finding how to translate this word?
Thanks for reading and I'd appreciate the help.
You can try using the gettext filter
Example
function my_text_strings( $translated_text, $text, $domain ) {
switch ( $translated_text ) {
case 'Related Products' :
$translated_text = __( 'Check out these related products', 'woocommerce' );
break;
}
return $translated_text;
}
add_filter( 'gettext', 'my_text_strings', 20, 3 );
WooCommerce uses gettext for translations, as described here there are several methods of updating the translation, the easies of which is editing the file in woocommerce/i18n/languages/
The "Includes" part is translate-supported. i.e. you just need to add it to your translation file:
The translation file is in my case (danish): "../wp-content/languages/plugins/woocommerce-da_DK.po"
Open the file in your texteditor, e.g. Notepad++ and add these lines:
#: includes/class-wc-order.php:40 includes/wc-cart-functions.php:246
msgid "(Includes %s)"
msgstr "(Inkluderer %s)"
Now you need to compile the PO file to an MO file and you can use Poedit.
Just open the PO file and save it, it will create a new MO file that you can upload and replace the current MO file (path: "../wp-content/languages/plugins/")
So fare so good!
In regards to the "Tax" part. This is controlled in the admin module:

How can i replace url from css

I'm trying to combine multiple css files into a single file (from many different folder in my host, and including external css files). I use the following short code:
Declare array:
$styles=array(
array(
'name'=>'style1.css',
'path'=>'http://mydomain.com/css/'
),
array(
'name'=>'camera.css',
'path'=>'http://mydomain.com/js/camera/'
),
array(
'name'=>'style3.css',
'path'=>'http://external.com/assets/css/'
));
Get content and replace url:
foreach ($styles as $style) {
echo preg_replace('/url\(\s*[\'"]?\/?(.+?)[\'"]?\s*\)/i', 'url('.$style['path'].'$1)', file_get_contents($style['path'].$style['name']));
}
After combined into one css file, i have some css background image url as follows:
url(ttp://mydomain.com/css/../image/background.png) //Internal path - Case 1A
url(http://mydomain.com/js/camera/../../image/background.png) //Internal path - Case 1B
url(http://external.com/assets/css/../../image/background.png) //External path - Case 2
Actual, the internal path (Case 1A, 1B) can display the background image (despite the lack of professionalism), but in the external path (Case 2) cannot display the background image, my question is:
How can i replace wrong path with correct path (REPAIR BASE ON CURRENT RESULTS) as:
url(http://mydomain.com/image/background.png) //Correct internal path
url(http://external.com/image/background.png) //Correct external path
(I understand the problem is if find a keyword containing '../' will remove keyword and remove 1 string before the keyword contain '*/', , but I can't figure out how to do this).
Thanks in advance.
(I have tried find out and tried searching for 1 week before ask new question).
additionally replace /up-level-directory/../ with /
that is '/([^\/]+)/../' with / globally
$correct_url = preg_replace('|/\w+/\.\./|', '/', $url);

Query Posts issue in wordpress

I am a little unsure how to do a WP_Query to search a meta value of my posts. The meta data includes a persons height. So valid entries would be 5'9" or 4'11" and I need to do a Compare-Between.
To make it a bit clearer: I have a filter page. So the user can select the height between 4'0" - 5'9 or 5'9" - 5'11"
The problem is I have the ' and " symbols. I can remove these. But then it will be searching between 59 and 511 which is not going to work.
Anyone know of a work around?
Save the values in inches.
You could then set up a WP_Query or a $wpdb query to fetch your results.
Whenever you are displaying the values on the front end, you convert them back to feet and inches.
update:
function convert_to_feet( $input){
$feet = (int) ($input/12);
$inches = $input%12;
return $feet . "'" . $inches . '"';
}
echo convert_to_feet(71);

Resources