尝试从id为短代码调用帖子标题,摘录和永久链接

时间:2015-01-07 21:00:10

标签: php wordpress

我能够正确显示标题和摘录,但我无法确定要使用的永久链接。

function display_excerpt_shortcode( $atts ) {
  extract(shortcode_atts(array(
    'excerptid' => ''
  ), $atts));
  if ($excerptid) {
    $args=array(
    'p' => $excerptid,
    'post_type' => 'post',
    'post_status' => 'publish'
  );
    $my_query = new WP_Query($args);
    if ($my_query) {
        $title = apply_filters( 'the_title', $my_query->posts[0]->post_title );
        $excerpt = apply_filters( 'the_excerpt', $my_query->posts[0]->post_excerpt );
        $link = apply_filters( 'the_permalink', $my_query->posts[0]->post_permalink );

        return '<h3>' . $title . '</h3> <p>' . $excerpt . '</p> <a class="button small primary" href="' . $link . '" title="' . $title . '" >Read More </a>';
    }
  }
  return;
}
add_shortcode('display_excerpt', 'display_excerpt_shortcode');

我尝试了各种组合。 the_permalink,get_permalink,post_permalink ...我无法弄清楚它是否是错误的组合,或者我是否完全脱离了标记。提前谢谢。

1 个答案:

答案 0 :(得分:1)

你试过了吗?

$link = get_permalink( $my_query->posts[0]->post_ID )

我认为您的问题是查询对象没有'永久链接'属性。 按照codex's class reference page中的指南,您将找到在使用$the_query->the_post();的循环的每次迭代期间设置新帖子对象的模式:

$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        //Now reference WP post functions:
        the_title();
        the_permalink();
    }
}

对不起,这是一个完全不同的设计,但这从未让我失望。