0

尝试使用 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;

它不起作用,因为自定义内容返回空。怎么了?提前致谢

4

1 回答 1

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] 放在帖子内容中,一切都会正常。

于 2013-10-16T21:23:26.407 回答