Get images by a slug in Wordpress - php

I am fairly new to Wordpress and I am trying to make a function that loads images under a media category. The media category has a slug that I want to pass into the function. If there is an easier way to do this please let me know. Below is my code so far:
Functions.php
function get_image_by_slug($slug) {
$query_images_args = array(
'post_type' => 'attachment',
'post_mime_type' =>'image',
'post_status' => 'inherit',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'attachment_category',
'field' => 'slug',
'terms' => $slug,
),
),
);
$query_images = new WP_Query( $query_images_args );
$images = array();
foreach ( $query_images->posts as $image) {
$images[]= $image->guid;
}
return $images;
}
function display_image_by_slug() {
$imgs = get_image_by_slug($slug);
$html = '<ul class="list-inline">';
foreach($imgs as $img) {
$html .= '<li><img src="' . $img . '" alt="" /></li>';
}
$html .= '</ul>';
return $html;
}
add_filter('display_slugs','display_image_by_slug');
In page
<?php apply_filter('display slugs', 'test_slug');?>

An attachment of image or file is just a post with the post_status = inherit and the post_type = attachment and it is saved into the wp_post & wp_postmeta , so can be queried with WP_Query or get_posts.
Note: The slug (post_name) is unique per post type.
You have to pass your slug in the query by replacing YOUR-SLUG in this place. &name=YOUR-SLUG
$_head = get_posts('post_type=attachment&name=YOUR-SLUG&posts_per_page=1&post_status=inherit');
$header = $_head ? array_pop($_head) : null;
$header_url = $header ? wp_get_attachment_url($header->ID) : '';
Another Method you can build your own custom function with the help that i have provided below.
function get_attachment_url_by_slug( $slug ) {
$args = array(
'post_type' => 'attachment',
'name' => sanitize_title($slug),
'posts_per_page' => 1,
'post_status' => 'inherit',
);
$_head = get_posts( $args );
$header = $_head ? array_pop($_head) : null;
return $header ? wp_get_attachment_url($header->ID) : '';
and then you can call using this function.
$header_url = get_attachment_url_by_slug('YOUR-SLUG');

So after looking around the Wordpress docs and understanding Naresh's answer I was able to come up with my own answer. Here it is...
$id = 'YOUR SLUG';
$args = array(
'post_type' => 'attachment',
'post_status' => 'any',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'media_category', // your taxonomy
'field' => 'slug',
'terms' => $id // term id (id of the media category)
)
)
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>'. wp_get_attachment_image( get_the_ID() );
if(empty_content(get_the_content())){
echo '<p>' . get_the_excerpt() . '</p></li>';
} else {
echo '<p>'.get_the_excerpt().'</p></li>';
}
}
} else {
// no attachments found
}
wp_reset_postdata();

Related

How to add category option to shortcode

I'm new to creating wordpress shortcodes and have one just about working the way I want. Missing something specific. Currently I am able to put the following on any page - [children] and it pulls a query of all posts from the custom post type "children" I would like to add the option to add the category id within the shortcode - something like [children category="8"] Here is the code I have so far:
add_shortcode( 'children', 'display_custom_post_type' );
function display_custom_post_type(){
$args = array(
'post_type' => 'children',
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
);
$string = '';
$query = new WP_Query( $args );
if( $query->have_posts() ){
while( $query->have_posts() ){
$query->the_post();
$string .= '<div id="childWrapper"><div id="childImage">' . get_the_post_thumbnail() . '</div><div style="clear: both;"></div><div id="childName">' . get_the_title() . '</div><div style="clear: both;"></div></div>';
}
}
wp_reset_postdata();
return $string;
}
Secondary - is it possible for it to show posts in multiple categories, but only where the posts are in each of the categories. For example showing a list of children, who fall under a category for critical care and surgery needed.
Any help would be greatly appreciated.
You should refer Shortcode function from WordPress Codex. Assuming your taxonomy name is category, I made some changes in your current code it should work as per your requirements.
/**
* [children category="5,7,8"]
*/
add_shortcode( 'children' , 'display_custom_post_type' );
function display_custom_post_type($atts) {
$atts = shortcode_atts( array(
'category' => ''
), $atts );
//If category is multiple: 8,9,3
$categories = explode(',' , $atts['category']);
$args = array(
'post_type' => 'children',
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page'=> -1,
'tax_query' => array( array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $categories
) )
);
$string = '';
$query = new WP_Query( $args );
if( ! $query->have_posts() ) {
return false;
}
while( $query->have_posts() ){
$query->the_post();
$string .= '<div id="childWrapper"><div id="childImage">' . get_the_post_thumbnail() . '</div><div style="clear: both;"></div><div id="childName">' . get_the_title() . '</div><div style="clear: both;"></div></div>';
}
wp_reset_postdata();
return $string;
}

Get first image of custom post type wordpress

I have this code
function display_categoria($args) {
$query = new WP_Query(array(
'post_type' => 'job_listing',
'post_status' => 'publish',
'posts_per_page' => 5
));
while ($query->have_posts()) {
echo $query->the_post();
$id=get_the_id();
echo $query1=get_permalink();
}
wp_reset_query();
}
add_shortcode( 'este', 'display_categoria' );
in theory i can solve it placing in the loop
if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
but many entries not have a thumbnail (featured images), Can understand?
This should retrieve the url of the first image for each post. Insert it after the "$id=get_the_id();" line
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'posts_per_page' => -1,
'post_status' => null,
'post_parent' => $id
);
$images = get_posts( $args );
if ( $images ) {
$first_image_id = $images[0];
//do something with the image
wp_reset_postdata();
}

Wordpress - display Media Library items based on category

