WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Custom Query help needed! (4 posts)

  1. pshero
    Member
    Posted 2 years ago #

    Hey gang,
    I'm trying to make a custom query of related posts by category, which works fine, but I'd also like to only include posts that have a post image (featured image) set. My query is pasted below, can anyone see what I'm doing wrong?

    // get other (random) posts from this category only as related posts //
    	$backup = $post;  // backup the current object
    	$categories = get_the_category($post->ID);
    		if ($categories) {
    			$category_ids = array();
                            foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
    
    	$args = array (
    		'category__in' => $category_ids,
    		'post__not_in' => array($post->ID),
    		showposts'=>10, // Number of related posts that will be shown.
    			'orderby'=>'rand',
    			'caller_get_posts'=>1,
    			'post_image'=>true
    			);
    
    	$my_query = new wp_query($args);
    	if( $my_query->have_posts() ) {
    	while ($my_query->have_posts()) : $my_query->the_post();
  2. Spike
    Member
    Posted 2 years ago #

    Probably a better way to do this, but inside the post, you could do something like this:

    <?php
    $thumbcheck = get_the_post_thumbnail();
    if ($thumbcheck == “”) {
    //do nothing
    } else {
    //post content
    }
    ?>
  3. pshero
    Member
    Posted 2 years ago #

    Thanks rdlucas2, but this isn't for the post itself, this query pulls a list of related posts into a div at the end of the current post (on a single post page), which is why the filter needs to happen within the new query.

  4. pshero
    Member
    Posted 2 years ago #

    I was able to solve this problem by replacing the query item:

    'post_image'=>true

    with

    'meta_key' => '_thumbnail_id'

    Not sure if it's right, but it worked for me.

Topic Closed

This topic has been closed to new replies.

About this Topic