Get image by name in wordpress - php

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.

Related

WordPress mouse over text with background color?

I m new to wordpress and using 4.2.2 version. I need to show mouse over background color with text on image. The given text and images are generating dynamically from the admin panel. I have given the below images for your reference, first image right now im having my site, and next image I need to do like that.
Thanks in advance!
You can use this function for wordpress
<?php wp_get_attachment_image( $attachment_id, $size, $icon, $attr ); ?>
or
<?php wp_get_attachment_metadata( $attachment_id, $unfiltered ); ?>
Here is the codex
https://codex.wordpress.org/Function_Reference/wp_get_attachment_image
https://codex.wordpress.org/Function_Reference/wp_get_attachment_metadata
With this u can get the name of the image and show like the Sagar said
You'll use this in your page, not in yout functions.php
U won't be this in the functions, you'll use this in your page, like this
<?php
$my_query = new WP_Query('post_type=eventos&category_name=galeria_evento&posts_per_page=1');
while ($my_query->have_posts()) : $my_query->the_post();
?>
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'attachment',
'post_parent' => $post->ID,
'numberposts' => -1,
'paged' => get_query_var('paged'),
'exclude' => get_post_thumbnail_id()
);
// making the list of the attachments
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
// getting the image and title of the attachment
echo "<div class='item-slide'><p class='title-slide'>".apply_filters( 'the_title', $attachment->post_title )."</p>".wp_get_attachment_image( $attachment->ID, 'full' )."</div>";
}
}
?>
<?php endwhile; ?>

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.

PHP function get the last inserted data in the array

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

Categories