• Resolved supor1t

    (@supor1t)


    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?

    Thread Starter supor1t

    (@supor1t)

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

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

    Thread Starter supor1t

    (@supor1t)

    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?

    Thread Starter supor1t

    (@supor1t)

    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).

    Thread Starter supor1t

    (@supor1t)

    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 ‘Simple PHP Question’ is closed to new replies.