WordPress post query

I am trying to show posts with the tag “medical” if they are a child of page 843, and so far, I have everything mostly working. I need to get some HTML within this if statement so that I can enclose it all in a div, and also to set an opening and closing ul for the list.

Can someone please help me get over this last hump? I’m just not sure where to add the HTML.

<?php
if (843 == $post->post_parent) {
global $post;
$myposts = get_posts('numberposts=10&tag=medical&order=DESC');
foreach($myposts as $post) :
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach;
}
?>

Related posts

Leave a Reply

3 comments

  1. If you want a to enclose all the posts in a div:

    <?php
    global $post;
    if (843 == $post->post_parent) {
        $myposts = get_posts('numberposts=10&tag=medical&order=DESC');
        echo '<div><ul>';
        foreach ($myposts as $post): ?>
            <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
        <?php endforeach;
        echo '</ul></div>';
    } ?>
    
  2. Can you just do something like the following?

    <div id="wrap">
    <ul>
    <?php
    if (843 == $post->post_parent) {
    global $post;
    $myposts = get_posts('numberposts=10&tag=medical&order=DESC');
    foreach($myposts as $post) :
    ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php endforeach;
    }
    ?>
    </ul>
    </div> <!-- #wrap !-->
    
  3. First, you call the global $post variable before the if statement, and re-write the condition this way :

    global $post
    if ($post->post_parent = 843)
    

    Also, you cannot use the functions the_permalink() and the_title() outside the loop, you have to use, instead, the functions get_the_permalink(ID) and get_the_title(ID) this way (and also, $post is ambiguous, you should use another variable name):

    <div><ul>
    <?php foreach($myposts as $mypost) : ?>
    <li><a href="<?php echo get_the_permalink($mypost->ID); ?>"><?php echo get_the_title($mypost->ID); ?></a></li>
    <?php endforeach;
    }?>
    </ul></div>