WordPress.org

Ready to get started?Download WordPress

Forums

wp_insert_post get post_title from custom fields (1 post)

  1. streetrose
    Member
    Posted 11 months ago #

    I have a custom post type that don't need titles, instead the title is like a combination of custom fields (I'm using Advanced Custom Fields plugin for the extra fields):

    custom field 1 = This
    custom field 2 = That
    Converted Title = This And That

    I managed to find a way to do that using this code:

    add_filter('wp_insert_post_data','gordugo_update_title',99,2);
    function gordugo_update_title($data, $postarr) {
    global $post;
      if ( !is_admin() )
            return $data;
    
        if ($data['post_type'] == 'rides') {
    
            $data['post_name'] = sanitize_title( get_post_meta($post->ID, "pickup_date", true). '-' .get_post_meta($post->ID, "leaving_from", true). '-to-' .get_post_meta($post->ID, "going_to", true) );
    
            $data['post_title'] = get_post_meta($post->ID, "pickup_date", true). ' - ' .get_post_meta($post->ID, "leaving_from", true). ' to ' .get_post_meta($post->ID, "going_to", true);
    
            return $data;
        } else {
            return $data;
        }
    }

    This really works when I'm posting in WP Admin.

    Now this is a multi-user site and users should be able to post through front end. I managed to make ACF show in front end through this tutorial: http://www.advancedcustomfields.com/resources/tutorials/using-acf_form-to-create-a-new-post/

    But the problem is the post_title in wp_insert_post, it doesn't get the title from the custom fields.

    Here's the code I've been trying to make work:

    function my_pre_save_post( $post_id )
    {
        // check if this is to be a new post
        if( $post_id != 'new' )
        {
            return $post_id;
        }
    
        // Create a new post
        $post = array(
            'post_status'  => 'publish' ,
            'post_title'  => 'get_post_meta($post->ID, "pickup_date", true). ' - ' .get_post_meta($post->ID, "leaving_from", true). ' to ' .get_post_meta($post->ID, "going_to", true)',
            'post_type'  => 'rides' ,
        );  
    
        // insert the post
        $post_id = wp_insert_post( $post ); 
    
        // return the new ID
        return $post_id;
    }
    
    add_filter('acf/pre_save_post' , 'my_pre_save_post' );

    this part is not working:
    'post_title' => 'get_post_meta($post->ID, "pickup_date", true). ' - ' .get_post_meta($post->ID, "leaving_from", true). ' to ' .get_post_meta($post->ID, "going_to", true)',

    Can anyone please help me in making this work. This would be a great help. Thank you.

Reply

You must log in to post.

About this Topic