Support

Account

Home Forums General Issues Get field always retruns null in wp_insert_post hook.

Helping

Get field always retruns null in wp_insert_post hook.

  • I was wondering if there was a way to set a thumbnail when creating a post. With a hard-coded image url in the wp_insert_post hook, I was able to set the thumbnail.

    The custom field (of type text) does not work when passed as a URL. The issue occurs with or without the post_id.

    get_field('device_image_url') returns the url when used inside a single post.

    
    function set_post_thumbnail_when_created( $post_id, $post, $update ) {
    	require_once( ABSPATH . 'wp-admin/includes/media.php' );
    	require_once( ABSPATH . 'wp-admin/includes/file.php' );
    	require_once( ABSPATH . 'wp-admin/includes/image.php' );
    	if ( wp_is_post_revision( $post_id ) ) {
    		return;
    	}
    	if ( ! $update ) {
    		//$url  = "https://fdn2.gsmarena.com/vv/bigpic/xiaomi-poco-m4-pro-5g.jpg";
    		$url  = get_field( "device_image_url" );
    		$desc = "image description";
    		
    		$image = media_sideload_image( $url, $post_id, $desc, 'id' );
    		set_post_thumbnail( $post_id, $image );
    	}
    }
    
    add_action( 'wp_insert_post', 'set_post_thumbnail_when_created', 10, 3 );
    

    I’d appreciate your help with this.

  • When getting a field during the save process you must supply the post ID to get the value from or it will not return a value.

    
    $url  = get_field( "device_image_url", $post_id );
    
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.