Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Nikolaj Dinesen
Nikolaj Dinesen
6,903 Points

How to show custom post type, single post, by shortcode in a page??

Hi there

I have a problem. I have found some solutions to create a shortcode to get a single post from a custom post type, but it only calls whats in the original editor-field in every post or page in wordpress. It does not call what is in my custom fields. I suspect that it cannot read from the template file, so i tried combining some get_template_part into, but with no luck.

Does anyone know what to add to make it display it all?

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

I have a php file called 'content-rejse.php' with the html design where it calls from the custom fields, and it works if i show all my post, and a single post, but not when i try to retrieve it with my shortcode, then it only show whats in the original editor-field.

Thank you very much in advance, i hope you can help me.

Best regards Nikolaj

1 Answer

Yojance Rabelo
Yojance Rabelo
1,156 Points

Try replacing this: $content = $post[0]->post_content;

With this:

$content = apply_filters( 'the_content', get_post_field( 'post_content', $post[0]->ID ) );

Nikolaj Dinesen
Nikolaj Dinesen
6,903 Points

Thank you

I tried it - didn't work, so i went to the ACF-support site to check for some help: This is all i found: ACF Code examples I can't seem to get it to work. I tried to include the examples from ACF, but with no luck..

Have no idea how to get it to work...?!