PHP function get the last inserted data in the array - php

I know you guys going to say this might be possible duplicate to PHP get index of last inserted item in array
But I've tried and not succeed to get my function work and I'm trying to figure it out why.
I've a function which will grab the thumbnail attachment from the content of Wordpress post.
The code working fine with a post that have only one image, but if there are more than one image in the post it will display the first image correctly from the array, but I don't know why it stores the image in reverse. Meaning the first image of the post stored last and the last store first. I'm geussing this is maybe how the media function of Wordpress work.
Anyway I just need to get the last inserted data from function even if it has one or more than one image stored in the array
// Get Image Attachments
function sa_get_image($postid=0, $size='thumbnail') {
if ($postid<1)
$postid = get_the_ID();
$thumb = get_post_meta($postid, "thumb", TRUE);
if ($thumb != null or $thumb != '') {
echo $thumb;
}
elseif ($images = get_children(array(
'post_parent' => $postid,
'post_type' => 'attachment',
'numberposts' => '1',
'post_mime_type' => 'image', )))
foreach($images as $image) {
$thumbnail=wp_get_attachment_image_src($image->ID, $size);
?>
<?php echo $thumbnail[0]; ?> // here is the problem where the image display.
<?php }
}

change:
$thumbnail=wp_get_attachment_image_src($image->ID, $size);
to:
$thumbnail[] = wp_get_attachment_image_src($image->ID, $size);
don't forget to declarate $thumbnail = array() outside the for-each.
and then you can use (preferred):
echo end($thumbnail);
or something like:
echo $thumbnail[count($thumbnail)-1];
If you wan't to get the 'last' appended value.
Or you can use [0] or first() to get the first value
You can add it here (ex.):
$thumb = get_post_meta($postid, "thumb", TRUE);
$thumbnail = array(); //<<<
if ($thumb != null or $thumb != '') {

You are accessing $thumbnail as an array but you are overwriting the variable inside your foreach() as if it was a string.
Change:
$thumbnail=wp_get_attachment_image_src($image->ID, $size);
to
$thumbnail[]=wp_get_attachment_image_src($image->ID, $size);
to make it an array then the rest of your code should work
AH

There is an easier method to my solution and here is how we can get the last from the array.
Simply just add this to the array area.
'orderby' => 'menu_order',
'order' => 'ASC', //If reverse use DESC

Related

Get image by name in wordpress

i want to make a custom background image, witch will be changed every day, with url to original source.
for example :
img name 346.jpg
$dayofyear = date('z');
$dayofyear = Get image by name in wp?
background-image: url(<? php echo $dayofyear; ?>)
thx, and sorry for my English :D
Each image you upload to the media library uses the filename before the extension as it's slug.
You can use the get_posts function and pass in $dayofyear:
function get_attachment_url_by_slug( $slug ) {
$args = array(
'post_type' => 'attachment',
'name' => sanitize_title($slug),
'posts_per_page' => 1,
'post_status' => 'inherit',
);
$_background = get_posts( $args );
$background = $_background ? array_pop($_background) : null;
return $background ? wp_get_attachment_url($background->ID) : '';
}
That will return the ID of the image you're trying to get by it's slug.
If you're doing this inside a page or post template, you would use:
$dayofyear = date('z');
$background_url = get_attachment_url_by_slug($dayofyear);
Then set the inline style of the element, for example:
<div style="background-image: url(<? php echo $background_url; ?>);"></div>
This won't work if you're trying to inject this into a stylesheet.

Get a single specific image from Wordpress Media Library

I've uploaded images to Wordpress Media Library.
I understand that I can view am image then get the URL for that specific image and then use the img html tag to display this on the page.
This however doesn't get the alt, title, caption and description of the image.
The img is not attached to a post or page field and so i assume you cannot use the Get Attachment function etc.
The reason I want to use a function instead of writing out a static img html code is so that they are cached better and easier to maintain with all data for the image been updated in the Media Library instead of having to edit html code which is not idea for the end user.
thank you in advance.
I presume you have an attachment ID? Have you tried using attachement functions?
From the codex:
Note that media items are also 'Posts' in their own right and can be
displayed as such via the WordPress Template Hierarchy. Themes can
make use of this to loop over media items or create galleries.
The following functions should get you started:
you can retrieve the image src using: wp_get_attachment_image_src()
$img= wp_get_attachment_image_src($attachmentID, $imageSizeName);
you can get the image caption using: get_post_field()
get_post_field('post_excerpt', $attachmentID)
you can get the alt tag using: get_post_meta()
get_post_meta($attachmentID, '_wp_attachment_image_alt', true);
first get image
function get_images_from_media_library() {
$args = array(
'post_type' => 'attachment',
'post_mime_type' =>'image',
'post_status' => 'inherit',
'posts_per_page' => 5,
'orderby' => 'rand'
);
$query_images = new WP_Query( $args );
$images = array();
foreach ( $query_images->posts as $image) {
$images[]= $image->guid;
}
return $images;
}
and display image
function display_images_from_media_library() {
$imgs = get_images_from_media_library();
$html = '<div id="media-gallery">';
foreach($imgs as $img) {
$html .= '<img src="' . $img . '" alt="" />';
}
$html .= '</div>';
return $html;
}
and use php fire event
<?php echo display_images_from_media_library(); ?>
or use this function
<?php
if ( $attachments = get_children( array(
'post_type' => 'attachment',
'post_mime_type'=>'image',
'numberposts' => 1,
'post_status' => null,
'post_parent' => $post->ID
)));
foreach ($attachments as $attachment) {
echo wp_get_attachment_link( $attachment->ID, '' , true, false, 'Link to image attachment' );
}
?>
Please try to below code:
<?php
$attachmentID = 1875;
$imageSizeName = "thumbnail";
$img = wp_get_attachment_image_src($attachmentID, $imageSizeName);
//print_r($img);
?>
<img src="<?php echo $img[0]; ?>" alt="image">
So many complicated and to my opinion wrong answers while the answer is very straight forward:
<?php
$url_to_my_attachment = "http://example.com/wp-content/uploads/image.png";
$attachment_id = attachment_url_to_postid($url_to_my_attachment);
print wp_get_attachment_image($attachment_id);
For more information have a look at wp_get_attachment_image
Note: this renders a "responsive image" where the alt attribute contains the alt data of the attachment. Thus this answer doesn't completely satisfy the OP's request which also demands to include the title, description and caption fields. See the accepted answer or other answers on how to include these other fields.

Echo single image attachment title in wordpress

I was wondering what is the exact code to be able to get the title on the attachment image page. Here is the code I have right now in my image.php file for the title portion.
<h2><?php echo get_the_title($post->post_parent); ?> <?php echo ' ยป $attachment->post-title'; ?></h2>
So I want it to show the main post title then the double right arrow and then the single image title but the $attachment->post-title is not the correct command for this.
I am trying this on my test site. Here you can see the exactly what I am referring to. http://pandafeed.net/gave-her-a-bath-and-tucked-her-in-she-passed-out-right-away/thumbnail-for-1407/
Thanks in advance
This should fetch the title for each post's first attached image on the front page (or any post that's part of a list):
<?php
if (! is_singular()) {
$image_id = get_the_ID();
// Not necessary, but it's an option:
//$permalink = get_permalink($image_id);
$args = array(
'post_type' => 'attachment',
'numberposts' => 1,
'post_parent' => $image_id
);
$attachments = get_posts($args);
if ($attachments) {
$title = get_the_title($attachments[0]->ID);
print $title;
}
}
?>

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.

