[wp-hackers] get_post_meta in widgets

Mike Schinkel mikeschinkel at newclarity.net
Wed Apr 14 06:59:21 UTC 2010


Hi Ash,

I haven't tested this before emailing but I'm pretty sure what you want is:

$rightAdsection = new WP_Query('post_type=page&posts_per_page=1&meta_value=_adsPositionRight&orderby=rand');
foreach($rightAdsection as $ad) {
  $adRight = get_post_meta($ad->ID, '_adright', true);
  if ($adRight)
    echo "it works";
  else
    echo "it doesn't work";
}

HTH.

-Mike
P.S. If you can use WP3.0 you could create a custom post type "Ad" and then do this instead:

$rightAdsection = new WP_Query('post_type=ad&posts_per_page=1&meta_value=_adsPositionRight&orderby=rand');
foreach($rightAdsection as $ad) {
  $adRight = get_post_meta($ad->ID, '_adright', true);
  if ($adRight)
    echo "it works";
  else
    echo "it doesn't work";
}


On Apr 14, 2010, at 2:30 AM, Ash Goodman wrote:

> Hi, I have been chasing my tail on this for a couple of days.
> 
> I don't seem to be able to access get_post_meta from within a widget and am
> hoping someone can point me in the right direction?
> 
> I am building a  widget to run ads in the sidebar. The ads are pages with
> meta values that assign them as ads and I use the the_post_thumbnail for the
> ad image and custom write panels to store the ads url as a meta value. I
> have checked and the data is being stored correctly in the database.
> 
> Within the widget I am running a new WP-Query:
> 
> $rightAdsection = new
> WP_Query('post_type=page&posts_per_page=1&meta_value=_adsPositionRight&orderby=rand');
> 
> 
>    while($rightAdsection->have_posts()) :
>    $rightAdsection->the_post();
>    $adRight = get_post_meta($post->ID, '_adright', true);
>    if ($adRight) {
>    echo "it works";
>    }else{
>    echo "it doesn't work";
>    };
>    endwhile;
> 
> No matter what I always get "it doesn't work"
> 
> The WP_Query is running correctly, the loop is there and if I set
> post_per_page to a higher number it echo's "it doesn't work" a matching
> number of times.
> 
> If I substitute the whole if statement with
> 
> echo $post_ID;
> 
> I get nothing so it seems as if the query doesn't get the post id?
> 
> But it does get
> 
> the_post_thumbnail('ads-image-right');
> 
> In fact if I replace the "it doesn't work" in the if statement with
> the_post_thumbnail('ads-image-right'); It displays the correct image. Which
> is to say that the $adRight variable is empty though it shouldn't be but the
> the_post_thumbnail still works
> 
> If I replace $adRight = get_post_meta($post->ID, '_adright', true); with
> $adRight = get_post_meta($id, '_adright', true);
> 
> It makes no difference
> 
> I am relatively new to PHP and am sure I am missing something terribly
> obvious.
> 
> Thanks!
> 
> Ash
> _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers



More information about the wp-hackers mailing list