Create php function to use inside while loop

How can I create a function to use inside a while loop. Like the_title() or the_meta() in WordPress?
A simple sample is enough.

Related posts

Leave a Reply

2 comments

  1. you could use globals. For example, assuming you have a global array, here is something that does that (obviously you need to add more robustness such a error checking. plus how you would use this on wordpress would depend on what you are doing)

    $post= array( 0=>array('title'=>'the title', 'content'=>'this is the content'),
                  1=>array('title'=>'the second title','content'=>'we all love seconds'),
                );
    $array_index=0;
    the_title();
    the_post();
    next_post();
    the_title();
    the_post();
    
    function the_title() {
       global $post, $array_index;
       echo $posts[$array_index]['title'];
    }
    function the_post() {
       global $post, $array_index;
       echo $posts[$array_index]['title'];
    }
    function next_post() {
       global $post, $array_index;
       $array_index++;
    }
    
  2. So from looking at the the_title() and related functions, it looks like you should be able to do as follows (untested, but should work):

    function whatever_you_want( $post_id = 0 ) {
      $post = get_post($id);
      // Display something with data from $post
    }
    

    If you don’t specify any post_id to the function, get_post() will retrieve the current post in the loop for you to use in your function.