ACF Magic: Dynamic Post Titles From First & Last Name Fields

by Mei Lin 61 views

Hey guys! Ever found yourself in a situation where you need to automatically generate post titles using Advanced Custom Fields (ACF) but are running into snags? Especially when dealing with forms like WS Form that save posts without titles? You're not alone! This is a common challenge, and I'm here to walk you through a robust solution. We'll dive deep into how you can dynamically create post titles from ACF fields, ensuring your content is not only well-organized but also SEO-friendly. Let's get started!

Understanding the Problem: Posts Without Titles

The core issue we're tackling is the creation of posts without titles, particularly when using form plugins like WS Form. These plugins often excel at capturing data and saving it as post content, but they might not automatically generate a title. This can lead to a messy backend, making it difficult to manage your content effectively. Imagine having a list of posts all labeled "Untitled" – a nightmare, right?

This is where ACF comes to the rescue. By leveraging ACF fields, we can capture specific pieces of information, such as a first name and last name, and use them to dynamically generate a title. This not only keeps your content organized but also opens up possibilities for SEO optimization. Think about it: a well-crafted title can significantly improve your post's visibility in search engine results. So, let's explore how to make this happen.

Why dynamic titles are crucial:

  • Organization: Clear titles make it easy to identify and manage your posts in the WordPress backend.
  • SEO: Titles are a significant factor in search engine rankings. Including relevant keywords in your titles can boost your SEO.
  • User Experience: A descriptive title helps users understand the content of the post at a glance.

Common Scenarios:

  • Contact Forms: Generating titles from names and contact information.
  • Event Registrations: Creating titles from event details and participant names.
  • Directory Listings: Dynamically generating titles from business names and categories.

Diving into the Solution: PHP Magic

The heart of our solution lies in using PHP code snippets within your WordPress theme's functions.php file (or a custom plugin). This code will hook into the post-saving process and automatically generate a title based on the values of your ACF fields. Let's break down the code and understand how it works step-by-step.

Here’s a general outline of the steps we’ll take:

  1. Identify the ACF Fields: Determine which ACF fields you want to use for generating the title (e.g., first name, last name).
  2. Hook into the save_post Action: This action is triggered whenever a post is saved or updated.
  3. Retrieve ACF Field Values: Get the values of the ACF fields using the get_field() function.
  4. Construct the Title: Combine the field values to create a meaningful title.
  5. Update the Post Title: Use wp_update_post() to update the post with the generated title.

The Code Snippet (and how to use it):

function generate_post_title_from_acf( $post_id ) {
 // Check if this is an ACF post being saved
 if ( ! isset( $_POST['acf'] ) ) {
 return; 
 }

 // Prevent infinite loop (very important!)
 remove_action( 'save_post', 'generate_post_title_from_acf' );

 // Get ACF field values
 $first_name = get_field( 'first_name', $post_id );
 $last_name = get_field( 'last_name', $post_id );

 // Construct the title
 if ( $first_name && $last_name ) {
 $post_title = $first_name . ' ' . $last_name;
 } else {
 // Fallback title if fields are empty
 $post_title = 'Untitled - Post ID: ' . $post_id;
 }

 // Update the post title
 $post_data = array(
 'ID' => $post_id,
 'post_title' => sanitize_text_field( $post_title ),
 'post_name' => sanitize_title( $post_title ), // Generate post slug
 );

 wp_update_post( $post_data );

 // Re-hook the function
 add_action( 'save_post', 'generate_post_title_from_acf' );
}
add_action( 'save_post', 'generate_post_title_from_acf' );

