• Is it possible to use the get_posts() function within a function as below? I am trying to print the latest posts within the body of an html heredoc email template. Everything prints fine on a plugin page in the dashboard when the code is not placed within the function. But if create a function (getnews) and call getnews() nothing prints.

    <?php function getnews() { $args = array( 'numberposts' => 10, 'order'=> 'ASC', 'orderby' => 'title' ); $postslist = get_posts( $args ); foreach ($postslist as $post) : setup_postdata($post); ?>

    <?php the_date(); ?>
    <?php the_title(); ?> <?php the_excerpt(); ?>
    <?php endforeach; } ?>

    For the heredoc attempt I have $newsletter = 'getnews'; and refer to it so: {$newsletter()} without success.

    Thanks for any help sorting this out.

Viewing 3 replies - 1 through 3 (of 3 total)
  • This is more a heredoc question than a WordPress-question. I would question if the getnews() function is loaded before you access it in the template? You may also find an entry in the error log.

    Thread Starter starapple

    (@starapple)

    @threadi I’d think it was a solely heredoc problem if I had not had the same problem when I just called the function outside of that context and got no output to the screen and no error message. Remove function getnews() {} and the output prints to the screen.

    Moderator bcworkz

    (@bcworkz)

    You cannot expect function calls to be expanded within heredoc, only variables (singleton, array element, or object prop) assigned string values will work. Instead of getnews() echoing out, it should collect all output into a return value. Assign the return value to a variable and use the variable in heredoc.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Is it possible to use the get_posts function within a function?’ is closed to new replies.