我有一个Wordpress网站,正在使用重力形式和ACF字段。
我在重力表格中有一个用于图像URL的ACF URL字段product_photo_copy
。
提交重力表时,将创建一个帖子,我想获取图像URL并将其设置为该帖子的精选图像。
我正在使用以下代码:
function FeaturedImagefromUrl(){
if( !empty( get_field('product_photo_copy')) ){
$link = get_field('product_photo_copy');
//set as featured image
// Add Featured Image to Post
$image_url = $link; // Define the image URL here
$image_name = 'featured-image.png';
$upload_dir = wp_upload_dir(); // Set upload folder
$image_data = file_get_contents($image_url); // Get image data
$unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); // Generate unique name
$filename = basename( $unique_file_name ); // Create image file name
// Check folder permission and define file location
if( wp_mkdir_p( $upload_dir['path'] ) ) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
// Create the image file on the server
file_put_contents( $file, $image_data );
// Check image file type
$wp_filetype = wp_check_filetype( $filename, null );
// Set attachment data
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
// Create the attachment
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
// Include image.php
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Define attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );
// And finally assign featured image to post
set_post_thumbnail( $post_id, $attach_id );
}
}
上面创建了特色图片。现在,我需要在创建帖子时将其连接到帖子。我不确定执行此操作的最佳方法。我尝试使用Gravity表单挂钩,但是如果我提交了2ND FORM,它只会创建特色图片。表示图片为空白,然后如果我添加新帖子,则为第一篇帖子设置特色图片-第二篇帖子为空白-直到创建第三篇帖子,等等。
add_action( 'gform_after_submission', 'set_post_content', 10, 2 );
function set_post_content( $entry, $form ) {
//getting post
$post = get_post( $entry['post_id'] );
FeaturedImagefromUrl();
//updating post
wp_update_post( $post );
}`
这应该和此处https://docs.gravityforms.com/gform_after_submission/一样工作。因此,引力和WordPress部分正在起作用,但是我的代码有些不正确。 为什么钩子不能马上走?是否与我的代码不同步?