Explanation of the Code:

  • generate_post_title_from_acf( $post_id ): This is the function that will generate the post title.
  • if ( ! isset( $_POST['acf'] ) ) { return; }: This checks if the post is being saved via ACF. If not, the function exits to avoid unnecessary processing.
  • remove_action( 'save_post', 'generate_post_title_from_acf' );: This line is crucial to prevent an infinite loop. When wp_update_post() is called, it triggers the save_post action again. Removing the action temporarily prevents the function from calling itself repeatedly.
  • $first_name = get_field( 'first_name', $post_id ); and $last_name = get_field( 'last_name', $post_id );: These lines retrieve the values from your ACF fields. Replace 'first_name' and 'last_name' with the actual names of your ACF fields.
  • if ( $first_name && $last_name ) { ... }: This conditional statement checks if both first name and last name fields have values. This ensures we don't create titles with missing information.
  • $post_title = $first_name . ' ' . $last_name;: This line constructs the title by concatenating the first name and last name with a space in between.
  • $post_data = array( ... );: This creates an array containing the data to update the post, including the title and the post slug (which is a URL-friendly version of the title).
  • 'post_title' => sanitize_text_field( $post_title ): This sanitizes the title to prevent security vulnerabilities.
  • 'post_name' => sanitize_title( $post_title ): This generates a URL-friendly slug from the title.
  • wp_update_post( $post_data );: This function updates the post with the new title and slug.
  • add_action( 'save_post', 'generate_post_title_from_acf' );: This re-hooks the function after the update, ensuring it will run for future post saves.
  • add_action( 'save_post', 'generate_post_title_from_acf' );: This line hooks the function to the save_post action, meaning the function will be executed whenever a post is saved.

How to Implement the Code:

  1. Access your functions.php file: You can find this file in your theme's directory (e.g., wp-content/themes/your-theme/functions.php). Important: Be cautious when editing this file, as errors can break your site. Consider using a child theme to avoid losing changes during theme updates.
  2. Paste the code: Copy the code snippet above and paste it into your functions.php file.
  3. Modify the code: Crucially, replace 'first_name' and 'last_name' with the actual names of your ACF fields.
  4. Save the file: Save your functions.php file.
  5. Test it out: Create a new post using your form (e.g., WS Form) and fill in the ACF fields. Save the post, and you should see the title automatically generated!

Troubleshooting Tips:

  • Infinite Loop: If you experience an infinite loop (the page keeps loading), double-check that you have the remove_action() and add_action() lines in the correct places.
  • Title Not Updating: Make sure you've replaced the placeholder ACF field names with your actual field names. Also, check for any PHP errors in your error logs.
  • Incorrect Title: Verify that the logic for constructing the title is correct. Are you using the right fields? Is the concatenation working as expected?

Customizing the Title Generation: Beyond First and Last Name

The beauty of this approach is its flexibility. You're not limited to just first and last names. You can use any combination of ACF fields to generate your titles. Let's explore some customization options.

1. Using Multiple Fields:

Imagine you have fields for event_name, event_date, and event_location. You can combine these fields to create a descriptive title like "[Event Name] - [Event Date] - [Event Location]".

$event_name = get_field( 'event_name', $post_id );
$event_date = get_field( 'event_date', $post_id );
$event_location = get_field( 'event_location', $post_id );

if ( $event_name && $event_date && $event_location ) {
 $post_title = $event_name . ' - ' . $event_date . ' - ' . $event_location;
}

2. Adding Static Text:

You might want to include some static text in your titles, such as a category or a prefix. For example, you could add "New Customer:" before the customer's name.

$first_name = get_field( 'first_name', $post_id );
$last_name = get_field( 'last_name', $post_id );

if ( $first_name && $last_name ) {
 $post_title = 'New Customer: ' . $first_name . ' ' . $last_name;
}

3. Conditional Logic:

You can use conditional logic to generate different titles based on certain criteria. For instance, you might want to include a company name in the title only if it's available.

$first_name = get_field( 'first_name', $post_id );
$last_name = get_field( 'last_name', $post_id );
$company_name = get_field( 'company_name', $post_id );

if ( $first_name && $last_name ) {
 $post_title = $first_name . ' ' . $last_name;
 if ( $company_name ) {
 $post_title .= ' - ' . $company_name;
 }
}

4. Using ACF Relationship Fields:

ACF relationship fields allow you to connect posts to each other. You can use this to include information from related posts in your title. For example, if you have a