Forums

The Loop inside a function: some thing works, other don't (5 posts)

  1. ambarino
    Member
    Posted 3 years ago #

    I want to put The Loop inside a function to show the most recent post of some categories in different places of my home page. I've written the following function, but although THE_CONTENT works, THE_TITLE shows the same title for both posts. Help, please!

    <?php
    function show_posts($id_categoria) {
    $posts=get_posts("category=$id_categoria&numberposts=1");
    if ($posts) :
    foreach($posts as $post) :
    setup_postdata($post); ?>
    <h2>"><?php the_title() ?></h2>
    <?php the_content("[Més...]"); ?>
    </div>
    <?php
    endforeach;
    endif;
    }
    ?>

  2. Otto
    Tech Ninja
    Posted 3 years ago #

    Short version: Don't put the Loop inside a function. ;)

    Possible workaround: Try making $post into a global at the beginning of the function.

  3. ambarino
    Member
    Posted 3 years ago #

    Why can't I put the loop inside a function? If it's a piece that I have to repeat many times, it's logical and much better to put it inside a function.

  4. Otto
    Tech Ninja
    Posted 3 years ago #

    Functions have their own variable scope. The Loop, in general, expects to be in the global scope.

    Also, it's extremely rare that one would reuse an existing Loop enough times to gain anything from function-izing it. In fact, using a function like that would be slower than unrolling it into several different Loops.

  5. d910qf
    Member
    Posted 3 years ago #

    This is useful and FYI putting

    global $post

    at the beginning of your function is all you need...

Topic Closed

This topic has been closed to new replies.

About this Topic