Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I've created a filter to alter the_title hook in one of my custom post types (thanks Chip Bennett for the snippet). The function is supposed to tell Wordpress to call the title from a custom field (_location) within my custom post type page.

The problem is that all of my pages and posts in Wordpress are displaying 'No Title'. Instead, I want plain 'ole posts to display their titles normally, then I want my custom post title to display the contents from my custom field.

Here's the code that filters the titles:

function change_title ( $title ) { 
if ( !'events' == get_post_type() ) { 
    return $title; 
} else { 
    global $post; 
    $custom = ( get_post_custom( $post->ID ) ? get_post_custom( $post->ID ) : false ); 
    $custom_title = ( isset( $custom['_location'][0] ) ? $custom['_location'][0] : '(No Title)' ); 
    return $custom_title; 
} 

} 
add_filter( 'the_title', 'change_title' ); 

Here's my entire functions.php file:

<?php


// Registers the new post type and taxonomy
function wpt_event_posttype() {
register_post_type( 'events',
    array(
        'labels' => array(
            'name' => __( 'Custom Widgets' ),
            'singular_name' => __( 'Custom Widget' ),
            'add_new' => __( 'Add Custom Widget' ),
            'add_new_item' => __( 'Add New Custom Widget' ),
            'edit_item' => __( 'Edit Custom Widgets' ),
            'new_item' => __( 'Add New Custom Widgets' ),
            'view_item' => __( 'View Custom Widgets' ),
            'search_items' => __( 'Search Custom Widgets' ),
            'not_found' => __( 'No custom widgets found' ),
            'not_found_in_trash' => __( 'No custom widgets found in trash' )
        ),
        'public' => true,
        'supports' => array( 'custom_fields' ),
        'capability_type' => 'post',
        'rewrite' => array("slug" => "events"), // Permalinks format
        'menu_position' => 99,
        'register_meta_box_cb' => 'add_events_metaboxes'
    )
);
}
add_action( 'init', 'wpt_event_posttype' );



// Add the Custom Widgets Title Meta Box
function add_events_metaboxes() {
add_meta_box('wpt_events_location', 'Custom Widget Title', 'wpt_events_location', 'events', 'normal', 'high');

// Add the Page Template Assignments Meta Box
add_meta_box('pagetemplate', 'Page Template Assignments', 'pagetemplate', 'events', 'normal', 'high');

// Add the Post Assignments Meta Box
add_meta_box('postassignments', 'Post Assignments', 'postassignments', 'events', 'normal', 'high');

// Add the Additional Filters Meta Box
add_meta_box('additionalfilters', 'Additional Filters', 'additionalfilters', 'events', 'normal', 'high');
}


// The Callback for Custom Widget Title Metabox
function wpt_events_location() {
global $post;
// Noncename needed to verify where the data originated
echo '<input type="hidden" name="eventmeta_noncename" id="eventmeta_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
// Get the title data if its already been entered
$boxtitle = get_post_meta($post->ID, '_location', true);
// Echo out the field
echo '<input type="text" name="_location" value="' . $boxtitle  . '" class="widefat" />';
}


// The Callback for Page Template Assignmets Metabox
function pagetemplate() {
global $post;
// Noncename needed to verify where the data originated
echo '<input type="hidden" name="pagetemplatemeta_noncename" id="pagetemplate_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
// Get the title data if its already been entered
$boxtitle2 = get_post_meta($post->ID, 'page_template', true);
// Echo out the field
echo '<input type="text" name="page_template" value="' . $boxtitle2  . '" class="widefat" />';
}


// The Callback for Post Assignmets Metabox
function postassignments() {
global $post;
// Noncename needed to verify where the data originated
echo '<input type="hidden" name="postassignmentsmeta_noncename" id="postassignments_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
// Get the title data if its already been entered
$boxtitle3 = get_post_meta($post->ID, 'post-assign', true);
// Echo out the field
echo '<input type="text" name="post_assign" value="' . $boxtitle3  . '" class="widefat" />';
}


// The Callback for Additional Filters Metabox
function additionalfilters() {
global $post;
// Noncename needed to verify where the data originated
echo '<input type="hidden" name="additionalfiltersmeta_noncename" id="additionalfilters_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
// Get the title data if its already been entered
$boxtitle4 = get_post_meta($post->ID, 'additional_filters', true);
// Echo out the field
echo '<input type="text" name="additional_filters" value="' . $boxtitle4  . '" class="widefat" />';
 }


// Save the Metabox Data
function wpt_save_events_meta($post_id, $post) {
// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if ( !wp_verify_nonce( $_POST['eventmeta_noncename'], plugin_basename(__FILE__) )) {
return $post->ID;
}
// Is the user allowed to edit the post or page?
if ( !current_user_can( 'edit_post', $post->ID ))
    return $post->ID;
// OK, we're authenticated: we need to find and save the data
// We'll put it into an array to make it easier to loop though.
$events_meta['_location'] = $_POST['_location'];
// Add values of $events_meta as custom fields
foreach ($events_meta as $key => $value) { // Cycle through the $events_meta array!
    if( $post->post_type == 'revision' ) return; // Don't store custom data twice
    $value = implode(',', (array)$value); // If $value is an array, make it a CSV (unlikely)
    if(get_post_meta($post->ID, $key, FALSE)) { // If the custom field already has a value
        update_post_meta($post->ID, $key, $value);
    } else { // If the custom field doesn't have a value
        add_post_meta($post->ID, $key, $value);
    }
    if(!$value) delete_post_meta($post->ID, $key); // Delete if blank
}
}
add_action('save_post', 'wpt_save_events_meta', 1, 2); // save the custom fields




