Wordpress wp_update_attachment_metadata image width and height = 1? - wordpress

Hello Friends I used to set post thumbnail programmatically.
this is my code.
foreach ($csv as $key => $value) {
$filename = "wp-content/uploads/images/".$value[8].".jpg";
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => 'this is the first project file.',
'post_status' => 'Published'
);
$my_post = array(
'post_title' => $value[0],
'post_content' => $value[2],
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'post_staff'
);
$post_id = wp_insert_post( $my_post );
$attach_id = wp_insert_attachment( $attachment, $filename,$post_id);
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
add_post_meta($post_id, '_thumbnail_id', $attach_id);
update_post_meta( $post_id, '_staff_name', $value[1] );
update_post_meta( $post_id, '_staff_city', $value[3] );
update_post_meta( $post_id, '_staff_postal_code', $value[4] );
update_post_meta( $post_id, '_staff_direct_line', $value[5] );
update_post_meta( $post_id, '_staff_fax', $value[6] );
update_post_meta( $post_id, '_staff_email', $value[7] );
$tagd = array( 9 );
wp_set_post_terms( $post_id, $tagd, 'department' );
if($value[3] == "St. John's, NL"){
$tagl = array( 8 );
}else if($value[3] == "Corner Brook"){
$tagl = array( 7 );
}
wp_set_post_terms( $post_id, $tagl, 'location' );
if(set_post_thumbnail( $post_id, $attach_id )){
echo "image set";
}
}
This is working fine but the imported feature image with size 1x1 width = 1 and height = 1
why it takes width and height is 1 automatically please help.
when i trying to get image using get_the_post_thumbnail the return image.
image is found but by default the image width = 1 and height = 1 take.
this is my code.
get_the_post_thumbnail( get_the_ID(), array(250,165))
Thank you.

This Function is used to import post with image in wordpress.
function fetch_media($file_url, $post_id) {
require_once(ABSPATH . 'wp-load.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
global $wpdb;
if(!$post_id) {
return false;
}
//directory to import to
$artDir = 'wp-content/uploads/importedmedia/';
//if the directory doesn't exist, create it
if(!file_exists(ABSPATH.$artDir)) {
mkdir(ABSPATH.$artDir);
}
//rename the file... alternatively, you could explode on "/" and keep the original file name
$extpop = explode(".", $file_url);
$ext = array_pop($extpop);
$new_filename = 'blogmedia-'.$post_id.".".$ext; //if your post has multiple files, you may need to add a random number to the file name to prevent overwrites
if (#fclose(#fopen($file_url, "r"))) { //make sure the file actually exists
copy($file_url, ABSPATH.$artDir.$new_filename);
$siteurl = get_option('siteurl');
$file_info = getimagesize(ABSPATH.$artDir.$new_filename);
//create an array of attachment data to insert into wp_posts table
$artdata = array();
$artdata = array(
'post_author' => 1,
'post_date' => current_time('mysql'),
'post_date_gmt' => current_time('mysql'),
'post_title' => $new_filename,
'post_status' => 'inherit',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_name' => sanitize_title_with_dashes(str_replace("_", "-", $new_filename)), 'post_modified' => current_time('mysql'),
'post_modified_gmt' => current_time('mysql'),
'post_parent' => $post_id,
'post_type' => 'attachment',
'guid' => $siteurl.'/'.$artDir.$new_filename,
'post_mime_type' => $file_info['mime'],
'post_excerpt' => '',
'post_content' => ''
);
$uploads = wp_upload_dir();
$save_path = $uploads['basedir'].'/importedmedia/'.$new_filename;
//insert the database record
$attach_id = wp_insert_attachment( $artdata, $save_path, $post_id );
//generate metadata and thumbnails
if ($attach_data = wp_generate_attachment_metadata( $attach_id, $save_path)) {
wp_update_attachment_metadata($attach_id, $attach_data);
}
//optional make it the featured image of the post it's attached to
$rows_affected = $wpdb->insert($wpdb->prefix.'postmeta', array('post_id' => $post_id, 'meta_key' => '_thumbnail_id', 'meta_value' => $attach_id));
}
else {
return false;
}
return true;
}
Pass value to this function like.
$file_name = 'full path of existing image';
$post_id = '1';
fetch_media($filename,$post_id);
Thank you.

Related

Programmatically add an attachment sets a wrong permalink

I have a few hundreds of PDFs and I try to upload them programmatically in Wordpress and attach them in a custom post type with Advanced Custom Fields.
This is part of my code where I create the attachment
function update_attachment( $f, $pid, $file_url ){
wp_update_attachment_metadata( $pid, $f );
if( empty( $file_url ) )
return false;
$wp_upload_dir = wp_upload_dir();
$filetype = wp_check_filetype( basename( $file_url ), null );
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $file_url ),
'post_parent' => $pid,
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $file_url ) ),
'post_type' => 'attachment',
'post_content' => '',
'post_status' => 'inherit',
'post_mime_type' => $filetype['type'],
);
$attach_id = wp_insert_attachment( $attachment, $file_url );
return array(
'pid' => $pid,
'url' => $file_url,
'attach_id' => $attach_id
);
}
//create the custom post type
$post_id = wp_insert_post(array (
'post_type' => 'resources',
'post_title' => $file['Title'],
'post_status' => 'publish',
'comment_status' => 'closed',
'ping_status' => 'closed',
));
//Create the attachment in Media
$att = update_attachment( 'file', $post_id , 'migration/' . $file['FileName'] );
//Save the attachment to the ACF field
update_field('field_5eeb34e23731c', $att['attach_id'], $post_id );
The $file variable is an array where I have created before this code and contains the info of the pdf.
The post is created with the correct attachment. However, the permalink of the media file is the one from the post I created.
mydomain.org/resources/filename/‎
So, when I open the url mydomain.org/wp-content/uploads/migration/filename.pdf it redirects to the url above.

