Insert post into any post or page shortcode embed

cyber-ki codesnippets

It’s quiet bit of code for a “short code” found on the web.
Insert post or page into a post or page. There a tons of plugins but a snippet can be handy as well.
Credits go to  the fuxia on github


<?php # -*- coding: utf-8 -*-
/**
* Plugin Name: T5 Embed Post Shortcode
* Description: Embed any page, post or custom post type with shortcode: <code>[embed_post id=1 title="hello" type="post"]</code>.
* Plugin URI: http://toscho.de/?p=2056
* Version: 2012.08.17
* Author: Thomas Scholz
* Author URI: http://toscho.de
* License: MIT
* License URI: http://www.opensource.org/licenses/mit-license.php
*
* T5 Embed Page Shortcode, Copyright (C) 2012 Thomas Scholz
*/

add_shortcode( 'embed_post', 't5_embed_post' );

/**
* Get a post per shortcode.
*
* @param array $atts There are three possible attributes:
* id: A post ID. Wins always, works always.
* title: A page title. Show the latest if there is more than one post
* with the same title.
* type: A post type. Only to be used in combination with one of the
* first two attributes. Might help to find the best match.
* Defaults to 'page'.
* @return string|void
*/
function t5_embed_post( $atts )
{
$defaults = array (
'id' => FALSE,
'title' => FALSE,
'type' => 'page'
);
extract( shortcode_atts( $defaults, $atts ) );

// Not enough input data.
if ( ! $id and ! $title )
{
return;
}

$post = FALSE;

if ( $id )
{
$post = get_post( $id );
}
elseif ( $title )
{
$post = get_page_by_title( $title, OBJECT, $type );
}

if ( $post )
{
return apply_filters( 'the_content', $post->post_content );
}
}

[embed_post id=1 title="hello" type="post"]

I’ve edited the code a little bit because I wanted to be able to style the embed post via css. So I’ve put “div’s” around the post to be embeded.
To archive this you just replace the last line.
Thus:

return apply_filters( 'the_content', $post->post_content );

becomes

return apply_filters( 'the_content', '<div class="'. $class . '" />' . $post->post_content . '</div>' );

And shortcode:

[embed_post id=1 title="hello" type="post" class="class"]

Warning! It works but I’m not sure if this is done in the proper way.

Leave a Reply