upload PNG using set_post_thumbnail in WordPress - wordpress

It works fine for JPG but for PNG.
I wonder which part am I gonna change to make this work for PNG as well.
Here is my code
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$pid = wp_insert_post( $my_post ); //retrieves the last inserted post id
$attachment_id = media_handle_upload( 'my_image_upload', $pid );
if ( is_wp_error( $attachment_id ) ) {
$mine_msg = "There was an error uploading the image.";
} else {
$mine_msg = "The image was uploaded successfully!";
set_post_thumbnail( $pid , $attachment_id );
}
Please suggest me if this question needs to be changed or removed, instead of voting down my question.
Thanks :)

Found solution. Posting here for future reference.
After trying the comments/suggestions by Punit Gajjar and Ash Patel for hours I came to know that it was a virus in my client's desktop. The virus prevented him from uploading images.
Both mine and Ash Patel's code (link in comment above) works.

Related

wp_handle_upload() from the backend

I've used wp_handle_upload from the front end and it works fine.
Now I want to receive base64 string (jpg) from API POST store in metabox then turn it in to jpg(until here it works fine). Then I need to upload it in the media library and attach it to a post.
when I pass the file with file_get_contents or fopen it does not work. Any ideas?
function base64ToImage($base64){
$img = base64_decode($base64);
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
// wp_handle_upload( $_POST['img'], 0 );
$fp = fopen(get_template_directory()."/xxxxxxxxxxxxxxxxxxxxxxxxx.jpg", "w+");
// write the data in image file
fwrite($fp, base64_decode($base64));
// close an open file pointer
fclose($fp);
wp_handle_upload( file_get_contents("../" ."/xxxxxxxxxxxxxxxxxxxxxxxxx.jpg"), 0 );
return 0;
}
So to my past self and to anyone that might find this useful.
I used the wp_upload_bits function instead, subsequently I used
-wp_insert_attachment
-wp_generate_attachment_metadata
-wp_update_attachment_metadata
-set_post_thumbnail in order to associate the image with a specific parent post.

Wordpress Updating Attachment Data

I'm attempting to add a feature to a plugin that extends media management. This feature would allow you to rename an attachment file. I've been able to complete this with the following code.
public function update_attachment_filename( $post_ID ) {
// Get path to existing file
$file = get_attached_file( $post_ID );
$path = pathinfo( $file );
// Generate new file name
$file_updated = $path['dirname'] . '/' . $_POST['update_filename'] . '.' . $path['extension'];
// Update the name and reference to file
rename( $file, $file_updated );
update_attached_file( $post_ID, $file_updated );
}
While the original file gets renamed using the above method, all additional image sizes defined in the plugins/theme are not updated. I'm struggling to figure out the best way to accomplish this task.
I've looked into wp_update_attachment_metadata() and wp_generate_attachment_metadata() but am unsure whether they will give me the desired functionality.
Additionally I've looked into something such as:
$file_meta = wp_get_attachment_metadata( $post_ID );
foreach( $file_meta['sizes'] as $image ) {
// Do something
}
Any nudge in the right direction would be greatly appreciated.
Thanks!
I was able to utilize both the wp_generate_attachment_metadata() and the wp_update_attachment_metadata() function to achieve the desired end result.
public function update_attachment_filename( $post_ID ) {
if( isset( $_POST['update_filename'] ) && ! empty( $_POST['update_filename'] ) ) {
// Get path to existing attachment
$file = get_attached_file( $post_ID );
$path = pathinfo( $file );
// Create new attachment name
$file_updated = $path['dirname'] . '/' . $_POST['update_filename'] . '.' . $path['extension'];
// Update the attachment name
rename( $file, $file_updated );
update_attached_file( $post_ID, $file_updated );
// Update attachment meta data
$file_updated_meta = wp_generate_attachment_metadata( $post_ID, $file_updated );
wp_update_attachment_metadata( $post_ID, $file_updated_meta );
}
}

WordPress RSS list add featured image link

