Wordpress get the first attached image on the post - php

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.

Related

Wordpress media library custom taxonomy get image

I am using this code here to get images from media library using custom taxonomy. It gets the image url fine, but I want to get image id and title. How do I do that?
This is what I have so far.
function get_images_from_media_library($cat) {
$args = array(
'post_type' => 'attachment',
'post_mime_type' =>'image',
'post_status' => 'inherit',
'posts_per_page' => 6,
'orderby' => 'rand',
'tax_query' => array(
array(
'taxonomy' => 'gallery-category',
'field' => 'slug',
'terms' => $cat
)
)
);
$query_images = new WP_Query( $args );
$images = array();
foreach ( $query_images->posts as $image) {
$images[]= $image->guid;
echo $image->ID; // Returns image ID, but I need it in display_images_from_media_library function
}
return $images;
}
function display_images_from_media_library($cat) {
$imgs = get_images_from_media_library($cat);
foreach($imgs as $img) {
$html .= '<img src="' . $img . '" alt="">';
}
return $html;
}
get_images_from_media_library() returns an array of image URLs therefore display_images_from_media_library() never has access to anything other than those URLs. If you wish to access the ID and title as well you'll need to make a couple of updates.
Inside get_images_from_media_library(), change this:
$images = array();
foreach ( $query_images->posts as $image) {
$images[]= $image->guid;
echo $image->ID; // Returns image ID, but I need it in display_images_from_media_library function
}
return $images;
To this:
return $query_images->posts;
The original code looped through the images and added their URLs to a new array. Here we're going to return the images in their original form.
Then we need to update the function that uses those images.
Change this:
$html .= '<img src="' . $img . '" alt="">';
To this:
$html .= '<img src="' . $img->guid . '" alt="">';
In my answer I've modified the code you've written to arrive at the desired result. I would however advise that you change the way you're retrieving the images in the first place. WP_Query isn't the most efficient way of handling it. Consider get_posts() instead.

Showing image caption only if caption exists - Wordpress

I found a really helpful discussion here that outlines how to display the image caption, alt, title, etc. I've tested this function, and it works well, but for the images that don't have captions, the div for the caption still displays. How would I go about making this function display nothing, if there's no caption available?
function the_post_thumbnail_caption() {
global $post;
$thumb_id = get_post_thumbnail_id($post->id);
$args = array(
'post_type' => 'attachment',
'post_status' => null,
'post_parent' => $post->ID,
'include' => $thumb_id
);
$thumbnail_image = get_posts($args);
if ($thumbnail_image && isset($thumbnail_image[0])) {
//show thumbnail title
echo $thumbnail_image[0]->post_title;
//Uncomment to show the thumbnail caption
//echo $thumbnail_image[0]->post_excerpt;
//Uncomment to show the thumbnail description
//echo $thumbnail_image[0]->post_content;
//Uncomment to show the thumbnail alt field
//$alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true);
//if(count($alt)) echo $alt;
}
}
if ($thumbnail_image[0]->post_excerpt != '')
{
echo $thumbnail_image[0]->post_excerpt;
}

How to get the first image from post?

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

Wordpress Custom fields display file URL

I have the following code and need to show THREE things from my custom post type called fact-sheet.
The Title
The summary (fact_sheet_summary)
A file upload URL (fact_sheet_pdf_link)
I can get the first two to work but no idea how to do the third.
Basically my output should be...
The Title
The Summary paragraph
Click here to download as PDF
Any ideas how I can query to list all of these post type results? Is there a better way to do this rather than what I have below? The main problem is, I can't get the URL of the uploaded file.
<?php
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'fact-sheet',
'order' => 'ASC',
));
if($posts)
{
foreach($posts as $post)
{
echo '<span class="fact-sheet-title">' . get_the_title($post->ID) . '</span><br />';
echo '<p><span class="fact-sheet-summary">' . the_field('fact_sheet_summary') . '</span></p>';
}
}
?>
I think It's better to use query_posts() as you can use The Loop default structure.
As for the custom fields (Using ACF Plugin), you're using the_field(), which automatically echoes the retrieved field value. You can use, in other hand, the get_field() function, which just returns the value of the field.
You could do something like this:
// Query all posts from 'fact-sheet' post_type
query_posts(array(
'numberposts' => -1,
'post_type' => 'fact-sheet',
'order' => 'ASC',
// Getting all posts, limitless
'posts_per_page' => -1,
));
// Loop throught them
while(have_posts()){
the_post();
echo '<span class="fact-sheet-title">' . get_the_title() . '</span><br />';
echo '<p><span class="fact-sheet-summary">' . get_field('fact_sheet_summary') . '</span></p>';
// Echos the link to PDF Download
echo '<p>Click here to download as PDF</p>';
}
// Once you're done, you reset the Default WP Query
wp_reset_query();
In case you might need further explanation about wp_reset_query(), check this out.
Can you try this? It's slightly modified from the manual of the WP Codex (not much)
<ul>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
$args = array(
'post_type' => 'attachment',
'post_mime_type' => array('application/pdf'),
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post->ID
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo '<li>';
the_attachment_link( $attachment->ID, true );
echo '<p>';
echo apply_filters( 'the_title', $attachment->post_title );
echo '</p></li>';
}
}
endwhile; endif; ?>
</ul>
If it works, maybe it's better to modify a working sample to your needs - by adding your custom fields. Just my thoughts :-)

PHP preg_match_all with Wordpress to echo a image if more than 1 image in post

Basically what I am looking to accomplish is if there is more than 1 img it will echo the below statement so I can basically have a rollover saying click to see more. Another question would be how would I have it link to the post itself if I were to change it to 'a href' and echo out the permalink to post_id.
Any help would be very much appreciated.
function catch_images() {
global $post, $posts;
$first_image = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/ii', $post->post_content, $matches);
$first_image = $matches [2] [0];
if ($output == '2') {
echo '<div class="seemore"><img src="images/magglass.png"></div><div class="seemoretext">See More</div>';
}
}
Well I feel stupid, I should of just put the following:
if ($output > '2') {
Why don't you do something like this to check the number of attached images in your post? This assumes that your images are attached to your post, though.
Well, As said in comment , I did not really understood what you want to link if it has more than 2 images , to the image itself ?? to attachment page ? to another post ?
anyhow, something like this should work - read and execute the comments to suit your needs ..
(the second question I did not understood ...)
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => 'published', // or NULL
//'post_mime_type' => 'image', // only if you want images alone
'post_parent' => $post->ID
);
$attachments = get_posts($args);
$counter = 0;
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
if (!$counter == 1) {
echo wp_get_attachment_image($attachment->ID);
}
else {
// uncomment the following line if you want a LIST of all following attachments and then delete the marked line
//echo '<a href = ' . wp_get_attachment_url($attachment->ID) . '> see more (image'. $counter .') </a>' ;
}
++$counter;
}
// Delete this line if you have more than 2 images, otherwise it will show the last one only
echo '<a href = ' . wp_get_attachment_url($attachment->ID) . '> see more (image'. $counter .') </a>' ;
}
The following is the answer to my own question, it will echo if there is more than 1 img src tag in a given post.
function catch_images() {
global $post, $posts;
$first_image = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/ii', $post->post_content, $matches);
$first_image = $matches [0] [1];
if ($output > '2') {
echo '<div class="seemore"><div class="seemoreimg"><img src="images/magglass.png"></div><div class="seemoretext">See More</div></div>';
}
}
Thanks everyone for your help!

Categories