add_filter( 'manage_edit-events_columns', 'my_edit_events_columns' ) ;

function my_edit_events_columns( $columns ) {

$columns = array(
    'cb' => '<input type="checkbox" />',
    'title' => __( 'Custom Widget Title' ),
    'page_assign' => __( 'Page Template Assignments' ),
    'post_assign' => __( 'Post Assignments' ),
    'additional' => __( 'Additional Filters' ),
    'date' => __( 'Date' )

);

return $columns;
}




add_action( 'manage_events_posts_custom_column', 'my_manage_events_columns', 10, 2 );

function my_manage_events_columns( $column, $post_id ) {
global $post;

switch( $column ) {

    /* If displaying the 'duration' column. */
    case 'page_assign' :

        /* Get the post meta. */
        $page_assign = get_post_meta( $post_id, 'page_assign', true );

        /* If no duration is found, output a default message. */
        if ( empty( $page_assign ) )
            echo __( 'Unknown' );

        /* If there is a duration, append 'minutes' to the text string. */
        else
            printf( __( '%s minutes' ), $page_assign );

        break;

    /* If displaying the 'duration' column. */
    case 'post_assign' :

        /* Get the post meta. */
        $post_assign = get_post_meta( $post_id, 'post_assign', true );

        /* If no duration is found, output a default message. */
        if ( empty( $post_assign ) )
            echo __( 'Unknown' );

        /* If there is a duration, append 'minutes' to the text string. */
        else
            printf( __( '%s minutes' ), $post_assign );

        break;  




    /* If displaying the 'genre' column. */
    case 'additional' :

        /* Get the genres for the post. */
        $terms = get_the_terms( $post_id, 'additional' );

        /* If terms were found. */
        if ( !empty( $terms ) ) {

            $out = array();

            /* Loop through each term, linking to the 'edit posts' page for the specific term. */
            foreach ( $terms as $term ) {
                $out[] = sprintf( '<a href="%s">%s</a>',
                    esc_url( add_query_arg( array( 'post_type' => $post->post_type, 'additional' => $term->slug ), 'edit.php' ) ),
                    esc_html( sanitize_term_field( 'name', $term->name, $term->term_id, 'additional', 'display' ) )
                );
            }

            /* Join the terms, separating them with a comma. */
            echo join( ', ', $out );
        }

        /* If no terms were found, output a default message. */
        else {
            _e( 'No Additional Filters' );
        }

        break;

    /* Just break out of the switch statement for everything else. */
    default :
        break;
}
}


function change_title ( $title ) {  
global $post;  
if ( !'events' == get_post_type( $post ) ) {  
    return $title;  
} else {  
    $custom = ( get_post_custom( $post->ID ) ? get_post_custom( $post->ID ) : false );  
    $custom_title = ( isset( $custom['_location'][0] ) ? $custom['_location'][0] : '(No Title)' );  
    return $custom_title;  
}  

}  
add_filter( 'the_title', 'change_title' );  
share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

Your call to get_post_type() needs to be passed the $post object, which you don't globalize until later. Try globalizing the $post object earlier. Also, try using foo != bar instead of ! foo == bar:

function change_title ( $title ) { 
    global $post; 
    if ( 'events' == get_post_type( $post ) ) { 
        $custom = ( get_post_custom( $post->ID ) ? get_post_custom( $post->ID ) : false ); 
        $custom_title = ( isset( $custom['_location'][0] ) ? $custom['_location'][0] : '(No Title)' ); 
        return $custom_title; 
    } else { 
        return $title; 
    } 

} 
add_filter( 'the_title', 'change_title' ); 

Edit

Also, to ease of troubleshooting, I would recommend writing your conditional in the affirmative with respect to your custom post type, i.e. if ( 'events' == get_post_type( $post ) ), rather than if ( 'events' != get_post_type( $post ) ). The former will only ever return true for your post type; the latter will return true always except for your post type.

share|improve this answer
    
Hi Chip, I got this snippet from one of your answers. Thanks for the snippet. I tried the answer you posted above and all my posts still show "no title". Maybe I'm posting the wrong labels - in this case "events" is my custom post name and the custom field is "_location". Did I insert those labels correctly? –  Rob Myrick Jun 9 '12 at 19:25
    
See updated answer. I made another change to your conditional. –  Chip Bennett Jun 9 '12 at 19:31
    
And one more update, to reconfigure your if/else handling. –  Chip Bennett Jun 9 '12 at 19:34
    
Hi Chip, it worked.....you may want to update the snippet from the related post you have here wordpress.stackexchange.com/questions/22011/…. You could also write a blog post on that one. Not too much out there, but I know people would love to read it. –  Rob Myrick Jun 9 '12 at 19:36
    
Also, I read your profile and noticed you're in ST. Louis. What suburb are you from? I just moved from South City to the Phoenix, AZ area. Take care. –  Rob Myrick Jun 9 '12 at 19:37
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.