WordPress.org

Support

Support » How-To and Troubleshooting » [Resolved] Simple PHP Question

[Resolved] Simple PHP Question

  • I have a PHP snippet that I am trying to add to my sidebar before the main loop. It works fine when I add it after:

    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

    It doesn’t work when I add it before the loop. Does a PHP guru out there know what I can add to the snippet to get it to work before the loop?

Viewing 8 replies - 1 through 8 (of 8 total)
  • Why not add it to your sidebar.php file?

    I’m trying. My sidebar is before the loop.

    What’s the PHP you’re trying to insert? Could you paste it here?

    Here it is:

    <?php
    $posts = get_posts("category=23" . $cat->cat_ID . "&numberposts=5");
    if( $posts ) : ?>
    <ul>
    <?php foreach( $posts as $post ) : setup_postdata( $post ); ?>
    <li><a href="<?php the_permalink() ?>" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a></li>
    <?php endforeach; ?>
    </ul>
    <?php endif; ?>

    What is it you’re trying to do? List the posts within a certain category?

    Yes. And this works fine below the loop, but not above it.

    Try altering the first several code bits to:

    <?php
    $myposts = get_posts("category=23" . $cat->cat_ID . "&numberposts=5");
    if( $myposts ) : ?>
    <ul>
    <?php foreach( $myposts as $post ) : setup_postdata( $post ); ?>

    In other words, change $posts to $myposts (or something other than $posts). There’s most likely a conflict with the default $posts object on the page.

    I’d also recommend changing the get_posts() call to:

    $myposts = get_posts("category=23&numberposts=5");

    as $cat->cat_ID would typically have no value here (and if it did, could cause some bugginess).

    Brilliant Kafkaesqui! That’s exactly what I needed! The final code is this and it works perfectly:

    <?php
    $myposts = get_posts("category=23&numberposts=5");
    if( $myposts ) : ?>
    <ul>
    <?php foreach( $myposts as $post ) : setup_postdata( $post ); ?>
    <li><a href="<?php the_permalink() ?>" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a></li>
    <?php endforeach; ?>
    </ul>
    <?php endif; ?>

Viewing 8 replies - 1 through 8 (of 8 total)
  • The topic ‘[Resolved] Simple PHP Question’ is closed to new replies.
Skip to toolbar