PHP code example of creativecoder / wp-template-controller

1. Go to this page and download the library: Download creativecoder/wp-template-controller library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

creativecoder / wp-template-controller example snippets


// Example:
e( get_template_directory() . '/controller.php' );

class My_Controller extends Template_Controller {

	// Generates data for all templates
	public function common() {
		$this->add( 'hi', 'I load for every template on the site.' );
	}

	public function page() {
		$this->add( 'yo', 'I load for page.php and custom page templates.' );

		// Get recent posts to display on the page
		$this->add( 'recent_posts', get_posts( array(
			'post_type' => 'post',
			'posts_per_page' => 2,
				)
			)
		);
	}
}

My_Controller::init();

// within page.php

// Store the data
$yo = get_tpl_data( 'yo' );

// Echo out the data
tpl_data( 'hi' );

// Use data as you normally would in template files
$recent_posts = tpl_data( 'recent_posts' );
foreach( $recent_posts as $post ) {
	echo $post->post_title;
}

// within page.php

global $template_data;
extract( $template_data, EXTR_SKIP );

echo $yo;

foreach( $recent_posts as $post ) {
	echo $post->post_title;
}