Support » Plugins and Hacks » Hacks » [Resolved] Query posts with attachments by category

[Resolved] Query posts with attachments by category

  • I’m attempting to pull media from posts by category and the media is showing up, it’s just not by category. It’s currently ALL media regardless of whether or not it’s attached to a post. I’m having trouble figuring out what to do.

    <div class="row-fluid">
    global $post;
    $args = array(
    'post_category' => 'trees',
    'post_type' => 'attachment',
    'numberposts' => 8,
    'orderby' => 'random',
    'post_status' => null,
    'post_parent' => null, // any parent
    $attachments = get_posts($args);
    foreach ($attachments as $post) : setup_postdata($post); ?>
    <div class="span3">
Viewing 15 replies - 1 through 15 (of 20 total)
  • esmi


    Forum Moderator

    Try changing 'post_category' => 'trees', to 'category_name' => 'trees',. There is no post_category attribute.

    I’ve tried that and it’s caused the images to disappear completely. Here is the page in question if it helps. http://www.nashvillebonsai.com/




    Forum Moderator

    Try reviewing the list of available parameters.

    Assuming unattached attachments (say what?) have the post_parent field set to 0 (confirm this), you need a query fragment that reads $wpdb->posts.post_parent != 0. There is no way to do this using WP_Query arguments. But you could supply 'post_parent' => 0, (resulting in $wpdb->posts.post_parent = 0) and then use the ‘posts_where’ filter to change the = operator to !=.

    This should result in only attachments that are attached to a post.

    I’m slipping here a little bit. I spent the better part of my day (and night) tinkering with this. Although I have a fundamental understanding of manipulating the for loop and object oriented programming I can’t write PHP straight-up yet.

    I’ve tried 3 different solutions that I found researching this issue online and none have nailed it yet. One, allowed me to query global posts within a category and successfully provided a permalink wrapped around the title. I then piggy-backed this solution to echo the content, but that’s not exactly what I want because it includes any and all text as well. Plus, when querying the media attachments directly, I’m able to take advantage of the lightbox plugin to display them nicely and they are automatically resized as well.

    Here’s a screenshot of what I mean (since by the time this is read I’ll no doubt be tinkering with it again http://cl.ly/image/16032N2R2B18)

    This is the relative, final product I’m looking for. I actually thought I had it working before, until I uploaded the Google SSL image and noticed it showed up on the homepage.

    I think the problem I’m having is that I can’t filter my attachment query properly against anything usable to ONLY show uploaded attachments that were used on Category – 4 i.e. – ‘Trees’ posts. On the flipside, I can’t sort out how to ONLY pull the attachments within a post when I query the posts. I’ve just had luck yet.

    bcworkz, I am not sure I understand the solution you suggested. I’ve reread it multiple times. I just think it’s still above my pay grade right now. 🙁

    Yes, on re-reading my suggestion it is extremely terse, sorry about that. It was late and I didn’t want to get into a lengthy explanation. I’m not even totally sure it is the correct solution though it has much promise. I would have liked to test this more thoroughly but I currently cannot access my test installation.

    It would be a good solution if it works, but you may be able to cobble some brute force solution, depending on the nature of your attachments. For instance, query for much more than the 8 needed attachments then check each one for a parent before outputting only those that do. Should work most of the time. Or perhaps query several posts at random and grab whatever attachments they may have. Success is a matter of odds, but you can stack the odds by over querying the data you need so you can get enough results almost every time.

    Another approach, if you can construct a proper mySQL query string, is to simply query the DB directly with $wpdb methods, bypassing WP_Query entirely.

    My two cents: it seems you would have to first query for posts by category (‘post_type’ => ‘post’, ‘category_name’ => ‘trees’), then for each post that is found, query for its attachments (‘post_type’ => ‘attachments’, ‘post_parent’ => $post->ID). Then display each attachment as thumbnails, linked to full-size with lightbox.

    What may help is get_children: Display all images attached to post page

    Or, you can see this method: Function to get attachment details

    Thanks for helping me along. I have got the exact interaction I’m looking for up and running here: http://www.nashvillebonsai.com *under gallery.

    Note the lightbox when clicking. This is what I want.

    However, it’s simply not automated enough. I achieved this by doing the following:

    							global $post;
    							$args = array(
    							    'post_type' => 'attachment',
    							    'numberposts' => 8,
    							    'orderby' => 'random',
    							    'is_category' => 4,
    							    'post_status' => 'published',
    							    'post_parent' => 212, // any parent
    							$attachments = get_posts($args);
    							foreach ($attachments as $post) : setup_postdata($post); ?>
    						 	<div class="span3">
    						 		<?php the_content(); ?>
    						<?php endforeach; ?>

    As you can see, the only reason it works now is because I put in a post ID. I need it to pull attachments for all posts in category 4.

    It looks like that link you shared with me is what I need, but unfortunately, I couldn’t sort out how to make it happen.

    I see.. The code you pasted there should be included inside another query loop which gets all posts of the category you want. Then you can pass each post ID as post_parent.

    Here’s an attempt at “blind-coding”, you may have to adjust it to work on your end.

    // Get posts by category name
    	$my_category_name = "tree";
    	$my_query = new WP_Query( array(
    		'cat' => get_category_by_slug($my_category_slug)->term_id,
    		'post_type' => 'any',
    	if( $my_query->have_posts() ) {
    		// For each post found..
    		while ( $my_query->have_posts() ) {
    			// Get its attachments..
    			$new_children =& get_children( array (
    				'post_parent' => get_the_ID(),
    				'post_type' => 'attachment',
    				'post_status' => 'any'
    			) );
    			foreach( $new_children as $attachment_id => $attachment ) {
    				$attachment_ids .= $attachment_id . " ";
    			$attachment_ids = explode(" ", trim( $attachment_ids ) );
    			$output = '';
    			// For each attachment, output thumbnails with links to full-size
    			foreach ( $attachment_ids as $attachment_id ) {
    				$output .= '<div class="span3">';
    					$output .= '<a href="';
    					$output .= wp_get_attachment_image_src( $attachment_id, "full" );
    					$output .= '" rel="lightbox">';
    					$output .= wp_get_attachment_image( $attachment_id, 'thumbnail' );
    					$output .= '</a>';
    				$output .= '</div>';
    			echo $output;

    By the way, are you doing this inside a post or page? If so, I may have a much easier shortcode solution.

    I’m doing this inside of the page template. *So far I’m getting an ‘unexpected $end’ error. I’m going to keep analyzing this. I have a lot to learn so I appreciate your patience.

    Apparently that error happens when there’s a closing quote, bracket, parenthesis or comma missing. I looked over the above code but couldn’t find it. Probably a missing } somewhere.. Also, the whole thing should be between <?php and ?>.

    Oh! I see on the 4th line, the variable $my_category_slug should be $my_category_name. Sorry, a simple mistake on my part.

    *Update: ALMOST there! You’re awesome for helping me out. I’ve made some modifications mostly just typos and it’s there now, but the final frontier is getting the content loaded into the lightbox which is currently failing.

    Ah, I see that wp_get_attachment_image_src() returns an array, not just the image URL. Maybe wp_get_attachment_url( $attachment_id ) would do instead?

Viewing 15 replies - 1 through 15 (of 20 total)
  • The topic ‘[Resolved] Query posts with attachments by category’ is closed to new replies.