Get last section from echo and store in variable PHP

I've a function that will echo the URL of the image from the content of Wordpress.
I got the function work now no problem
// Get Image Attachments
function sa_get_image($postid=0, $size='thumbnail') { //it can be thumbnail or full
if ($postid<1)
$postid = get_the_ID();
$thumb = get_post_meta($postid, "thumb", TRUE); // Declare the custom field for the image
if ($thumb != null or $thumb != '') {
echo $thumb;
}
elseif ($images = get_children(array( //If you upload an image function gets first image
'post_parent' => $postid,
'post_type' => 'attachment',
'numberposts' => '5',
'post_mime_type' => 'image', )))
foreach($images as $image) {
$thumbnail=wp_get_attachment_image_src($image->ID, $size);
?>
<?php echo $thumbnail[0]; ?>
<?php }
else { //If you don't upload or declare as thumb custom field func. gets custom (default) image
echo get_bloginfo ( 'template_directory' ); //same as wp-content/themes/your-theme/
echo '/images/image-pending.gif'; // Put this image into your themes images folder and set the path here
}
}
The only problem now is that the <?php echo $thumbnail[0]; ?> if there are more than one image it will echo all of them something like this
<img src=" http://applesiam.com/wp-content/uploads/2555-05-02_19h14_34-150x150.png http://applesiam.com/wp-content/uploads/2555-05-02_19h14_11-150x150.png http://applesiam.com/wp-content/uploads/2555-05-02_19h13_43-150x123.png http://applesiam.com/wp-content/uploads/2555-05-02_19h13_20-150x150.png http://applesiam.com/wp-content/uploads/2555-05-02_19h13_17-150x150.png ">
As you can see it just separated by some spaces.
Now I just want to have the last image if there is more than one image in the $thumbnail
I'm not really expert with PHP as my semester for PHP course will start next week.
Thanks in advance for any suggestion going to be.
Try:
$imgSrc = end((explode(' ', trim($imgSrc)));
Where $imgSrc is the value you put into <img src="!!!==>>here<<==!!!">.
quickly typed, w/o any warranty. Should leave single URLs intact, and if multiple ones separated by space(s) will take the last.
Try this instead.
echo trim($thumbnail[sizeof($thumbnail)-1]);

Categories