Elli Elli - 26 days ago 9
PHP Question

Get images by a slug in Wordpress

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');?>

Answer

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><a href="' . get_the_content() . '">' . get_the_excerpt() . '</a></p></li>';
                    }
                }
            } else {
                // no attachments found
            }

            wp_reset_postdata();
Comments