WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Simple PHP Question (9 posts)

  1. supor1t
    Member
    Posted 7 years ago #

    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?

  2. drmike
    Member
    Posted 7 years ago #

    Why not add it to your sidebar.php file?

  3. supor1t
    Member
    Posted 7 years ago #

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

  4. maerk
    Member
    Posted 7 years ago #

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

  5. supor1t
    Member
    Posted 7 years ago #

    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; ?>

  6. maerk
    Member
    Posted 7 years ago #

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

  7. supor1t
    Member
    Posted 7 years ago #

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

  8. Kafkaesqui

    Posted 7 years ago #

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

  9. supor1t
    Member
    Posted 7 years ago #

    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; ?>

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags