WordPress.org

Ready to get started?Download WordPress

Forums

PHP Code Widget
[resolved] WP_Query loop inside widget error (5 posts)

  1. Driftless
    Member
    Posted 1 year ago #

    I'm having issues with a custom wp_query in the widget. This code works fine throughout my site:

    <?php
    $facts = custom_wp_query('3'); //get 3 results
      //echo "<pre>"; print_r($facts); echo "</pre>";
    while ( $facts->have_posts() ) : $facts->the_post();
      echo "<pre>"; print_r($post); echo "</pre>";//This works elsewhere
    endwhile;
    ?>

    The custom query gives me 3 wp_post objects in $facts as expected. However, the while loop fails saying $post is not defined. This works elsewhere on my site, but not in this widget. What am I missing?

    http://wordpress.org/extend/plugins/php-code-widget/

  2. Driftless
    Member
    Posted 1 year ago #

    And... it returns the error 3 times, meaning the loop knows there is 3 posts, they just aren't being shifted to the global $post variable...

  3. Driftless
    Member
    Posted 1 year ago #

    Got it working with:

    <?php
    $facts = custom_wp_query('3'); //get 3 results
    while ( $facts->have_posts() ) : $facts->the_post();
      $post = $facts->post;
      echo "<pre>"; print_r($post); echo "</pre>";//This works elsewhere
    endwhile;
    ?>

    Strange that the previous works elsewhere...

  4. Samuel Wood (Otto)
    Tech Ninja
    Plugin Author

    Posted 1 year ago #

    You didn't declare that the $post was global by using a global $post call anywhere.

    The code inside the widget will run in a function context, not in the global context. You need to declare what variables you're using that are globals.

  5. Driftless
    Member
    Posted 1 year ago #

    Makes sense, thanks.

Topic Closed

This topic has been closed to new replies.

About this Plugin

About this Topic

Tags