Tuesday, 27 August 2013

Shortcode to display custom field of custom post type works only in some post types

Shortcode to display custom field of custom post type works only in some
post types

I created a shortcode to pull custom fields from a custom post type called
"room", by the post slug. The shortcode works fine within a different
custom post type, but doesn't return anything when used in the same custom
post type (room), or in normal posts/pages.
Interestingly, the fields for "title" and "link" display fine for all post
types. So, I believe the problem must be with my get_post_meta line.
If anyone could help me, I'd really appreciate it.
// Add shortcode for getting specific custom field from custom post type
add_shortcode('room-info', 'room_info_func');
function room_info_func($atts) {
extract(shortcode_atts(array(
'name' => null, 'field' => null,
), $atts));
$excerpt_post_name = $name;
$excerpt_field = $field;
// Get post ID from post slug
$args=array(
'name' => $excerpt_post_name,
'post_type' => 'room',
'post_status' => 'publish',
'showposts' => 1,
'caller_get_posts'=> 1
);
$my_posts = get_posts($args);
$excerpt_out = null; // Return empty if there's no post by that slug
if( $my_posts ) {
$id=$my_posts[0]->ID;
// Get custom field from post ID
$excerpt_out = get_post_meta($id, 'wpcf-'.$excerpt_field, $single=true);
}
switch ($field) {
case 'link': return $res=get_post_permalink($id); break;
case 'title': return $res=get_the_title($id); break;
case 'image-url': return
$res=wp_get_attachment_url(get_post_thumbnail_id($id)); break;
default: return $res="$excerpt_out"; break;
}
}

No comments:

Post a Comment