• I am writing a generic page that I want to grab other small pages to put on it. For my smaller pages I have the code

    <?php
    $myrows = $wpdb->get_results(
    "
    SELECT ID, post_content
    FROM $wpdb->posts
    WHERE post_name = 'title'
    "
    );
    foreach ( $myrows as $myrows)
    {
    echo $myrows->post_content;
    }
    ?>

    to pull the code with the title “title”. The problem is when I make another copy of this generic template it pulls all the pages with that title. I want it to only pull the page that is a child to my new copy of this generic template. How do I do that. Also, how do I have a conditional statement that if the page doesnt exist than display nothing?

Viewing 1 replies (of 1 total)
  • I think what you want is to restrict the query to posts having the post_parent equal to the current post ID. And you should probably only retrieve published posts. If you are ‘in the Loop’, then this query should work:

    $the_id = $post->ID;
    $myrows = $wpdb->get_results(
    "
    SELECT ID, post_content
    FROM $wpdb->posts
    WHERE post_name = 'title'
    AND post_type = 'post'
    AND post_status = 'publish'
    AND post_date < NOW()
    AND post_parent = $the_id
    "
    );

    For the conditional, try this:

    if ($myrows) :
       foreach ( $myrows as $myrows)
       {
          echo $myrows->post_content;
       }
    else:
       // Code here for nothing found
    endif;
Viewing 1 replies (of 1 total)

The topic ‘Grabbing child only with SQL retrieve’ is closed to new replies.