How to Autofill a Custom Post Type title from ACF field in WordPress

How to Autofill a Custom Post Type title from ACF field in Wordpress

// Auto fill Title and Slug for CPT’s – ‘companies’, ‘contacts’, ‘properties

function lh_acf_save_post( $post_id ) {

    // Don't do this on the ACF post type
    if ( get_post_type( $post_id ) == 'acf' ) {
        return;
    }

    $new_title = '';
    $new_slug = '';

    // Get title from 'companies' CPT acf field 'company_name'
    if ( get_post_type( $post_id ) == 'gold' ) {
        $new_title = get_field( 'select_date', $post_id );
        $new_slug = sanitize_title( $new_title );
    }

    // Prevent iInfinite looping...
    remove_action( 'acf/save_post', 'lh_acf_save_post' );

    // Grab post data
    $post = array(
        'ID'            => $post_id,
        'post_title'    => $new_title,
        'post_name'     => $new_slug,
    );

    // Update the Post
    wp_update_post( $post );

    // Continue save action
    add_action( 'acf/save_post', 'lh_save_post' );

    // Set the return URL in case of 'new' post
    $_POST['return'] = add_query_arg( 'updated', 'true', get_permalink( $post_id ) );
}
add_action( 'acf/save_post', 'lh_acf_save_post', 10, 1 );
We Well organized and easy-to-understand Interactive tutorials With lots of examples of how to use Tutorials WordPress, PHP, Bootstrap, Bootstrap 4, HTML, CSS, AJAX, jQuery, Woocommerce, Post, Database, Javascript, Theme, Responsive, Templates.

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact us

Fill in the form below or give us a call and we'll contact you. We endeavour to answer all enquiries within 24 hours on business days.