在wordpress短代码中使用postmeta

时间:2013-09-14 16:34:51

标签: wordpress

尝试使用shrotcodes从帖子中获取我的帖子元,然后将其显示在内容上。这是尝试执行此操作的代码:

$string = '';
$custom_content = get_post_custom($post->ID);

if( $my_query->have_posts() ) {
  while ($my_query->have_posts()) : $my_query->the_post(); 
      $content = get_the_content();
      $bonus = $custom_content["bonus"];

      $string .= $content . $bonus . '<br>'; 
  endwhile;
}
return $string;

由于自定义内容返回空,因此无效。怎么了?提前致谢

1 个答案:

答案 0 :(得分:0)

我认为您没有获得短代码的想法,您应该阅读有关add_shortcode()的一些信息,您也可以使用get_post_meta()从数据库中检索元数据。

以下是一个如何实现此目的的示例,但这只适用于主循环(默认情况下):

<?php
//you can put this code in functions.php or you can build a plugin for it
function metadata_in_content($attr) {
//this is the function that will be triggerd when the code finds the proper shortcode in the content; $attr is the parameter passed throw the shortcode (leave null for now)
    global $wpdb, $wp_query;
    //we need global $wpdb to query the database and to get the curent post info
    if (is_object($wp_query->post)) {
        $post_id = $wp_query->post->post_id;// here we save the post id
        $metadata = get_post_meta( $post_id, $key, $single ); // here we get the needed meta, make sure you place the correct $key here, also if you don't want to get an array as response pass $single as "true"
        return $metadata; // this finally replaces the shortcode with it's value
    }
}
add_shortcode('insert_metadata', 'metadata_in_content');
//the above code hooks the metadata_in_content function to the [insert_metadata] shortcode
?>

现在剩下要做的就是在帖子内容中放置[insert_metadata],事情应该有效。