Ive added a custom content type called publications, via pods, and Im trying to save a post programmatically with an image, the post has been inserted successfully, but with no image, when I go to edit post page I cant find the image, I tracked the db on all is good, only table wp_podsrel is empty and has no records, seems that I should add a relationship
when i try to add a relationship i got an error
$pod = pods( 'publications', $newpost_id);
$id = $pod->add_to( 'publications_image', $attach_id );
the error is:
Uncaught Error: Call to undefined function tribe() in /home//wp-content/plugins/pods/classes/PodsAPI.php:
I have an external URL for the image that I want to save
$postData = array(
'post_title' => "feroferofero",
'post_content' => 'posts',
'post_status' => 'publish',
'post_type' => 'publications',
'meta_input' => array(
'publications_title' => 'feroferofero',
'publications_body' => $description,
'publications_type' => $type
),
);
$newpost_id = wp_insert_post($postData);
if ($newpost_id != 0) {
$image = pathinfo($image_url); //Extracting information into array.
$image_name = $image['basename'];
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$unique_file_name = wp_unique_filename($upload_dir['path'], $image_name);
$filename = basename($image_name);
if (!is_wp_error($newpost_id)) {
if ($image != '') {
// 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',
'post_parent' => $newpost_id,
'guid' => $upload_dir['url'] . '/' . $filename,
);
// Create the attachment
$attach_id = wp_insert_attachment($attachment, $file, $newpost_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
$thumbnail = set_post_thumbnail($newpost_id, $attach_id);
}
}
add_post_meta($newpost_id, 'publications_image', $attach_id);
}
Any idea?
2
Answers
I had good results with the following code:
So as you can see my code tries a dfifferent approach to the idea so give it a try and let me know if it works.
you can use the below code for image upload from url.
if you want to test this function you can add a test page in wordpress admin (code goes in functions.php or your plugin code)