使用简码按ID显示帖子

时间:2018-09-24 08:32:42

标签: php wordpress function shortcode

add_shortcode('testimonials', 'testimonial_query');
function testimonial_query($atts, $content){
extract(shortcode_atts(array( // a few default values

'id' => null,
'posts_per_page' => '1',
'caller_get_posts' => 1)
, $atts));
$args = array(
'post_type' => 'testimonial',
'numberposts' => -1
);
global $post;
$posts = new WP_Query($args);
$output = '';
if ($posts->have_posts( $attributes['id']))
while ($posts->have_posts( $attributes['id'])):
$posts->the_post();
$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID), 'thumbnail' );
$out = '<div class="testimonial-img">
<img src="'.$url.'" />
</div>
<div class="testimonial_content">
<img src="'.get_field('logo').'" alt="icon">
<p class="testimonial_desc">'.get_the_content().'</p>
<div class="author-details">
<img src="'.get_field('author_image').'" alt="image">
<p>'.get_field('author_name').' <span>'.get_field('author_designation').'</span></p>
</div>';
// add here more...
$out .='</div>';
endwhile;
else
return; // no posts found

wp_reset_query();
return html_entity_decode($out);
}

我正在尝试使用[testimonials id="272"]文件中的简码functions.php通过ID获取帖子。我使用下面的代码,它正在工作,但无法通过ID获取帖子。如果我做错了,谁能帮我解决这个问题?预先感谢。

1 个答案:

答案 0 :(得分:1)

尝试此代码

add_shortcode('testimonials', 'testimonial_query');

function testimonial_query($atts, $content){

    extract(shortcode_atts(array( // a few default values
    'id' => null,
    'posts_per_page' => '1',
    'caller_get_posts' => 1)
    , $atts));


    $args = array(
    'post_type' => 'testimonial',
    'numberposts' => -1
    );

    if($atts['id']){
     $args['p'] = $atts['id'];
    }

    global $post;
    $posts = new WP_Query($args);
    $output = '';


    if ($posts->have_posts())
        while ($posts->have_posts()):
            $posts->the_post();
            $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID), 'thumbnail' );
            $out = '<div class="testimonial-img">
            <img src="'.$url.'" />
            </div>
            <div class="testimonial_content">
            <img src="'.get_field('logo').'" alt="icon">
            <p class="testimonial_desc">'.get_the_content().'</p>
            <div class="author-details">
            <img src="'.get_field('author_image').'" alt="image">
            <p>'.get_field('author_name').' <span>'.get_field('author_designation').'</span></p>
            </div>';
            // add here more...
            $out .='</div>';
        endwhile;
    else
    return; // no posts found
    wp_reset_query();
    return html_entity_decode($out);
}