Mike Rifgin
Mike Rifgin

Reputation: 10747

loop won't work inside my plugin

Is it possible to loop in a wordpress plugin?

I've created this plugin that utilizes a wordpress loop to grab some info about posts in my custom post type of events:

function getEventsFeed() {
    $args = array( 'post_type' => 'events' );
    $loop = new WP_Query( $args );
    $htmlOutput = '<h2>Events</h2>';
    while ( $loop->have_posts() ) : $loop->the_post();
        $date = get_post_meta($post->ID, 'events_0');
        $location = get_post_meta($post->ID, 'events_9');
        $htmlOutput .= '<tr><td>' . the_title()  . '</td><td>' . $date[0] . '</td><td><a href="' . get_bloginfo('url') . '/event/?id='. $post->ID . '">' . $post->post_title .'</a></td><td>' .           $location[0] . '</td></tr>';
        endwhile;
        $htmlOutput .= '</div>';
        echo $htmlOutput;
   }

Problem is only the the_title info is being returned. $post is not working within the loop so $post->ID and $post->post_title are not being returned. I'm using this exact code in another page template and it returns all the data correctly. I'm not sure why it won't return when I use it in a plugin.

Any ideas?

Upvotes: 0

Views: 644

Answers (1)

jm_toball
jm_toball

Reputation: 1217

Try adding

global $post;

to the beginning of your function. $loop->the_post() will set the global $post variable, but it is not available inside your function scope.

Upvotes: 3

Related Questions