• Resolved Akram Taghavi-Burris

    (@taghaviburris)


    Hello,
    I am currently working on a site where I have two custom post types:

    • Courses
    • Semesters

    What I have a custom template for the Courses post type using single.course.php method.

    For each course page, I display the content of the course post, which in this case is a description of the course.

    Next I create a query to display the semesters posts.

    Because this site also has regular blog posts, I don’t want the semesters and courses to use regular categories.

    So, each course I set up a custom field named course then I set the value to the course number, for example GIT-221

    Next I set the same custom field on my semesters post.

    In short what I want to happen is that each course custom post, will check the current course post custom field and set it’s value to a variable. Then on the same page, run the loop for the semesters posts, if the semester post, custom field value matches the value of the course, then display them.

    Here’s what I have going on right now.

    I use the following code to set the value of the course post custom field to a variable

    <?php
    	 $values = get_post_custom_values("course");
    	if (isset($values[0])) {
    	 $courseVale = $values[0];
    }
    ?>

    Next I run a query to get the semester posts

    <?php
    			$myVale = (string)$courseVale;
    
     $querydetails = "
       SELECT wposts.*
       FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
       WHERE wposts.ID = wpostmeta.post_id
       AND wpostmeta.meta_key = 'course'
       AND wpostmeta.meta_value =  $courseVale
       AND wposts.post_status = 'publish'
       AND wposts.post_type = 'semesters'
       ORDER BY wposts.post_date DESC
     ";
    
     $pageposts = $wpdb->get_results($querydetails, OBJECT)
    
     ?>
    
    <div class="col col-100">
    	<?php if ($pageposts):
     foreach ($pageposts as $post):
           setup_postdata($post); ?>
    
                   <h3><?php the_title(); ?></h3>
                   <?php the_content(); ?>
    
     <?php endforeach;
    endif; ?>
    </div>

    If I hard code the wpostmeta.meta_value, it will display correctly, but it needs to be equal to the $courseVale (in other words semester posts have to equal the same value as the course, that the semester posts for only that course display).

    What am I doing wrong.

Viewing 2 replies - 1 through 2 (of 2 total)
  • I think you need to enclose $courseVale in quotes:

    AND wpostmeta.meta_value =  '$courseVale'
    Thread Starter Akram Taghavi-Burris

    (@taghaviburris)

    Thank you vtxzzy. I had another project come up and never got back to this. I can’t believe that all I needed were quotes.
    This worked perfectly.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Query by Custom Field value Equal to another posts custom field value’ is closed to new replies.