Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have a query in a custom widget (my first one!) which, if it's of custom post type book, retrieves the post ID. This then gets used in a WP_QUERY to retrieve data about the page.

This works perfectly when in the static sidebar.php, but not in either a dynamic PHP Widget or as a custom widget in functions.php. In those, it retrieves the relevant field from all examples of post type book.

Here's the offending code.

            <?php
         if('book' == get_post_type()) : 
            $ww_book_id = $post->ID;

        else :

            $ww_book_id = $default_book; //this is pulled in from the widget admin options form and works perfectly.
        endif; 

        $testimonial_args = array(
            'post_type' => 'book',
            'p' => $ww_book_id

        );
        $main_testimonials = new WP_Query($testimonial_args);
        if($main_testimonials->have_posts()) : while($main_testimonials->have_posts()): $main_testimonials->the_post(); 

         echo the_title(); //I actually do much more stuff than this, but it works for testing purposes.

        endwhile; 
    wp_reset_postdata();
     endif; 

    ?>

Many thanks!

share|improve this question
add comment

1 Answer 1

up vote 0 down vote accepted

Solved it!

I replaced $ww_book_id = $post->ID; with $ww_book_id = get_the_ID();

I'm not sure why $post->ID; was referencing all the posts in the widgetized version of this code. If anyone can tell me, I'd be very curious.

share|improve this answer
1  
You should do a var_dump($post->ID) in that context. There's a good chance that $post->ID is not what you think it should be in that context, thus causing the problem. Depending on the widget and the loop in the main template, many of the post vars can get mixed up and cause these variables to hold unexpected values. –  tollmanz Aug 23 '11 at 19:49
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.