0

I am looking for a custom function to auto generate a post title/slug for a specific CPT from two taxonomies and one custom field, created with ACF Pro.

Auto generation should be done only when the post title is empty.

Could someone of the experts help me out? Thank you so much!

Here my custom code:

// Create Auto Title for 'Veranstaltungen'
add_action('save_post', 'wpb_autogenerate_events_title', 10, 3);

function wpb_autogenerate_events_title($post_id, $post, $update) {
    // Check if it's the 'events' CPT and if the title is empty.
    if ('veranstaltungen' !== $post->post_type || !empty($post->post_title)) {
        return;
    }

    // Fetch terms from 'category' and 'nameselection' taxonomies.
    $category_term = wp_get_post_terms($post_id, 'event_category', ['fields' => 'names']);
    $nameselection_term = wp_get_post_terms($post_id, 'titel_winzer', ['fields' => 'names']);

    // Fetch the 'date' custom field created with ACF Pro.
    $date_start = get_field('datum_beginn', $post_id);
    $date_end = get_field('datum_ende', $post_id);

    // Combine the terms and the date to form the title.
    $new_title = join(' - ', array_merge((array) $category_term, (array) $nameselection_term, (array) $date_start, (array) $date_end));

    // Prepare the slug from the title.
    $new_slug = sanitize_title($new_title);

    // Update the post.
    wp_update_post([
        'ID' => $post_id,
        'post_title' => $new_title,
        'post_name' => $new_slug, // This is the slug.
    ]);
}

1 Answer 1

0

Try this in your functions.php file:


add_action('save_post', 'wpb_autogenerate_events_title', 10, 3);

function wpb_autogenerate_events_title($post_id, $post, $update) {
    // Check if it's the 'events' CPT and if the title is empty.
    if ('events' !== $post->post_type || !empty($post->post_title)) {
        return;
    }

    // Fetch terms from 'category' and 'nameselection' taxonomies.
    $category_term = wp_get_post_terms($post_id, 'category', ['fields' => 'names']);
    $nameselection_term = wp_get_post_terms($post_id, 'nameselection', ['fields' => 'names']);

    // Fetch the 'date' custom field created with ACF Pro.
    $date = get_field('date', $post_id);

    // Combine the terms and the date to form the title.
    $new_title = join(' - ', array_merge((array) $category_term, (array) $nameselection_term, (array) $date));

    // Prepare the slug from the title.
    $new_slug = sanitize_title($new_title);

    // Update the post.
    wp_update_post([
        'ID' => $post_id,
        'post_title' => $new_title,
        'post_name' => $new_slug, // This is the slug.
    ]);
}

0

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