php - Getting first image from post
Solution:
I understand that you want to check if there is a custom image for that post (from the ACF field), and if there isn't take the first image from the post content.
I also understand (didn't check) that your current code works for the second case (get the first image from the post), so all you need is to add a query for the ACF image.
I would try something like this:
function catch_that_image() {
global $post;
$acf_image = get_field('your_acf_image_field_name');
if (!empty($acf_image)) {
return $image['url'];
} else {
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+?src=[\'"]([^\'"]+)[\'"].*?>/i', $post->post_content, $matches);
$first_img = $matches[1][0];
if(empty($first_img)) {
$first_img = "/path/to/default.png";
}
return $first_img;
}
}
Please note that in WordPress there are many advantages for using the native wp_get_attachment_image() with an image ID from ACF Image fields - you can find more information here: https://www.advancedcustomfields.com/resources/image/
Answer
Solution:
@Hillel, thanks.
I tried this instead. But my return result all in array. Is there something wrong. I modified from other code.
/**
* Filters the title and alt message for thumbnails.
*
* @since 2.3.0
*
* @param string $post_title Post tile used as thumbnail alt and title
* @param object $result Post Object
*/
$post_title = apply_filters( 'tptn_thumb_title', $post_title, $result );
$output = '';
$postimage = '';
$pick = '';
if(! $postimage)
{
$args = [
'numberposts' => 1,
'order' => 'ASC',
'post_parent' => $post_title,
'post_type' => 'attachment',
'post_mime_type' => 'image'
];
$post_attachments = get_children($args);
if ( ! empty($post_attachments) ) {
$output = array_shift($post_attachments->url);
return [
$postimage => get_attached_file($output->url),
$pick => get_post_meta($postimage->ID, '_wp_attachment_image_alt', true)
];
}
}
Answer
Solution:
I try out this instead.
if(!$postimage)
{
$header_image = get_field( 'article_header_image', $result );
if($header_image ){
$postimage = ( $postimage['url'] );
$pick .= 'first';
}
else{
$postimage = tptn_get_first_image( $result->ID, $args['thumb_width'], $args['thumb_height'] ); // Get the first image.
$pick = 'firstchild';
}
}
How do I parse to URL?
https://i.stack.imgur.com/j34BI.jpg
I tried the edited code. Not sure why it took the image randomly. Some is correct some is not.
Source