WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Query posts with attachments by category (21 posts)

  1. madphill
    Member
    Posted 10 months ago #

    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">
    <?php
    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">
  2. esmi
    Forum Moderator
    Posted 10 months ago #

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

  3. madphill
    Member
    Posted 10 months ago #

    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/

    Thanks!

  4. esmi
    Forum Moderator
    Posted 10 months ago #

    Try reviewing the list of available parameters.

  5. bcworkz
    Member
    Posted 10 months ago #

    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.

  6. madphill
    Member
    Posted 10 months ago #

    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. :(

  7. bcworkz
    Member
    Posted 10 months ago #

    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.

  8. Eliot Akira
    Member
    Posted 10 months ago #

    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.

  9. Eliot Akira
    Member
    Posted 10 months ago #

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

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

  10. madphill
    Member
    Posted 10 months ago #

    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:

    <?php
    							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(); ?>
    							</div>
    						<?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.

  11. Eliot Akira
    Member
    Posted 10 months ago #

    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() ) {
    			$my_query->the_post();
    
    			// 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.

  12. madphill
    Member
    Posted 10 months ago #

    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.

  13. Eliot Akira
    Member
    Posted 10 months ago #

    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 ?>.

  14. Eliot Akira
    Member
    Posted 10 months ago #

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

  15. madphill
    Member
    Posted 10 months ago #

    *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.

  16. Eliot Akira
    Member
    Posted 10 months ago #

    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?

  17. madphill
    Member
    Posted 10 months ago #

    The lightbox is working, but the URL appears wrong. It's nashvillebonsai.com/Array

  18. Eliot Akira
    Member
    Posted 10 months ago #

    Hmm.. How about replace this line:

    $output .= wp_get_attachment_image_src( $attachment_id, "full" );

    with:

    $src = wp_get_attachment_image_src( $attachment_id, "full" );
    $output .= $src[0];

    That should get the first item in the array which is the URL.

  19. madphill
    Member
    Posted 10 months ago #

    I have no words to thank you. I've learned a lot (even though it may not seem that way). I'll be breaking this down and studying it for a while I'm sure. You've done it!

    Thanks so much for all your help.

  20. Eliot Akira
    Member
    Posted 10 months ago #

    Glad to hear it worked! Very nice looking website, by the way. I came across this thread by chance because of someone else who helped me with an issue, so I wanted to pass along the community goodness.

    Recently I've been working on a small plugin which (at least for me) simplifies the query and display of a variety of content, including attachments. It's called Custom Content Shortcode in the WordPress repository, if you're curious.

  21. madphill
    Member
    Posted 9 months ago #

    Very cool. I've favorited it and will check it out!

Reply

You must log in to post.

About this Topic