I get the first image from post whith this code:
function first_image() {
global $post, $posts;
$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)){
$images = array(
'white5px.jpg',
);
$image = $images[array_rand($images)];
$first_img = "/wp-content/themes/tabs/images/" . $image . "";
}
return $first_img;}
?>
<img src="<?php echo first_image() ?>"title="<?php the_title(); ?>" alt="<?php the_title(); ?>"/>
Everything works fine except when I use the galery - the image not displayed.
Live example:http://beardhouse.com.ua/?cat=2 Why it doesn't work and how I can solve this problem?
Everything works fine except when I use the galery - the image not
displayed.
Galleries are not stored in the post body as full img tags, which is what your regex looks for. A gallery is saved to the post body as a shortcode which is processed on display and transformed into the gallery you see.
That is, if you echo $post->post_content what you will see is something like this:
[gallery ids="729,732,731,720"]
The quick and dirty solution would be to process that shortcode before your regex gets involved.
$content = do_shortcodes($post->post_content);
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);
$first_img = $matches [1] [0];
I can't help but think that that is a somewhat clumsy and inefficient solution. Most images in WordPress are "attachments" to the post, so you might be better off querying for attachments directly, as per this example from the Codex:
function echo_first_image( $postID ) {
$args = array(
'numberposts' => 1,
'order' => 'ASC',
'post_mime_type' => 'image',
'post_parent' => $postID,
'post_status' => null,
'post_type' => 'attachment',
);
$attachments = get_children( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$image_attributes = wp_get_attachment_image_src( $attachment->ID, 'thumbnail' ) ? wp_get_attachment_image_src( $attachment->ID, 'thumbnail' ) : wp_get_attachment_image_src( $attachment->ID, 'full' );
echo '<img src="' . wp_get_attachment_thumb_url( $attachment->ID ) . '" class="current">';
}
}
}
To get First Image of Post Enter this code in Function.php file
function catch_that_image(){
global $post, $posts;
$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)){ //Defines a default image
$first_img = "/images/default.jpg";}return $first_img;}
}
add this code in post loop
Related
im updating my WordPress website and removing the https://wpbakery.com/ editor and I'm wanting to remove the markup generated by the plugin.
This plugin https://codecanyon.net/item/shortcode-cleaner-clean-wordpress-content-from-broken-shortcodes/21253243 I'm using will remove all shortcodes with no problem except one. It's removing images.
On closer inspection images are posted on the backend using the below shortcode
[vc_single_image image="10879" img_size="large" add_caption="yes" alignment="center"]
And I want to update all references to use HTML instead
<img src="IMGURL">
However, I'm not sure about the right way to do it, any advice, please?
There is a regular expression replace in MySQL 8, but if you don't have that, you could do it with PHP.
$query = new WP_Query( [-- whatever posts you want--] );
while ( $query->have_posts() ) {
$query->the_post();
$content = get_the_content();
preg_match('/\[vc_single_image image="(\d+)" img_size="(\w+)"[^\]]*\]/', $content, $matches);
if( isset($matches[1]) ) {
$url = wp_get_attachment_image_url( (int) $matches[1], $matches[2] );
$img = sprintf( '<img src="%s" />', $url );
$new_content = str_replace( $matches[0], $img, $content );
wp_update_post( [ 'ID' => get_the_ID(), 'post_content' => $new_content] );
}
}
Here Is the updated answer to update all images in the post/page content. The above code finds the first image of the content and update that.
// Args for the WP_Query
$args = array(
'post_type' => 'post',
'posts_per_page' => 10,
'post__in' => array(5824),
'orderby' => 'post__in'
);
// Execute WP_Query with args
$query = new WP_Query( $args );
// Start the Loop
while ( $query->have_posts() ) {
$query->the_post();
// Get Page/Post content
$content = apply_filters('the_content', $content);
// Get the vc_single_image count from the post
$found_keyword = substr_count( $content,"vc_single_image" );
// Start loop to replace all elements from the content
for ($i=0; $i < $found_keyword; $i++) {
// Get the position of vc_single_image shortcode with Image ID and Image Size
preg_match( '/\[vc_single_image image="(\d+)" img_size="(\w+)"[^\]]*\]/', $content, $matches );
// Check shotcode are exist on loop
if( isset( $matches[1]) ){
// Get the Image ur by Image id and Size
$url = wp_get_attachment_image_url( (int) $matches[1], $matches[2] );
$img = sprintf( '<img src="%s" />', $url );
// Replce shortcode with <img> tag
$content = str_replace( $matches[0], $img, $content );
}
}
// Update post content with updated content with <img> tag
wp_update_post( [ 'ID' => get_the_ID(), 'post_content' => $content] );
}
// END the Loop
This could be a duplicate question, but not one of these similiar questions has touched the get_attached_media part, which is what I need help with.
If I don't have any Featured Image in the post, I want to use the image attached in the content of the post, as a Featured Image.
Here is what I'm trying and failing:
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php
if(get_post_thumbnail_id() == TRUE) {
$image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'backstretch' );
}
else {
$image_url = wp_get_attachment_image_src( get_attached_media('image'), 'backstretch');
}
?>
<header class="backstretch-target backstretch-header <?php echo crisp_filter_img() ?>" data-background="<?php echo $image_url[0]; ?>">
I've realised I need to fetch the url of get_attached_media('image') for it to work. But even with using foreach I've not managed this:
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php
function get_image($arr) {
$images = get_attached_media('image');
$arr = [];
foreach($images as $image) {
$url = wp_get_attachment_url($image->ID);
$image_url = wp_get_attachment_image_src($url, 'backstretch');
$arr[] = $image_url;
}
return $arr;
}
?>
<header class="backstretch-target backstretch-header <?php echo crisp_filter_img() ?>" data-background="<?php echo get_image($arr[0]); ?>">
My url becomes this:
http://site.loc/wp/2016/01/05/postname/%3Cbr%20/%3E%3Cfont%20size='1'%3E%3Ctable%20class='xdebug-error%20xe-notice'%20dir='ltr'%20border='1'%20cellspacing='0'%20cellpadding='1'%3E%3Ctr%3E%3Cth%20align='left'%20bgcolor='
Which clearly states that it gets image attributes as url. I've googled and played with the code, and I just can't find realize the problem.
I really appreciate your help.
Also if you still find this as a duplicate, I apologize!
I use this function to get all available images from a WordPress post:
function get_post_images( $post = null ) {
if ( $post === null ) {
global $post;
}
/* Get the featured image of the post */
if ( has_post_thumbnail() ) {
$images[] = get_post_thumbnail_id( $post->ID );
}
/* If the post contains galleries, get all images from them */
if( has_shortcode( $post->post_content, 'gallery' ) ) {
$galleries = get_post_galleries( $post, false );
foreach ( $galleries as $gallery ) {
$ids = explode( ',', $gallery['ids'] );
$images = array_merge( $images, $ids );
}
}
/* Get all single images in the post */
preg_match_all("/wp-image-(\d+)/", $post->post_content, $imgs );
foreach ($imgs[1] as $img) {
$images[] = $img;
}
/* get all images attached to the post
* not sure if this is a good idea, there might be images attached
* which were not supposed to be published */
$post_images = get_posts( array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'numberposts' => -1,
'post_mime_type' => 'image',
'exclude' => $images ) );
foreach ( $post_images as $image ) {
$images[] = $image->ID;
}
/* As a fallback, add a predefined default image */
if ( sizeof( $images ) == 0 && $this->default_image != null) {
$images[] = $this->default_image;
}
/* remove duplicated images */
$images = array_unique( $images );
return $images;
}
The function returns an array containing all image IDs related to the given post, if you only need one you can extract that easily:
$images = get_post_images();
echo wp_get_attachment_image( array_shift( $images ) );
Well, I fixed the problem. I tried to use the popular get_that_image plugin, but it didn't fix my problem. At the end of the day I trashed the get_attached_media, and used this function which I found here.
function crisp_catch_that_image() {
$image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'backstretch' );
if (!empty($image_url)) {
return $image_url[0];
}
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
if (empty($matches[1])) {
return '';
}
return $matches[1][0];
return $first_img;
}
The images that I'm querying from my wordpress media gallery are appearing correctly. But, I also want them to link to my custom attachment page and I can't get it to work
<?php
$query_images_args = array(
'post_type' => 'attachment', 'post_mime_type' =>'image', 'post_status' => 'inherit', 'posts_per_page' => -1,
);
$query_images = new WP_Query( $query_images_args );
$images = array();
foreach ( $query_images->posts as $image) {
$images[]= wp_get_attachment_url( $image->ID );
}
foreach ($images as $img) {
$url = get_attachment_link($img->ID);
echo '' . '<img src="' . $img . '" alt="" />' . '';
}
?>
Skip the second foreach loop. You have everything you need in the first one:
$query_images = new WP_Query( $query_images_args );
$images = array();
foreach ( $query_images->posts as $image) {
$images[]= wp_get_attachment_url( $image->ID );
$url = get_attachment_link($image->ID);
echo '' . '<img src="' . wp_get_attachment_url( $image->ID ) . '" alt="" />' . '';
}
wp_get_attachment_url() returns the URI of the image, see http://codex.wordpress.org/Function_Reference/wp_get_attachment_url; you were trying to get the ID from this non-object.
I am working with this two Wordpress Function for my Pinterest Button. What i'm trying to achieve is the flow chart below.
Function Catch That Image
function catch_that_image() {
global $post, $posts;
$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)){ //Defines a default image
$first_img = "http://www.mywebsite.com/wp-content/themes/Lord%20of%20Avernus%20-%20Abaddon/Images/Deafult_Img.png";
}
return $first_img;
}
Function Get Featured Image
function get_featured_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;
}
Wordpress Featured Thumbnail
<?php the_post_thumbnail(); ?>
As you can see in my flow chart, I am trying to combine the two functions above. The problem is it's not working.
This is my code:
Function Consolidated Pinterest Image Function
function pinterest_image_snatcher($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];
}
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)){ //Defines a default image
$first_img = "http://www.mywebsite.com/wp-content/themes/Lord%20of%20Avernus%20-%20Abaddon/Images/Deafult_Img.png";
}
return $first_img;
}
The first two functions above is working really fine but the third one is not! Could anyone help to consolidate the two function above. Everyone is welcome to modify the codes.
Please help me out Dear PHP Experts. My Code is messed up and NOT working. Do you mind to modify this according to the flow chart? thank you!
How to add Pinterest button for WordPress Blogs
Try this:
function pinterest_image_snatcher( $size = 'full' ) {
global $post;
$first_img = '';
if ( has_post_thumbnail($post->ID) ) {
$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), $size);
$first_img = $featured_image[0];
} else {
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches[1][0];
if( empty($first_img) ) {
$first_img = "http://www.mywebsite.com/wp-content/themes/Lord%20of%20Avernus%20-%20Abaddon/Images/Deafult_Img.png";
}
}
return $first_img;
}
I just fixed missing brackets as #royal-bg mentioned in the comments & changed logic a bit.
Today I've been trying to display the most popular post in wordpress using the following code:
http://pastebin.com/TjJTiiTZ
It works great however it's not allowing me to grab the first attached image on the post. I need to do it that way in order to get the image from any of the several custom fields holding the images.
I tried to use the following code (which actually works on another customization) to get the first attached image on the post but I have not been able to make it work.
$p = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'numberposts' => 1,
'order' => 'ASC',
'orderby' => 'menu_order ID',
'post_status' => null,
'post_parent' => $post->ID
);
$thumb = get_posts($p);
if ($thumb) {
$imgsrc = wp_get_attachment_image_src($thumb[0]->ID, 'thumbnail');
$img = $imgsrc[0];
}
Is there any way in which this can be accomplish??
You can use this code to get posts first attachment image:
$catposts = get_posts('category='.$category_id."&order=DESC&numberposts=".$NUMBEROFPOSTS);
function catch_that_image($_catposts)
{
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $_catposts->post_content, $matches);
$first_img = $matches[1][0];
return $first_img;
}
$j=0;
foreach ($catposts as $item) :
$get_contents = $item->post_content;
$regex_pattern = "/<a href=\"(.*)\">(.*)<\/a>/";
$output = preg_match_all($regex_pattern,$item->post_content, $matches);
echo '<img src="'.catch_that_image($catposts[$j]).'" alt="" border="0px" />';
$j++;
endforeach;
where $category_id is specific category id . suppose if you have a category id = 26 then all 26 category posts display in foreach loop.
on that related posts first image display which you enter in posts.
Thank you.