I’m trying to display a custom field in a widget I’m customizing but I can’t get the custom field to display. I think it has something to do with the variable I’m using to get the post ID in the loop because when I change it to the standard the_title function, the widget works, so it has something to do with how I’m calling the custom field.
I know the key to the custom field is “wpcf-promo-title” but no matter what I’ve tried, the custom field (which holds a shortened version of the post title for the sidebar) just won’t display. This code results in the thumbnails showing, but not the promo title. You can see this in action at http://www.cantstopshipping.com
Here’s my code, including the query and the front end of the widget.
function widget($args, $instance) {
extract( $args );
$title = apply_filters( 'widget_title', empty($instance['title']) ? 'Recent Posts' : $instance['title'], $instance, $this->id_base);
$show_date = isset( $instance['show_date'] ) ? $instance['show_date'] : false;
if ( ! $number = absint( $instance['number'] ) ) $number = 5;
if( ! $cats = $instance["cats"] ) $cats='';
// array to call recent posts.
$crpw_args=array(
'showposts' => $number,
'category__in'=> $cats,
);
$crp_widget = null;
$crp_widget = new WP_Query($crpw_args);
echo $before_widget;
// Widget title
echo $before_title;
echo $instance["title"];
echo $after_title;
// Post list in widget
echo "<ul>n";
while ( $crp_widget->have_posts() )
{
$crp_widget->the_post();
?>
<li class="crpw-item">
<p style="float:left">
<a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent link to <?php the_title_attribute(); ?>" class="crpw-title"><?php the_post_thumbnail('sidebar-small'); ?></a>
</p>
<?php $promotitle = get_post_meta($post->ID, 'wpcf-promo-title', true); ?>
<p style="float:right; width:200px">
<a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent link to <?php the_title_attribute(); ?>" class="crpw-title"><?php echo $promotitle; ?></a>
</p>
<?php if ( $show_date ) : ?>
<span class="crpw-date"><?php echo "("; ?><?php echo get_the_date(); ?><?php echo ")"; ?></span>
<?php endif; ?>
</li>
<?php
}
wp_reset_query();
echo "<div class="fix"></div>";
echo "</ul>n";
echo $after_widget;
}
It looks like your
global $post
is missing.But you could try
get_the_ID()
instead of$post->ID
.You should also consider getting rid of
extract()
, it’s now considered a “bad” practice.Another thing is that you should use
wp_reset_postdata()
to restore the global$post
object. Thewp_reset_query()
call should be used with thequery_posts()
call.