0

Using filters/hooks, how would I replace the title of a wordpress post with whatever term has been selected from a custom taxonomy.

Hopefully the attached image will explain what I'm trying to do.

enter image description here

Let's say I selected 'Powerchrono' - I would like the title of the post to be replaced with the selected term, and it's parent.

Any help would be much appreciated.

I'd obviously like the url of the post to also be updated too.

Nick
  • 715
  • 2
  • 7
  • 10

1 Answers1

2

I can't guarantee this will work straight out of the gate since it's untested. But this should get you started:

functions.php

<?php
add_action('save_post', 'update_term_title');
function update_term_title($post_id)
{
    if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) 
        return;
    if(!current_user_can('edit_post', $post_id))
        return;

    //Replace 'manufacturer' with whatever your custom taxonomy slug is
    $terms = wp_get_post_terms($post_id, 'manufacturer');

    if(empty($terms))
        return;

    $title = false;
    foreach($terms as $term)
    {
        if($term->parent)
        {
            $parent = get_term($term->parent, 'manufacturer');
            $title = $term->name.' '.$parent->name;
            break;
        }
    }
    /*Default to first selected term name if no children were found*/
    $title = $title ? $title : $terms[0]->name;

    /*We must disable this hook and reenable from within
    if we don't want to get caught in a loop*/
    remove_action('save_post', 'update_term_title');
    $update = array(
        'ID'=>$post_id,
        'post_name'=>sanitize_title_with_dashes($title),
        'post_title'=>$title
    );
    wp_update_post($update);
    add_action('save_post', 'update_term_title');
}
?>
maiorano84
  • 11,574
  • 3
  • 35
  • 48
  • Wow! Well out of the box it's almost 100% working - only issue I have is that for some reason it's not using the parent term in the title. I clicked on PowerChrono, and the title of the post is 'PowerChrono' - not 'Accurist PowerChrono'. – Nick Oct 22 '12 at 19:14
  • 1
    Did you have to change the taxonomy slug where I marked it in my comments? If so, did you also change it where $parent was being set? – maiorano84 Oct 22 '12 at 19:28
  • I've fixed it, I just changed 'manufacturer' to 'manufacturers'. It works like a treat, thanks for helping. – Nick Oct 22 '12 at 19:29
  • Exactly what I have been looking for for hours, thanks – bilcker Sep 03 '14 at 19:32