Display Post from Custom Post Type with Shortcode

admin2025-01-07  3

I've created a custom post type for locations on my site and I would like to display each post in full with shortcode. I'm quite new to creating shortcode and I'm struggling to wrap my head around it. I want to display the post by slug like this: [stefan_location slug="Aspley"] but I can't get it to work. I know I'm probably way off so any advise would be welcome!!

function cpt_content_func($atts){
    $post = '';
    $content = '';
    extract( shortcode_atts( array(
        'slug' => null,
    ), $atts ) );
    $args = array(
        'name' => $slug,
        'post_type' => 'location',
        'numberposts' => 1
    );
    $post = get_posts( $args );
    if ( !empty( $post ) ) {
        $content = $post[0]->post_content;
    }
    return $content;
}
add_shortcode('stefan_location','stefan_location');

I've created a custom post type for locations on my site and I would like to display each post in full with shortcode. I'm quite new to creating shortcode and I'm struggling to wrap my head around it. I want to display the post by slug like this: [stefan_location slug="Aspley"] but I can't get it to work. I know I'm probably way off so any advise would be welcome!!

function cpt_content_func($atts){
    $post = '';
    $content = '';
    extract( shortcode_atts( array(
        'slug' => null,
    ), $atts ) );
    $args = array(
        'name' => $slug,
        'post_type' => 'location',
        'numberposts' => 1
    );
    $post = get_posts( $args );
    if ( !empty( $post ) ) {
        $content = $post[0]->post_content;
    }
    return $content;
}
add_shortcode('stefan_location','stefan_location');
Share Improve this question asked Mar 20, 2020 at 1:34 tashtash 11 bronze badge 1
  • 1 Well, the second parameter for your add_shortcode() should be cpt_content_func. – Sally CJ Commented Mar 20, 2020 at 1:46
Add a comment  | 

1 Answer 1

Reset to default 0
  • You enter second parameter in add shorcode is incorrect,you missing callable function in parameter.
  • Like below this add_shortcode with parameter.

add_shortcode( string $tag, callable $callback );

Code :

function cpt_content_func($atts){
    $post = '';
    $content = '';
    extract( shortcode_atts( array(
        'slug' => null,
    ), $atts ) );
    $args = array(
          'post_type' => 'location', 
          'posts_per_page' => 1, 
          'post_name__in' => $atts['slug'] ); 

    $post = get_posts( $args );
    if ( !empty( $post ) ) {
        $content = $post[0]->post_content;
    }
    return $content;
}
add_shortcode('stefan_location','cpt_content_func');
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736259615a602.html

最新回复(0)