Categories

Add Template File to a Post Using Shortcode

// read file
function include_template_file ($template_path=null) {
	if($template_path == null)
		return '';
	ob_start();
    load_template( get_template_directory() .'/'. $template_path );
	$content = ob_get_contents();
	ob_end_clean();
	return $content;
}
 
// shortcode code
function include_template_shortcode($atts, $content=''){
	 extract( shortcode_atts( array(
	      'path' => null
     ), $atts ) );
	return include_template_file($path);
}
 
add_shortcode( 'include_template', 'include_template_shortcode' );
 
// Example:
// [include_template path='assets/my-file.php']

Get Post or Page by Name

$post_title = 'my-post-name';
$post = get_page_by_title($post_title, OBJECT);
var_dump($post);

Truncate WordPress post content

$post_content = $post->post_content; // get the content
$post_content = strip_tags($post_content); // remove HTML tags
$post_content = preg_replace('/\[(.*)\]/', '', $post_content);  // remove shortcodes
$post_content = substr($post_content, 0, 30);
echo $post_content;

Associating images to a post or a page

In the version 2.9 WordPress introduced the capability of associating images to a post or a page. When you create your theme you can turn on this feature by simply adding a call to add_theme_support('post-thumbnails') in your functions.php (this file should be located inside you theme folder).

if ( function_exists( 'add_theme_support') ) {
	add_theme_support( 'post-thumbnails' );
	add_image_size( 'image-normal', 96, 9999, false );
	add_image_size( 'image-small', 32, 9999, false );
}

Believe it or not you are ready to go. Once you add this feature, the next time that you are creating or editing a post in the WordPress admin area, you will be presented with the option to add a Feature Image to your post. This will allow you to upload and associate an image to your post.

To show the image in your page you can simply call the_post_thumbnail($feature). Here is an example:

<?php 
	$posts = get_posts();
	foreach ($posts as $post){
		setup_postdata($post); 
		if(is_search()){
			?>
			<p id="<?=the_ID();?>"><?=the_title();?></p>
			<?php the_post_thumbnail('image-small');
		}else{
			?>
			<h1 id="<?=the_ID();?>"><?=the_title();?></h1>
			<?php the_post_thumbnail('image-normal');
		}
	}
?>

References

Add Theme Support
Add Image Size
The Post Thumbnail

Related articles

Retrieving The Thumbnail Image