Set featured image via post content programmatically - php

I was trying to add featured image from post content. My idea is to set the first image of the content as featured image of the post.
I wrote this in my funtions.php
add_action('publish_post', 'auto_featured_image_publish_post');
function auto_featured_image_publish_post($post, $post_id) {
$thumnail_id = //something I need help with
set_post_thumbnail( $post, $thumbnail_id );
}
This is just an idea how I want to do this.
Please help. Thanks

Check this url
https://www.gavick.com/blog/wordpress-quick-tip-4-automatically-set-the-first-post-image-as-a-featured-image
OR you can use this code to get the url of the first image from any HTML code
<?php
$postcontent = "";
preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $postcontent, $image);
// you can use the exist pattern or use this
// '/< *img[^>]*src *= *["\']?([^"\']*)/i'
echo $image['src'];
?>

Related

Wordpress: How to get the Header Image ID

Short story:
I'm trying to get the ID of the Header Image in Wordpress.
All I found was this guide, which dosn't seem to work anymore:http://nickohrn.com/2013/09/get-attachment-id-wordpress-header-image/
Long Story
I'm trying to make the WP Header responsive with an srcset. so I don't want to use this code
<img id="masthead-bg" src="<?php header_image() ?>" alt="">
...but instead want to use the wp_get_attachment_image_srcset function to get the srcset of my header image. Only problem: I need an Image ID for this function -> The ID of my Header image.
<img id="masthead-bg"
src="<?php header_image() ?>"
srcset="<?php echo wp_get_attachment_image_srcset( image_id(), 'thumbnail' ); ?>"
sizes="100vw" alt="">
Any suggestions?
Try this...
// Get the header image data
$data = get_object_vars(get_theme_mod('header_image_data'));
// Now check to see if there is an id
$attachment_id = is_array($data) && isset($data['attachment_id']) ? $data['attachment_id'] : false;
if($attachment_id) {
// Put your image code here, user whatever function to get image by id you need
}
Note: if you use a proper WordPress function to get the image it should add in all the srcset etc stuff for you, to allow for responsive images.
To answer the original question, I've found the simplest way to get the ID while I was filtering the markup that gets outputted by <?php the_header_image_tag(); ?> (introduced in v4.4).
function header_img_markup( $html, $header, $attr) {
// we can get the image ID by passing its src url to this method
$header_img_id = attachment_url_to_postid($attr['src']);
// now we can get its metadata from the db
$header_img_data = wp_get_attachment_metadata($header_img_id);
// now we can use the data
$customSizeWidth = $header_img_data['sizes']['my-custom-size']['width'];
// ...your custom output here...
return $html;
}
add_filter('get_header_image_tag', 'header_img_markup', 20, 3);
Responsive Wordpress Header Image with fallback:
if (get_header_image() !== '') {
$attachment_id = attachment_url_to_postid(get_header_image());
echo wp_get_attachment_image($attachment_id, 'large');
}
if (get_header_image() == '') {
echo '<h1>'.get_bloginfo( "name" ).'</h1>';
echo '<h2>'.get_bloginfo( "description" ).'</h2>';
}

I can't retrieve featured image url through wordpress

So I am trying to call an image to my main page (Home page). This image lives on a post and it is set as a featured image on that said post. So I got the post ID and I was able to display the title and content on the front page. But the featured image won't display the url. So here is the code I have on my front page:
<?php
$post_id = 53;
$queried_post = get_post($post_id);
$title = $queried_post->post_title;
$image = wp_get_attachment_image_src(get_post_thumbnail_id($post_id));
echo $title;
echo $image;
echo $queried_post->post_content;
?>
It just outputs array. Thank you for the help.
Here is the solution for your problem.
$post_thumbnail_id = get_post_thumbnail_id($post_id);
$thumb_images = wp_get_attachment_url($post_thumbnail_id);
echo $thumb_images;
//Here you will get url of featured image.
This following code can help you with your problem.
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post_id ), 'single-post-thumbnail' ); // get array of featured image
echo $image[0]; //get url of featured image of post

Add an ELSE to the IF in PHP script to get the default Image

I have this code inserted in the Function.PHP file of my wordpress this. What it basically do is:
when ever the user clicks the pinterest button, it ignores all the images in the blog post page but instead choose/return the feature image to be pinned.
function catch_that_image( $size = 'full' ) {
global $post;
if ( has_post_thumbnail($post->ID) ) {
$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), $size);
return $featured_image[0];
}
return false;
}
I have no problem with the code above, but then I realized that what if there's no featured image?
Is it possible if someone can modify the code for to to add the following IF and Else Condition:
IF Featured Image is Present:
Run the script above. (I think it's covered in the above code and works fine)
BUT IF THERE'S NOT FEATURED IMAGE, choose/return a default image to be pinned.
I'm not really sure how to integrate this code (below) to above code. Sorry but i lack of knowledge in this area.
if(empty($first_img)){ //Defines a default image
$first_img = "http://www.mywebsite/wp-content/themes/Default_Image.jpg";
}
THank you verymuch
Use the following code:
function catch_that_image( $size = 'full' ) {
global $post;
if ( has_post_thumbnail($post->ID) ) {
$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), $size);
if(empty($featured_image[0])){ //Defines a default image
$featured_image[0] = "http://www.mywebsite/wp-content/themes/Default_Image.jpg";
}
return $featured_image[0];
}
return false;
}