How to set the featured image of a post from the Media Library

If I create a post with this function:
function write_post_with_featured_image( $post_title, $categories ) {
$category_names_array = explode( ",", $categories );
$category_ids = array( );
foreach ( $category_names_array as $category_name ) {
$category_id = get_cat_ID( $category_name );
array_push( $category_ids, $category_id );
}
// Create post object
$my_post = array(
'post_title' => wp_strip_all_tags( $post_title ),
'post_status' => 'publish',
'post_author' => 1,
'post_category' => $category_ids,
);
// Insert the post into the database
$post_id = wp_insert_post( $my_post );
echo "post_id: " . $post_id;
}
How can I set it's featured image already existing in the Media Library?
Hopefully everyone will enjoy this function that creates a post and set's it's featured image from the Media Library:
function write_post_with_featured_image($post_title, $categories, $image_in_library_url) {
$category_names_array = explode(",", $categories);
$category_ids = array();
foreach ($category_names_array as $category_name) {
$category_id = get_cat_ID($category_name);
array_push($category_ids, $category_id);
}
// Create post object
$my_post = array(
'post_title' => wp_strip_all_tags($post_title),
'post_status' => 'publish',
'post_author' => 1,
'post_category' => $category_ids
);
// Insert the post into the database
$post_id=wp_insert_post( $my_post );
echo "post_id:" . $post_id;
//Get Image Attachment Id
$attachment_id = attachment_url_to_postid( $image_in_library_url );
echo "attachment_id:" . $attachment_id;
// And finally assign featured image to post
set_post_thumbnail( $post_id, $attachment_id );
echo "featured image added";
}
}
$post_title = 'My Super Post';
$categories = 'Category1,Category2';
$image_in_library_url = "http://localhost/wp-content/uploads/2018/06/my-super-image.jpg";
write_post_with_featured_image($post_title,$categories,$image_in_library_url);

get only featured image

I search internet, but I found only the reverse scenerio, the thing I want to do is that get only featured image in this query
$attachments = new WP_Query( array(
'post_parent__in' => $published,
'post_type' => 'attachment',
'post_status' => 'inherit',
'fields' => 'ids',
'posts_per_page' => 1,
'orderby' => 'rand',
'update_post_term_cache' => false,
'update_post_meta_cache' => false,
'no_found_rows' => true
) );
if ( $attachments->have_posts() ) {
$image = wp_get_attachment_image_src( $attachments->posts[0], $args[ 'size' ] );
if ( file_exists( $image[0] ) ) {
set_transient( $objects_key, $image, 3 * HOUR_IN_SECONDS );
}
}
}
You really don't want to mess with wp_query() if you can help it try this...
global $post;
$post_thumbnail_id = get_post_thumbnail_id( $post->ID );
if($post_thumbnail_id != null) {
$image = wp_get_attachment_image_src( $post_thumbnail_id, $args[ 'size' ] );
if ( file_exists( $image[0] ) ) {
set_transient( $objects_key, $image, 3 * HOUR_IN_SECONDS );
}
}
I am asuming that $objects_key and HOUR_IN_SECONDS are defined elsewhere

wp_insert_post function inserts the same post 2 times

Here is my code:
function insert_post() {
global $wpdb;
if (!isset($_POST['data'])) {
exit;
}
$data = json_decode(stripslashes_deep($_POST['data']), true);
$title = $data['post_title'];
$content = $data['post_content'];
$img = $data['post_thumbnail'];
$attach_id = $data['post_thumbnail'];
$review_post = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'publish',
'post_category' => array( 34 ),
'filter' => true
);
$post_id = wp_insert_post( $review_post );
$review = get_post( $post_id );
$avatar = wp_get_attachment_image( $img, 'full' );
$common_list = array();
$common_list['post'] = $review;
$common_list['post_thumbnail'] = $avatar;
$common_list['code'] = $code;
$common_list['fb'] = $fb;
$common_list['gender'] = $gender;
echo json_encode( $common_list);
exit;
}
add_action('wp_ajax_insert_post', 'insert_post');
add_action('wp_ajax_nopriv_insert_post', 'insert_post');
Problem is that wp_insert_post() function inserts the same post 2 times. Can't find solution. What can cause this?
I found a solution, here it is:
if (!get_page_by_title($title, 'OBJECT', 'post') ){
$review_post = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'publish',
'post_category' => array( 34 ),
'filter' => true
)
}
;
Just checked whether a post with same title exists or not, if yes it doesn't call wp_insert_post.

Wordpress wp_editor featured thumbnail image doesnt show

i was developing some theme that could create new post on front end. my issue is that when the "add media" has uploaded the photo, everything works well, except that when i set the "set featured image" for that post is not showing on the "thumbnail" when the post is published.
this is the wp_editor code setup:
<?php
$setupev = array(
'media_buttons'=>1,
'textarea_name'=>'post_ne',
'tinymce' => true );
wp_editor('content here', 'create_nepost', $setupev);
?>
this is the code i use to publish new post:
$the_contnt = $_POST['post_ne'];
$new_post = array(
'post_title' => $get_title,
'post_content' => $the_contnt,
'post_date' => date('YmdHis'),
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array(8,5)
);
wp_insert_post( $new_post );
is there some code to add-in to get the attachment thumbnail?
you need to use set_post_thumbnail() function. two things you require for this function are the $post_id which is the id you are providing to wp_insert_post() and $attach_id which is the id of attachment.
set_post_thumbnail( $post_id, $attach_id );
you already have $post_id, to find $attach_id
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'`
);
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );

Resources