ambarino
Member
Posted 1 year 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;
}
?>
Short version: Don't put the Loop inside a function. ;)
Possible workaround: Try making $post into a global at the beginning of the function.
ambarino
Member
Posted 1 year 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.
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.
d910qf
Member
Posted 11 months ago #
This is useful and FYI putting
global $post
at the beginning of your function is all you need...