How can I get an automatic thumbnail from the first image in a Wordpress post?

I'm creating a Wordpress theme and I'd like to grab the first image in a post as a thumbnail to use in the Facebook's OG meta tag.
I tried using the function get_the_post_thumbnail() but it generates an html img element. Also I'd like to take the first image in the post, without the need of adding a featured image when creating the post.
This should be simple because there are already all thumbnails generated for every post, I'm just not getting it right.
Here I made some function for you that you can hook to add/edit attachment event.
function set_first_as_featured($attachment_ID){
$post_ID = get_post($attachment_ID)->post_parent;
if(!has_post_thumbnail($post_ID)){
set_post_thumbnail($post_ID, $attachment_ID);
}
}
add_action('add_attachment', 'set_first_as_featured');
add_action('edit_attachment', 'set_first_as_featured');
There is a lot of space for improvement, but this one works like a charm too. On every upload / edit attachment, function checks if the post already has featured image. If it has not, image in question is set as featured. Every next picture will be ignored (since post already has featured image).
Maybe someone finds it helpful (you found solution in the middle of my coding, so... :) )
I found this solution:
$size = 'thumbnail'; // whatever size you want
if ( has_post_thumbnail() ) {
the_post_thumbnail( $size );
} else {
$attachments = get_children( array(
'post_parent' => get_the_ID(),
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID',
'numberposts' => 1)
);
foreach ( $attachments as $thumb_id => $attachment ) {
echo wp_get_attachment_image($thumb_id, $size);
}
}
I found a solution:
wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'thumbnail' )[0];
It works fine.
Put this code in your theme's functions.php:
// make the first image of WordPress post as featured image
function first_image_as_featured() {
global $post, $posts;
$first_img_featured = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img_featured = $matches [1] [0];
if(empty($first_img_featured)){ //Defines a default image
$first_img_featured = "/images/default.jpg";
}
return $first_img_featured;
}
Then add the below code inside WordPress loop:
<?php
if (has_post_thumbnail()) { ?>
<?php the_post_thumbnail(); ?>
<?php }
else { ?>
<img src="<?php echo first_image_as_featured(); ?>" />
<?php
}
?>
If the featured image not set, it will automatically take the first image as featured image.
Source: Get The First Image Of WordPress Post As Featured Image
I have tried the solutions above withou success. So, I build a new and easy solution:
function set_first_as_featured($post_id){
$medias = get_attached_media( 'image', $post_id );
if(!has_post_thumbnail($post_id)) {
foreach ($medias as $media) {
set_post_thumbnail($post_id, $media->ID);
break;
}
}
}
add_action('save_post', 'set_first_as_featured');
When you save a post, this code will check if it has any thumbnail. If not, so it will set the first image attached to this post as thumbnail.

How to get the first image and set it as the post thumbnail?

I have these two functions which I found online and edited to my needs.
What I'm trying to do is to set the thumbnail of a wordpress post to either a default, previously set within the function itself image, or the first image embedded in the post.
However, something went wrong somewhere...
wptuts_save_thumbnail($post_id) -> Set the thumbnail of a post to default OR the first image if it's not already set (by the author of the post...)!
function wptuts_save_thumbnail( $post_id ) {
$post_thumbnail = get_post_meta( $post_id, '_thumbnail_id', true );
if (!wp_is_post_revision($post_id)) { // Verify that the post is not a revision
if (empty($post_thumbnail)) { // Check if Thumbnail does NOT exist!
$firstImg = firstImg($post_id); // Get the first image of a post (if available)
if(!$firstImg){ // if available, update the post thumbnail
update_post_meta( $post_id, '_thumbnail_id', 'link to default image here' );
} else { // else -> set thumbnail to default thumbnail
update_post_meta( $post_id, '_thumbnail_id', $firstImg );
}
}
}
}
firstImg($post _id) -> Used to get the first image of a post (by id)
function firstImg($post_id) {
$post = get_post($post_id);
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches[1][0];
$urlLength = strlen(site_url());
$first_img = substr($first_img, $urlLength);
if(empty($first_img)){
return false;
}
return $first_img;
}
The only problem with these functions is in the if(!$firstImg) - else statement.
The image will be always set to default with or without an embedded image in the post.
$firstImg does indeed return the first image if it exists so the problem must be in either of the 2 if's: if(empty($first_img)) OR if(!$firstImg).
I tried to look for any clues for the problem but I found nothing.
Hopefully someone can shed some light on this problem :)
Thanks in advance!
Additional Info:
- Both of the functions are written in the functions.php of my theme.
- wptuts_save_thumbnail($post_id) is set to run every time a NEW post is published.
- When returned, $first_img is the relative path of the image (i.e /wp-contents/uploads/img.jpg), or false.
What I can point out by looking at the code, that the check on firstImg:
if(!$firstImg){ // if available, update the post thumbnail
update_post_meta( $post_id, '_thumbnail_id', 'link to default image here' );
} else { // else -> set thumbnail to default thumbnail
update_post_meta( $post_id, '_thumbnail_id', $firstImg );
}
seems to return false, which would deliver you the default image.
What you could do is check the result of the $matches[1][0] in a dump or print_r in the firstImg function. Also check what $first_img is when before returning it. This could help you find the answer, because it seems that you're not getting the expected in the $first_img.
Hope that helps.

Categories