1

I have stumbled upon a brilliant piece of code that just fits my needs on this thread : Using custom field as custom post title by @chrisguitarguy and I was hoping there might be a way to tweak it to use several custom fields' input to populate a CPT's title.

For example, to be sure there will never be any case of twice the same title being generated I would like to use a custom field named dlc_media_photos_titre followed by another named dlc_media_photos_date, this way I should obtain a title in this format : Photo gallery name 20210921.

The date format doesn't really matter, it is just a security to include it in the title.

Thanks in advance (and excuse me if my post is not usual, it is my first one on StackExchange/Overflow).

edit Yes I will add the code i am using next time, it's so obvious ! Thanks a lot for your help

2

Ideally you should include the code you've already tried with your question so we can help with that, just a tip. :) But if you're using the code from that other post as-is, the change would be to this bit:

add_filter( 'the_title', 'wpse33385_filter_title', 10, 2 );
function wpse33385_filter_title( $title, $post_id )
{
    if( $new_title = get_post_meta( $post_id, 'custom_field_name', true ) )
    {
        return $new_title;
    }
    return $title;
}

Where the original only references one custom field, you need to grab two and then use both:

add_filter( 'the_title', 'wpse33385_filter_title', 10, 2 );
function wpse33385_filter_title( $title, $post_id )
{
    $photos_title = get_post_meta( $post_id, 'dlc_media_photos_titre', true );
    $photos_date = get_post_meta( $post_id, 'dlc_media_photos_date', true );

    if( $photos_title && $photos_date) {
        $new_title = $photos_title . ' ' . $photos_date;
        return $new_title;
    }
    return $title;
}

Note that the line $new_title = $photos_title . ' ' . $photos_date; is adding a space between the output of the two fields. If you wanted something else there, a | (pipe symbol) for instance, you could do:

$new_title = $photos_title . ' | ' . $photos_date;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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