Someone helped accomplish this code last week which works perfectly, it pulls keywords entered into a custom field ( advanced custom fields ) into the middle of a URL and then redirects them.
Code in custom single template:
<?php $url = get_site_url(); $id = get_the_ID(); echo "<a href='{$url}/goto/amazon/{$id}/'>More info Test dynamic Amazon</a>"; ?>
Code in functions.php
add_action( 'template_redirect', function(){
global $wp_query;
if ($goto = get_query_var( 'gotoamazon' )) {
$keywds = urlencode(get_field('amazon_keywords',intval($goto)));
$link = "http://www.amazon.co.uk/s/?_encoding=UTF8&camp=1634&creative=19450&field-keywords={$keywds}&linkCode=ur2&tag=AFFID";
wp_redirect($link);
exit;
}
});
Rewrites also in functions.php :
add_action( 'init', function(){
add_rewrite_tag('%gotoamazon%','([^&]+)');
add_rewrite_rule('^goto/amazon/(.*)/?','index.php?gotoamazon=$matches[1]','top');
});
But what id like to do now is use the same code to pull the wp_title if the keyword field is empty, I have the conditional setup, Ive then copied the code from above changing it to the title ( or what i thought would work ) but its not inserting the title into the desired place.
add_action( 'template_redirect', function(){
global $wp_query;
if ($goto = get_query_var( 'gotoamazon' )) {
$keytitle = urlencode(wp_title(', '),true,intval($goto));
$link = "http://www.amazon.co.uk/s/?_encoding=UTF8&camp=1634&creative=19450&field-keywords={$keytitle}&linkCode=ur2&tag=AFFID";
wp_redirect($link);
exit;
}
});