Just like the title says, I'm trying to display only the items in the Media Library that are under a particular category. Whether they're attached to anything or not.
Currently I can get all images, but I'm not sure how to narrow it down to certain categories.
Here's what I have so far:
<select name="event-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value=""><?php echo esc_attr(__('Select Event')); ?></option>
<?php
$args = array(
'hide_empty' => 0,
);
$categories = get_categories($args);
foreach ($categories as $category) {
$option = '<option value="?cat='.get_cat_ID($category->cat_name).'">';
$option .= $category->cat_name;
$option .= ' ('.$category->category_count.')';
$option .= '</option>';
echo $option;
}
?>
</select>
<?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);
if($_GET['cat']){
// not sure what to do here yet
}else{
// this part works fine
foreach ( $query_images->posts as $image) {
echo wp_get_attachment_image($image->ID);
}
}
?>
Can someone enlighten me on how/if this can be done. All I've been able to find is stuff relating to attached images or post images. I just want to pull them directly from the Library.
EDIT Tags would work too. It doesn't have to be category.
unless you're adding a custom meta tag to each image in your media library, your query won't work.
A possible solution
e.g. create a post, name it something relevant, tag all the categories you want this post to be associated with, now dump all the images you want to show into this post.
you can use this query to bump out the post & category terms you want to show, along with the images attached to the post(s).
<?php
$args = array (
'post_type' => 'post',
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => 'your-cat-name-here'
)
)
);
$custom_query = new WP_Query( $args );
if ( $custom_query->have_posts() ):
while ( $custom_query->have_posts() ) :
$custom_query->the_post();
// Do stuff with the post content.
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_parent' => $post->ID,
'exclude' => get_post_thumbnail_id()
) );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$class = "post-attachment mime-" . sanitize_title( $attachment->post_mime_type );
$thumbimg = wp_get_attachment_link( $attachment->ID, 'thumbnail-size', true );
$image_title = $attachment->post_title;
$caption = $attachment->post_excerpt;
$description = $image->post_content;
//print_r($attachment);
echo '<div class="thumbnail"><figure><img src="'.wp_get_attachment_url($attachment->ID).'" /></figure></div>';
}
//End
echo '</div>';
}
endwhile;
else:
// we can insert something if Nothing found.
echo "<h2>Sorry, but there's nothing here.</h2>";
endif;
wp_reset_query();
?>

How to get post id from attachment wordpress

I'm using below code to get all the attachments assign to my custom post type..but now i want to get the post id within the loop..how can i do that??
$query = new WP_Query(
array(
'post_type' => 'portfolio', // adjust your custom post type name here
'posts_per_page' => -1,
'fields' => 'ids'
)
);
$image_query = new WP_Query(
array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'post_mime_type' => 'image',
'posts_per_page' => -1,
'post_parent__in' => $query->posts,
'order' => 'DESC'
)
);
if( $image_query->have_posts() ){
while( $image_query->have_posts() ) {
$image_query->the_post();
$imgurl = wp_get_attachment_url( get_the_ID() );
if(!empty($output)) $output = 'Sorry, no attachments found.';
$output .= '<img src="'.$imgurl.'">';
echo $output;
}
Thanks!
Depending on which ID you are looking for inside the loop, you can do the following
$post-ID -> Returns the post ID from the attachment post being displayed
$post->post_parent -> Returns the current attachment post parent post ID

Wordpress filtering post_mime_type

I have been struggling with this for some time now and would really appreciate some help!
I am trying to populate html5 audio player with 2 codexes in Wordpress media library.
I am using the wp function get_posts and created one filter for post_mime_types 'ogg'. I have set the parameters for post_mime_type in get_posts's $args. Now I want to loop over and sort them into the audio player list as $mp3 and $ogg.
$ogg = wp_get_attachment_url( $audio_attachment->post_mime_type="application/ogg" );
... in the code below but not outputting anything:
<?php
$query_audio_args = array(
'post_type' => 'attachment',
'post_mime_type' =>'application/ogg,audio',
'post_status' => 'inherit',
'posts_per_page' => -1,
);
$audio_attachments = get_posts($query_audio_args);
foreach ( $audio_attachments as $audio_attachment ) {
// Trying to sort them into $ogg, $aif and $mp3
$ogg = wp_get_attachment_url( $audio_attachment->ID);
$mp3 = wp_get_attachment_url( $audio_attachment-ID);
$tracks[] = '{
title:"'.$audio_attachment->post_title.'",
mp3:"'.$mp3.'",
oga:"'.$ogg.'",
aif:"'.$aif.'"
}';
$alltracks = implode(',',$tracks);
}
?>
Edit:
I also tried this, with the intention of creating a multiple array, but got stuck accessing the values:
<?php
$query_audio_args = array(
'post_type' => 'attachment',
'post_mime_type' =>'application/ogg',
'post_status' => 'inherit',
'posts_per_page' => -1,
);
$audio_attachments = get_posts($query_audio_args);
$ogg = array();
foreach ( $audio_attachments as $uk => $uv ) {
$ogg[] = $uv->guid;
}
$query_audio_args1 = array(
'post_type' => 'attachment',
'post_mime_type' =>'audio',
'post_status' => 'inherit',
'posts_per_page' => -1,
);
$audio_attachments1 = get_posts($query_audio_args1);
$mp3 = array();
foreach ( $audio_attachments1 as $ak => $av ) {
$mp3[] = $av->guid;
}
$audio = array(
$ogg,
$mp3
);
print_r($audio);
foreach($audio as $k =>$v)
$tracks[] = '{
title:"'.$uv->post_title.'",
mp3:"'.$mp3->guid.'",
oga:"'.$uv->guid.'",
aif:"'.$aifv->guid.'"
}';
$alltracks = implode(',',$tracks);
?>

Categories