I want wordpress post rss list featured image link
Ex:
<title>Test title</title>
<desc>Test desc</desc>
<image>imagelink</image>
I'm not using plugin.
Thanks
This will do. Add it to functions.php file:
// add the namespace to the RSS opening element
add_action( 'rss2_ns', 'custom_prefix_add_media_namespace' );
function custom_prefix_add_media_namespace() {
echo "xmlns:media="http://search.yahoo.com/mrss/"n";
}
// add the requisite tag where a thumbnail exists
add_action( 'rss2_item', 'custom_prefix_add_media_thumbnail' );
function custom_prefix_add_media_thumbnail() {
global $post;
if( has_post_thumbnail( $post->ID )) {
$thumb_ID = get_post_thumbnail_id( $post->ID );
$details = wp_get_attachment_image_src($thumb_ID, 'thumbnail');
if( is_array($details) ) {
echo '<media:thumbnail url="' . $details[0] . '" width="' . $details[1] . '" height="' . $details[2] . '" />';
}
}
}
Also when you add this, be sure to reset the permalinks (flush them), by going to Settings > Permalinks, and either change permalinks to default, and back to your defined settings, or just re-saving.
After that, check your feed and the media should be there.

The best way to display Pod based images in your template file

I am relatively new to the WordPress CMS and decided to use Pods for my custom field implementations including several image fields. While I love the admin UI I was a bit flustered trying output the images in my post template file.
After a lot of research and experimenting I wanted to share the technique I used. Obviously if there is a better way I'd love to know.
The first thing I learned from the Pods forum was that Pods saves images to the database as 'Attachment' posts. So, they can be accessed as you would access any regular old WordPress attachment.
Attachments have a parent-child relationship with their post which means you can programmatically grab all the attachments for a given post using this snippet adapted from WP beginners:
<?php
if ( $post->post_type == 'post-type' && $post->post_status == 'publish' ) {
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_parent' => $post->ID,
'exclude' => get_post_thumbnail_id()
) );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$class = "post-attachment mime-" . sanitize_title( $attachment->post_mime_type );
$thumbimg = wp_get_attachment_image( $attachment->ID, 'thumbnail');
echo '<li class="' . $class . ' data-design-thumbnail">' . $thumbimg . '</li>';
}
}
}
?>
But this solution is sub-optimal because the parent-child relationship between the post and the image can only be broken if the image is deleted from the media library. So:
An image removed from it's original post but left in the library for future use will still be output by the above code on the original post
If you do re-purpose the image on a different post's Pod field the code above won't print it on the new entry.
The attachment system does not record field level relationships. So, if you have more than one image based Pod field on a Post the code above will print them all regardless if their field.
That said, I have found the best option for outputting Pod based image data by field is to combine the 'get_post_meta' function outlined here on the WordPress support forums with the 'wp_get_attachment_image' function as shown below.
<?php
if ( get_post_meta( get_the_ID(), 'image_field', false ) ){
$image_array = get_post_meta( get_the_ID(), 'image_field', false );
}
if ( $image_array ) {
echo '<ul>';
foreach ( $image_array as $image ) {
$class = "post-attachment mime-" . sanitize_title( $image->post_mime_type );
$thumbimg = wp_get_attachment_image( $image['ID'], 'thumbnail');
echo '<li class="' . $class . ' data-design-thumbnail">' . $thumbimg . '</li>';
}
echo '</ul>';
}
?>
The former function gives you an object with only the current images. The latter renders those images with size and alt info limited to the attachments system.

Can't upload images in wordpress

I am trying to add images to my post, but I keep getting the following messege: "An error occurred in the upload. Please try again later."
Note that I can see the images in the media library.
I am working on localhost.
using wordpress 3.8.1.
it can be due to the Plugin conflict.To check whether it is actually the case,disable all of your plugin by navigating to WordPress Admin Dashboard > Plugins > Select All Plugins > Bulk Action > Disable > Go
Well, after digging into the issue, it seems like the process only fails if a post_id value is set and the user doesn’t have rights to edit the post with that id.
Go to wp-includes/media.php
Look for *wp_enqueue_media* function
afterwards move to this block
$post = null;
if ( isset( $args['post'] ) ) {
$post = get_post( $args['post'] );
$settings['post'] = array(
'id' => $post->ID,
'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
);
and change it to
$post = null;
if ( isset( $args['post'] ) ) {
$post = get_post( $args['post'] );
if (is_admin()) {
$settings['post'] = array(
'id' => $post->ID,
'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
);
}
If you have issues in finding:
require_once(ABSPATH . 'wp-settings.php');”
then find define('WP_DEBUG', false);and add the below given code before it:
define(‘CONCATENATE_SCRIPTS’, false );
There was a problem with code in my template (something related to unclosed tags), so tracing back my code solved the problem.

Resources