WordPress.org

Ready to get started?Download WordPress

Forums

Get posts category from only one parent (6 posts)

  1. cip6791
    Member
    Posted 6 months ago #

    I'm not sure how to return only the children categories that belong to cat 406. My code returns 10 posts from cat 406, but some of those posts are in a child cat of 406 but sometimes are in another category as well.

    Can I somehow check if '$post_cat[0]->slug' belongs to cat 406?

    echo '<ul class="artist-thumbs">';
    
      $thumbnails = get_posts('posts_per_page=10&cat=406');
    
        foreach ($thumbnails as $thumbnail) {
    
          $post_cat = get_the_category( $thumbnail->ID );
    
          echo '<li><a class="side-thumb" href="' . get_permalink( $thumbnail->ID ) . '" title="' . esc_attr( $thumbnail->post_title ) . '">';
    
    if ( has_post_thumbnail($thumbnail->ID)) {
        echo get_the_post_thumbnail($thumbnail->ID, 'thumbnail');
    
    	$upload_dir = wp_upload_dir();
    	$art_image = ''.$upload_dir['basedir'].'/icons/'.$post_cat[0]->slug.'.png';
    
    	if (file_exists($art_image)) {
    
    	  echo '<p class="artist-latest"><img src="http://dailydoseoftattoos.com/wp-content/uploads/icons/'.$post_cat[0]->slug.'.png" alt="'.$post_cat[0]->slug.'"/>'.$post_cat[0]->name.'</p>';
    
    	}else{
    
    	    echo '<p class="artist-latest">'.$post_cat[0]->name.'</p>';
    
    				}
    
    } else {
    
    }
     echo '</a></li>';
    
    			  }
    
    	echo '</ul>';
  2. alchymyth
    The Sweeper & Moderator
    Posted 6 months ago #

    return only the children categories that belong to cat 406

    only posts directly in cat 406, or only posts directly in a child category of 406?

    http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters

    this will only return posts directly in cat 406:

    $thumbnails = get_posts(array( 'posts_per_page' => 10, 'category__in' => array(406) ));

  3. cip6791
    Member
    Posted 6 months ago #

    If I do do that it doesn't return anything.

    var_dump($thumbnails); = array(0) { }

  4. alchymyth
    The Sweeper & Moderator
    Posted 6 months ago #

    from what category do you want to get the posts?

    do you have posts directly in category 406?

  5. cip6791
    Member
    Posted 6 months ago #

    No, posts are in children of category 406

  6. alchymyth
    The Sweeper & Moderator
    Posted 6 months ago #

    try to get the child categories of 406 and use them in the get_posts() code with the 'category__in' parameter;

    example:

    $child_cats = get_categories( array( 'parent' => 406 ) );
    $child_cats_ids = array();
    if( $child_cats ) foreach( $child_cats as $ids ) { $child_cats_ids[] = $ids->term_id; }
    $thumbnails[] = get_posts(array( 'posts_per_page' => 10, 'category__in' => $child_cats_ids ));
    
    if( $thumbnails && $child_cats ) foreach ($thumbnails as $thumbnail) {

    etc........

Reply

You must log in to post.

About this Topic