Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Add custom field to permalink / URL WordPress

  • SOLVED

I'm trying to get custom field data into the permalink / URL of a custom post type page.

At the moment I've got...

website.com/category/postname/

..but I would like...

website.com/data/category/postname/

data = custom field meta data

I'm registering the custom post type in the normal way.
I've tried several plugins which either don't work, or, work on the main post page but not on custom post pages.
I ran out of talent along time ago!

Answers (3)

2011-09-20

Romel Apuya answers:

Hey have you tried this plugin ?

http://wordpress.org/extend/plugins/custom-fields-permalink/

this one works great..


Paul Gosnell comments:

yep, tried it but no luck. Seemed to work ok on index and single but not on custom post type pages. Cheers


Romel Apuya comments:

try this one :
add this to your function.php

add_filter('query_vars', 'custom_field');
function custom_field($vars) {
// add cust to the valid list of variables
$new_vars = array('cust');
$vars = $new_vars + $vars;
return $vars;
}


then use parse_request hook to create your redirect

add_action('parse_request', 'cust_parse_request');
function cust_parse_request($wp) {
// only process requests with "cust"
if (array_key_exists('cust', $wp->query_vars) && $wp->query_vars['cust'] != '') {
$args = array('meta_key' => 'cust', 'meta_value' => $wp->query_vars['cust']);
$redirect_to_post = get_posts($args);
foreach($redirect_to_post as $p){
$link = get_permalink($p->ID);
wp_redirect( $link , 301 );
exit;
}
}
}


replace cust with the name of your custom field..


Paul Gosnell comments:

