0

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');
  • 1
    Well, the second parameter for your add_shortcode() should be cpt_content_func. – Sally CJ Mar 20 at 1:46
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');
| improve this answer | |
  • thanks I've changed this now and it's recognising the shortcode now but I think the attributes are still off as it's not displaying the post at all can you see where I'm going wrong? – tash Mar 20 at 2:52
  • You can change your argument like this$args = array( 'post_type' => 'location', 'posts_per_page' => 1, 'post_name__in' => $atts['slug'] ); – HK89 Mar 20 at 3:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.