Search code examples
wordpresspostembedshortcode

How to insert a post into a page in wordpress? Using [Shortcodes]


I am using wordpress as our CMS for our companies website. We have about 5-10 pages which we want to insert the same call to action content in.

How can I create a shortcode that will allow me to embed the content from a post into a page?

Thanks Steven.


Solution

  • I haven't tested this, but you'll probably want something along these lines:

    function create_call_to_action_shortcode( $atts ) {
            $call_to_action_content = '';
            $query = new WP_Query( array( 'p' => $post_id, 'no_found_rows' => true ) );
    
            if( $query->have_posts() ) {
                $query->the_post();
    
                remove_filter( 'the_content', 'sharing_display', 19);
    
                $call_to_action_content = apply_filters( 'the_content', get_the_content() );
    
                add_filter( 'the_content', 'sharing_display', 19);
    
                wp_reset_postdata();
            }
    
            return $call_to_action_content;
    }
    
    add_shortcode( 'call_to_action', 'create_call_to_action_shortcode' );`
    

    In your pages ( or other posts, for that matter ), you can simply insert [call_to_action] in the page/post content.

    You can find more information on shorcodes here. :)

    Edit:

    In order to remove sharing buttons from the post content, you need to call remove_filter( 'the_content', 'sharing_display', 19);. I've update the code above.