Here is a useful trick. Want to call or echo an image into your blog post with our using the custom fields? Well this could be tricky, but I know of a way.
All you have to do is print these lines of code into your
index.php
or home.php
inside the loop:
<?php $id =$post->ID; $the_content =$wpdb->get_var("SELECT post_content FROM $wpdb->posts WHERE ID = $id"); $home = get_option('home'); $pattern = '!<img.*?src="'.$home.'(.*?)"!'; preg_match_all($pattern, $the_content, $matches); $image_src = $matches['1'][0]; ?>
then after write:
<?php if($image_src != '') { ?> <a href="<?php echo the_permalink() ?>" rel="bookmark" title="Link to <?php the_title(); ?>"><?php the_title(); ?></a><br /> <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><img src="<?php echo $image_src; ?>" alt="<?php the_title(); ?>" /></a> <?php } ?>
That’s all! This will look for the first image in your post and echo it in the loop, could be used to show off those pretty thumbnails for the post..
Anyone in the Los Angeles area? Well the first Sunday of the month is the…
Steam is powerful, hot, and painful. It can move trains, boats, and has driven minds…
I received a Swekey in the mail this week. What's a Swekey you ask? Like…
React js Developer Skills
At the time of writing this post I have Theme Hybrid as my parent theme,…
What do Software as a Service (SaaS) Companies Do?
View Comments
Assuming the image has been added using the WP uploader, here's a way of doing the same thing using the WP API, which might have a performance advantage:
<?php $attachments = (array) get_children(array('post_parent' => get_the_ID(), 'post_type' => 'attachment'));
if ( ! empty( $attachments ) ) :
$attmt = array_shift($attachments);
$image_thumb = wp_get_attachment_thumb_url($attmt->ID); ?>
<a href="<?php echo the_permalink() ?>" rel="bookmark" title="Link to <?php the_title(); ?>"><?php the_title(); ?></a><br />
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><img src="<?php echo $image_thumb; ?>" alt="<?php the_title(); ?>" /></a>
<?php endif; ?>
Thanks for that one!
This is great script, it helps me a lots!!! Thank you so much!!
I wonder if this script can grab the first image in the post which hosted on share host like: flickr or imagesharkus?
Your welcome, I am not sure. If we could find out details to their database it may be possible.
That can be useful
Nick’s last blog post..Montana Library
Hi all,
First of all, very nice script. I noticed that the output was in html (ie, img src and thumbnailing).
Does anyone know of any snippet to be able to echo the image via php, without having to name the actual individual image file (eg. tree.jpg), and instead using a variable from a database that names photos in a directory.?
thanks
tom
Thanks for the tip, liked it!
.-= Maor´s last blog ..וורדפרס 2.8+: איך לא להציג קטגוריות מסוימות בתפריט הצדדי? =-.