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.
Related
I have this code where I'm trying to display all three images attached to visual composer's custom "attach_images" element type that has param "macimgs". The problem is that only the last one image will display and if I inspect the container that holds images, I see only one image inside instead of three.
Any ideas of what to modify here?
$gallery = shortcode_atts(
array(
'macimgs' => 'macimgs',
), $atts );
$image_ids=explode(',',$gallery['macimgs']);
$image_no = 1;
foreach( $image_ids as $image_id ){
$images = wp_get_attachment_image_src( $image_id, 'full' );
$output ='
<img src="'. $images[0] .'" alt="" />
';
$image_no++;
}
return $output;
}
i think you forget to concatenate the $output variable.
try this code
$gallery = shortcode_atts(
array(
'macimgs' => 'macimgs',
), $atts );
$image_ids = explode(',',$gallery['macimgs']);
$output = '';
$image_no = 1;
foreach( $image_ids as $image_id ){
$images = wp_get_attachment_image_src( $image_id, 'full' );
$output .='<img src="'. $images[0] .'" alt="" />';
$image_no++;
}
return $output;
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.
What I want to do
I have a website that uses a CMS I wrote some time ago, and now I am trying to migrate it to wordpress.
At the existing implementation, when someone writes a post, they can add some extra images that are shown as a gallery at the end of the post, as you can see in this page for example (sorry for non english page): http://apollonpatras.gr/news/562/i-bradia-ton-xorigon-parousiasi-xorigikou-programmatos-kai-eisitirion-diarkeias/.
How I think I can do it
I am thinking about letting the users create wordpress galleries and at post save time intercept the post contents and store the gallery image ids in a postmeta field so I can show them however I want.
Also, I will have to strip the galleries from the content before they are shown, since I will show them in my own way later.
What I am trying so far
add_filter('content_save_pre', 'intercept_galleries', 99);
function intercept_galleries($content) {
if (get_post_type() !== 'post') {
return $content;
}
if (has_shortcode($content, 'gallery')) {
// The [gallery] short code exists.
$a = get_post_gallery(0, false);
update_post_meta(get_the_ID(), 'has_gallery', 1);
update_post_meta(get_the_ID(), 'gallery_items', $a['ids']);
} else {
update_post_meta(get_the_ID(), 'has_gallery', 0);
update_post_meta(get_the_ID(), 'gallery_items', "");
}
return $content;
}
add_filter('the_content', 'remove_shortcodes_from_content');
function remove_shortcodes_from_content($content) {
return strip_shortcodes($content);
}
Where it goes wrong
Looks like when the post is originally saved, the postmeta field "has_gallery" is set to 1, but the field "gallery_items" is empty.
When I go to the wordpress editor and just hit update, the fields are absolutely correct.
Also the hook to remove shortcodes from the content is working.
What am I looking for
How can I fix this problem? Also, is there something wrong/stupid with the way I decided to do this? Would some other way be cleaner/easier/faster etc?
Thank you for your time
I've done this a few times and here's how I do it.
First I create a function that will display the gallery in the way that I want. You can modify this according to how you require you gallery markup to be:
function my_gallery_shortcode( $attr ) {
$post = get_post();
if ( ! empty( $attr['ids'] ) ) {
$attr['include'] = $attr['ids'];
}
extract( shortcode_atts( array(
'order' => 'ASC',
'orderby' => 'post__in',
'id' => $post->ID,
'columns' => 3,
'size' => 'large',
'include' => '',
), $attr));
$id = (int) $id;
$columns = (int) $columns;
if ( 'RAND' == $order ) {
$orderby = 'none';
}
if ( ! empty( $include ) ) {
$_attachments = get_posts( array( 'include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby ) );
$attachments = array();
foreach ( $_attachments as $key => $val ) {
$attachments[$val->ID] = $_attachments[$key];
}
}
if ( empty( $attachments ) ) {
return '';
}
$output = '<div class="slideshow"><ul>';
foreach ( $attachments as $id => $attachment ) {
$thumb = wp_get_attachment_image_src( $id, 'large', false );
$output .= '<li><img src="' . $thumb[0] . '" width="' . $thumb[1] . '" height="' . $thumb[2] . '" alt="' . get_post_meta( $id, '_wp_attachment_image_alt', true ) . '" /></li>';
}
$output .= '</ul></div>';
return $output;
}
You can complicate or simply the function above according to your requirements.
Then in your theme's functions.php add this:
add_shortcode( 'gallery', 'my_gallery_shortcode' );
Now you have two choices:
1) You can allow your user to add a gallery to the main page content by way of them editing the page in question and going to Media > Create Gallery
This will insert the gallery short code which will be formatted according to your function my_gallery_shortcode(), however the gallery can be managed via WordPress's gallery functionality in the admin area and is stored in the database by WordPress in the conventional way.
or
2) You could create a separate WYSIWYG field either through additional code in your functions.php file, or by using a plugin such as Advanced Custom Fields. You would then use this additional WYSIWYG field to allow the user to insert the gallery shortcode in the same way as above. This is virtually the same as option 1 above but you'd have more flexibility as to where you output and position the gallery on the page.
I hope this helps anyone looking to do the same thing.
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
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.