I removed the plugin (http://wordpress.org/extend/plugins/custom-fields-permalink/) and added the two functions above to my functions.php file replacing all instances of 'cust' with 'authors_name' but no change?

Thanks - in theory from my small understanding oh php / wordpress the code above looks like what I want / what it needs to do! So close...


Romel Apuya comments:

so the functions would be like this now? :

add_filter('query_vars', 'custom_field');
function custom_field($vars) {
// add cust to the valid list of variables
$new_vars = array('authors_name');
$vars = $new_vars + $vars;
return $vars;
}

add_action('parse_request', 'cust_parse_request');
function cust_parse_request($wp) {
// only process requests with "cust"
if (array_key_exists('authors_name', $wp->query_vars) && $wp->query_vars['authors_name'] != '') {
$args = array('meta_key' => 'authors_name', 'meta_value' => $wp->query_vars['authors_name']);
$redirect_to_post = get_posts($args);
foreach($redirect_to_post as $p){
$link = get_permalink($p->ID);
wp_redirect( $link , 301 );
exit;
}
}
}


Paul Gosnell comments:

Yep - that's how I've got it but no luck.
In the second function, is it redirecting if the authors_name exists?


Romel Apuya comments:

sorry i forget ot declare global $wp:

add_filter('query_vars', 'custom_field');
function custom_field($vars) {
// add cust to the valid list of variables
$new_vars = array('authors_name');
$vars = $new_vars + $vars;
return $vars;
}

add_action('parse_request', 'cust_parse_request');
function cust_parse_request($wp) {
global $wp;
// only process requests with "cust"
if (array_key_exists('authors_name', $wp->query_vars) && $wp->query_vars['authors_name'] != '') {
$args = array('meta_key' => 'authors_name', 'meta_value' => $wp->query_vars['authors_name']);
$redirect_to_post = get_posts($args);
foreach($redirect_to_post as $p){
$link = get_permalink($p->ID);
wp_redirect( $link , 301 );
exit;
}
}
}


Romel Apuya comments:

ok if this one won't work how about trying this one from this post :

[[LINK href="http://wordpress.stackexchange.com/questions/3507/custom-field-values-in-permalink"]]http://wordpress.stackexchange.com/questions/3507/custom-field-values-in-permalink[[/LINK]]


have to sleep now...gudnight..


Paul Gosnell comments:

Thanks for answers Romel. I'll keep working on it and I've tried that stackexchange answer but nothing either. I'm beginning to think that they way the custom post types are registered is wrong!


Romel Apuya comments:

Hi Paul,

Have you figured out this one already?


Paul Gosnell comments:

Hi Romel,

Jurre's answer below is creating the URL structure as I want it but returning a 404.

Cheers


Romel Apuya comments:

have you updated youe .htaccess file?


Paul Gosnell comments:

I've reset permalinks which I thought flushed the rewrite rules? What do I do to update the .htaccess file?


Romel Apuya comments:

Can I take a look into you ftp and wp-admin?


Romel Apuya comments:

what's the current content in your .htaccess?


Paul Gosnell comments:

Its a client site so I feel a bit uncomfortable in doing that. No offense, I'm sure you understand. I could send a copy of the theme - would that help?


Romel Apuya comments:

ok..not a problem i understand that.
yes that would be great if you can send me a copy of the template.


Romel Apuya comments:

did you notice the value of rewrite when u register the poetry post type?
it was false..

register_post_type( 'poetry',
array(
'labels' => $labels,
'public' => true,
'supports' => $supports,
'taxonomies' => array( 'post_tag' ),
'rewrite' => true
)
);


Romel Apuya comments:

i think your almost there..

with jurre's answer.

try changing you permalink structure to

/%post_custom_data%/%postname%/


Romel Apuya comments:

or rather :

/%post_custom_data%/%category%/%postname%/


Paul Gosnell comments:

I set 'rewrite' => false as per Jurre's comment below...

'First of all, when registering your post type, make sure that you set the parameter 'rewrite' to false.'

I've just tried changing 'rewrite' => to 'false' and 'true' but it doesn't seem to change anything, even after resetting permalinks.

2011-09-20

Jurre Hanema answers:

This sounds like a job for some custom rewrite rules!

First of all, when registering your post type, make sure that you set the parameter 'rewrite' to false. Then you can try adding this code to your functions.php:


add_action('init', 'wpq_add_rewrite_rules');
add_filter('post_type_link', 'wpq_permalinks', 10, 3);

function wpq_add_rewrite_rules()
{
// Register custom rewrite rules

global $wp_rewrite;

$wp_rewrite->add_rewrite_tag('%POST_TYPE%', '([^/]+)', 'POST_TYPE=');
$wp_rewrite->add_rewrite_tag('%post_custom_data%', '([^/]+)', 'post_custom_data=');

$wp_rewrite->add_permastruct('POST_TYPE', '/%post_custom_data%/%POST_TYPE%', false);
}


function wpq_permalinks($permalink, $post, $leavename)
{
$no_data = 'no-data';

$post_id = $post->ID;

if($post->post_type != 'POST_TYPE' || empty($permalink) || in_array($post->post_status, array('draft', 'pending', 'auto-draft')))
return $permalink;

$data = get_post_meta($post_id, 'permalink_data', true);

if(!$data)
$data = $no_data;

$permalink = str_replace('%post_custom_data%', $data, $permalink);

return $permalink;
}


Replace every occurence of POST_TYPE with the name of your post type. The name of the custom field in which you have to enter the data is permalink_data.

This will give you the following structure: website.com/data/postname/. It is certainly possible to make it into website.com/data/category/postname/, but first let's see if this works, ok?


Paul Gosnell comments:

Nearly there!

This is creating the permalink / URL (website.com/data/category/postname/) but getting 'Error 404 - Page Not Found'

I've tried changing the permalink structure to...

/%postname%/

or

/%category%/%postname%/

...but still get a 404

Thanks


Jurre Hanema comments:

Have you flushed the rewrite rules by going to Settings -> Permalinks and clicking save?

If it still doesn't work, can you please share your complete code? Without code, it is difficult to guess what exactly is going wrong...


Paul Gosnell comments:

Yes, I've re-saved the permalinks saving these custom structure(s)...

/%post_custom_data%/%postname%/

/%post_custom_data%/%category%/

/%post_custom_data%/%category%/%postname%/

..but still get a 404.

I can send you a stripped theme file which has the css and images removed - would this help?

Thanks


Jurre Hanema comments:

Well, I think you should leave the permalink setting at /%category%/%postname%/. That's what works for me at least.

It would definitely be of help if you could send me the stripped theme. At the very least I should be able to determine if there's a problem with your code or if it's something else.


Paul Gosnell comments:

Thanks, email sent with theme file attached


Paul Gosnell comments:

Changing the permalink structure to...

/%category%/%postname%/

or

/%postname%/

...and directly going to page works, the URL is correct and content is there but now every link on the page or navigation reloads the index.php page but changing the URL? So the URL is changing but the same index page is being loaded?

Thanks again


Jurre Hanema comments:

That's definitely weird. Anyway, I have discovered one thing that's definitely wrong with your coude: you are calling the function flush_rewrite_rules() at two different places in your functions.php.

Not only is this in general a bad idea, it also causes the 404's you've been getting (or at least for me it does). So I suggest you first remove every call to flush_rewrite_rules() and then go to Settings -> Permalinks to flush the rules once manually.

Also, I am wondering why you are creating this many post types... wouldn't it be easier to just create one post type (say, 'writing') and then use a taxonomy to classify the writings in student writing, poetry, script writing, etc?

Finally, I have got a little modification to my function wpq_permalinks(). Change:

$permalink = str_replace('%post_custom_data%', $data, $permalink

to

$permalink = str_replace('%post_custom_data%', sanitize_title_with_dashes($data), $permalink);

That way you will not run into problems when using spaces or other unusual charachters in the custom field.


Jurre Hanema comments:

I also found another potential problem. The permalink structure I created, '%post_custom_data%/%poetry%', may conflict with the permalinks for other post types. To counter this, I suggest editing my function wpq_add_rewrite_rules() by changing

$wp_rewrite->add_permastruct('poetry', '/%post_custom_data%/%poetry%', false);

to

$wp_rewrite->add_permastruct('poetry', '/poetry/%post_custom_data%/%poetry%', false);


Jurre Hanema comments:

And another one of my little mistakes... sanitize_title_with_dashes in my second-last answer should really be sanitize_title.


Paul Gosnell comments:

I've removed all instances of flush_rewrite_rules(), added your modification and saved the custom permalink structure of /%category%/%postname%/.

This still shows the page as it should (correct URL and content) but navigating the site returns you to the index page regardless of the URL? So clicking all links changes the URL in the address bar but the page shows the index page content.

Its like every URL, other than the one the function is creating, is defaulting to the homepage index page?

Thanks Jurre - really appreciate the help


Jurre Hanema comments:

That is very strange. I do not have this issue. Have you made any other modifications besides the ones I mentioned? What happens if you disable all plugins?


Paul Gosnell comments:

Yep - removed all plugins, reset every option and still the same. I'm going to install a fresh copy and start again to see what happens?


Paul Gosnell comments:

Still no luck! Just did a complete reinstall and still the same issue... I'm running out of hair to pull out at the moment.

Jurre - do you have it working locally? I have the site up and a live dev server which I can share the address with you - if so, let me know and I'll email you the link.

Thanks


Jurre Hanema comments:

Yes, I have the theme with my modifications working locally. I would be glad to take a quick look at your dev site.


Jurre Hanema comments:

After looking at the link you sent me, this is what I found.

It seems like you forgot to apply one of the changes I added later, that is replacing


$wp_rewrite->add_permastruct('poetry', '/%post_custom_data%/%poetry%', false);


with


$wp_rewrite->add_permastruct('poetry', '/poetry/%post_custom_data%/%poetry%', false);


I changed this in your functions.php. Also, I modified your permalink structure
to %category%/%postname% because you had it set to %category% only which I don't think
is going to work.

It seems like the site is working now.


Paul Gosnell comments:

Thank you so much. It's working :)

I'm away from my PC at the moment (7pm here) but will respond / close this question in the morning.

This website has proved to be a valuable asset!


Paul Gosnell comments:

I can confirm this is working so thank you so much. Just one last question and I'll leave you alone! If I would to use this function on other post types of the same website - can this be done? Thanks

2011-09-20

Fahad Murtaza answers:

By 'data' you mean actual value for a custom field?


Fahad Murtaza comments:

Did you try [[LINK href="http://wordpress.org/extend/plugins/custom-fields-permalink/"]]http://wordpress.org/extend/plugins/custom-fields-permalink/[[/LINK]] ?


Paul Gosnell comments:

Hi, yes, the actual data for the custom field. So in this instance its a name so the URL will look like...

website.com/joe-bloggs/category/postname/

And yes, tried the plugin but could get it to work on custom post type pages. Seemed to work on the index and single but nothing else?


Fahad Murtaza comments:

Did you go to permalinks and saved permalinks again after doing the settings on this plugin?


Paul Gosnell comments:

yes. Just installed plugin again, set permalinks to...

/%cfp_authors_name%/%category%/%postname%/

authors_name = is the custom field name

Now all links just load the index.php (main news page) page even though the url is showing a different path... but still not showing the authors_name