• ambarino

    (@ambarino)


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

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator Samuel Wood (Otto)

    (@otto42)

    www.ads-software.com Admin

    Short version: Don’t put the Loop inside a function. ??

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

    Thread Starter ambarino

    (@ambarino)

    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.

    Moderator Samuel Wood (Otto)

    (@otto42)

    www.ads-software.com Admin

    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.

    This is useful and FYI putting

    global $post

    at the beginning of your function is all you need…

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘The Loop inside a function: some thing works, other don’t’ is closed to new replies.