Thêm template page cho wordpress bằng plugin

template page cho wordpress
Đánh giá bài viết

Để tạo các trang đăng nhập hay quản trị chúng ta thường sử dụng template page cho wordpress. Để làm template page chúng ta thường hay viết một template page thẳng vào trong source của theme.

Hôm rồi tôi được khách hàng đặt làm một theme wordpress mà trong đó trang chủ sử dụng template page kết nối đến API để hiển thị dữ liệu. Tôi vẫn làm bình thường là code template page vào thẳng trong theme, rồi không biết vì lý do gì mà khách hàng cứ liên tục gặp rắc rối với API key và dĩ nhiên mỗi lần như vậy tôi lại phải giúp họ đi can thiệp vào code.

Sau vài lần như vậy tôi thấy không ổn lắm vì tiền theme thì chẳng được bao nhiêu mà còn phải hậu dịch vụ phiền phức nên nghĩ đến việc tạo template page trong wordpress bằng plugin để từ trong bảng setting plugin khách hàng có thể tự thay đổi API key mỗi khi nó thay đổi.

Chắc cũng không có nhiều trường hợp làm tương tự như tôi nhưng tôi xin chia sẽ lại để ai có nhu cầu thì có thể tham khảo.

Tạo plugin cho wordpress

Việc đầu tiên chúng ta cần làm đó là tạo plugin cho wordpress. Để tạo plugin cho wordpress, trong thư mục plugin của bạn, bạn tạo file .php bắt đầu với nội dung code như dưới đây.

<?php
/*
Plugin Name: Livescore
Plugin URI: https://hanhtinhcongnghe.com/
Version: 1.1.0
Author: hanhtinhcongnghe
Author URI: https://hanhtinhcongnghe.com/
*/

include( plugin_dir_path( __FILE__ ) . 'classes/APIlivescore_class.php');


function register_mysettings() {
        register_setting( 'apilivescore-settings-group', 'apilivescore_option_name' );
}

function apilivescore_plugin(){
    add_options_page('Livescore Widget Settings', 'Livescore Widget', 'manage_options', 'livescore-widget-plugin', 'apilivescore_settings_page');
    add_action( 'admin_init', 'register_mysettings' );  
}
add_action('admin_menu','apilivescore_plugin');


function apilivescore_settings_page() {
?>
<div class="wrap">
<h2>Tạo trang cài đặt cho plugin</h2>
<?php if( isset($_GET['settings-updated']) ) { ?>
    <div id="message" class="updated">
        <p><strong><?php _e('Settings saved.') ?></strong></p>
    </div>
<?php } ?>
<form method="post" action="options.php">
    <?php settings_fields( 'apilivescore-settings-group' ); ?>
    <table class="form-table">
        <tr valign="top">
        <th scope="row">API key</th>
        <td><input type="text" class="regular-text" name="apilivescore_option_name" value="<?php echo get_option('apilivescore_option_name'); ?>" /></td>
        </tr>
    </table>
    <?php submit_button(); ?>
</form>
</div>
<?php } ?>

Class xử lý tạo template page cho wordpress

Chúng ta sẽ tạo một class để xử lý mọi thứ liên quan đến việc gọi template page cho wordpress.

<?php 

// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) exit;

if(!class_exists('APIlivescore')){
	class APIlivescore {

		/**
		 * A reference to an instance of this class.
		 */
		private static $instance;

		/**
		 * The array of templates that this plugin tracks.
		 */
		protected $templates;

		/**
		 * Returns an instance of this class.
		 */
		public static function get_instance() {

			if ( null == self::$instance ) {
				self::$instance = new APIfootball();
			}

			return self::$instance;

		}

		/**
		 * Initializes the plugin by setting filters and administration functions.
		 */
		private function __construct() {

			$this->templates = array();


			// Add a filter to the attributes metabox to inject template into the cache.
			if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.7', '<' ) ) {

				// 4.6 and older
				add_filter(
					'page_attributes_dropdown_pages_args',
					array( $this, 'register_project_templates' )
				);

			} else {

				// Add a filter to the wp 4.7 version attributes metabox
				add_filter(
					'theme_page_templates', array( $this, 'add_new_template' )
				);

			}

			// Add a filter to the save post to inject out template into the page cache
			add_filter(
				'wp_insert_post_data',
				array( $this, 'register_project_templates' )
			);


			// Add a filter to the template include to determine if the page has our
			// template assigned and return it's path
			add_filter(
				'template_include',
				array( $this, 'view_project_template')
			);


			// Add your templates to this array.
			$this->templates = array(
				'../templates/livescore-template.php' => 'API_football',
			);

		}

		/**
		 * Adds our template to the page dropdown for v4.7+
		 *
		 */
		public function add_new_template( $posts_templates ) {
			$posts_templates = array_merge( $posts_templates, $this->templates );
			return $posts_templates;
		}

		/**
		 * Adds our template to the pages cache in order to trick WordPress
		 * into thinking the template file exists where it doens't really exist.
		 */
		public function register_project_templates( $atts ) {

			// Create the key used for the themes cache
			$cache_key = 'page_templates-' . md5( get_theme_root() . '/' . get_stylesheet() );

			// Retrieve the cache list.
			// If it doesn't exist, or it's empty prepare an array
			$templates = wp_get_theme()->get_page_templates();
			if ( empty( $templates ) ) {
				$templates = array();
			}

			// New cache, therefore remove the old one
			wp_cache_delete( $cache_key , 'themes');

			// Now add our template to the list of templates by merging our templates
			// with the existing templates array from the cache.
			$templates = array_merge( $templates, $this->templates );

			// Add the modified cache to allow WordPress to pick it up for listing
			// available templates
			wp_cache_add( $cache_key, $templates, 'themes', 1800 );

			return $atts;

		}

		/**
		 * Checks if the template is assigned to the page
		 */
		public function view_project_template( $template ) {
			// Return the search template if we're searching (instead of the template for the first result)
			if ( is_search() ) {
				return $template;
			}

			// Get global post
			global $post;

			// Return template if post is empty
			if ( ! $post ) {
				return $template;
			}

			// Return default template if we don't have a custom one defined
			if ( ! isset( $this->templates[get_post_meta(
				$post->ID, '_wp_page_template', true
			)] ) ) {
				return $template;
			}

			// Allows filtering of file path
			$filepath = apply_filters( 'page_templater_plugin_dir_path', plugin_dir_path( __FILE__ ) );

			$file =  $filepath . get_post_meta(
				$post->ID, '_wp_page_template', true
			);

			// Just to be safe, we check if the file exist first
			if ( file_exists( $file ) ) {
				return $file;
			} else {
				echo $file;
			}

			// Return template
			return $template;

		}

	}
	add_action( 'plugins_loaded', array( 'APIlivescore', 'get_instance' ) );

Trong class trên bạn chú ý đến đoạn code $this->template = array(); Tại đây bạn thêm đường dẫn đến template page mà bạn sẽ sử dụng để hiển thị cho giao diện người dùng.

// Add your templates to this array.
$this->templates = array(
	'../templates/livescore-template.php' => 'API_livescore',
);

Nếu bạn muốn thêm css hay javascript cho template page thì trong function __construct() bạn thêm add_action() cho wp_enqueue_scripts

add_action( 
	'wp_enqueue_scripts', 
		array( $this, 'enqueue_scripts_styles' )
);

Và tạo function enqueue_scripts_styles như dưới đây để gọi css và javascript

/**
 * Add enqueue your scripts on init action
 *
 */
public function enqueue_scripts_styles() {
	if( is_page_template('../templates/livescore-template.php') ){
		//css
		wp_enqueue_style( 'datepicker_styles', plugins_url( '../vendors/bootstrap-datepicker/css/datepicker.min.css', __FILE__ ), '', '1.0' );
		wp_enqueue_style( 'datepicker_standalone_styles', plugins_url( '../vendors/bootstrap-datepicker/css/datepicker.standalone.min.css', __FILE__ ), '', '1.0' );

		//script
		wp_enqueue_script( 'datepicker_script', plugins_url( '../vendors/bootstrap-datepicker/js/bootstrap-datepicker.js', __FILE__ ), array( 'jquery' ), '1.0', true );
		wp_enqueue_script( 'customs_script', plugins_url( '../js/customs.js', __FILE__ ), array( 'jquery' ), '1.0', true );
	}
} // End enqueue_scripts_styles ()

Tạo template page cho wordpress

tạo template page cho wordpress bằng plugin
tạo template page cho wordpress bằng plugin

Sau khi đã có đầy đủ phần cần thiết để có thể tạo template page cho wordpress thì chúng ta cũng cần phải có template page để có thể chọn template khi add page.

Bạn tạo một file php và dán đoạn code bên dưới để có thể hiển thị template trong phần page.

<?php
/*
 Template Name: LiveScore
 */

Một số phụ trợ thêm khi làm plugin tạo template page

Hiện thị menu plugin ra ngoài

Menu chính

//menu of plugin
    function hopafi_plugin_menu() {
        add_menu_page(
            'Home page', // Page title
            'Homepage', // Menu title
            'manage_options', // Capability
            'hopafi-plugin', // Menu slug
            'hopafi_plugin_settings_page', // Callback function
            'dashicons-share-alt', // Icon URL
            100 // Position
        );
        add_action( 'admin_init', 'register_hopafi_settings' );  
    }
    add_action( 'admin_menu', 'hopafi_plugin_menu' );

    

Menu con

//submenu of plugin
    /* function hopafi_plugin_submenu() {
        add_submenu_page(
            'hopafi-plugin', // Parent slug
            'My Plugin Submenu', // Page title
            'My Plugin Submenu', // Menu title
            'manage_options', // Capability
            'hopafi-plugin-submenu', // Menu slug
            'hopafi_plugin_submenu_page' // Callback function
        );
    }
    add_action( 'admin_menu', 'hopafi_plugin_submenu' ); */

CSS và js cho plugin admin panel

//menu of plugin
    function my_options_page_styles() {
        $screen = get_current_screen();
        if ( $screen->id === 'toplevel_page_hopafi-plugin' ) {
            wp_enqueue_style( 'bootstrap-style', plugin_dir_url( __FILE__ ) . 'vendors/bootstrap-5.2.3/css/bootstrap.min.css');
            wp_enqueue_style( 'setting-style', plugin_dir_url( __FILE__ ) . 'css/setting_style.css');
            wp_enqueue_script( 'bootstrap-script', plugin_dir_url( __FILE__ ) . 'vendors/bootstrap-5.2.3/js/bootstrap.min.js');
        }
    }
    add_action( 'admin_enqueue_scripts', 'my_options_page_styles' ); 

Upload hình ảnh trong plugin panel

Bỏ <?php wp_enqueue_media(); ?> vào bên trong function hopafi_plugin_settings_page nơi mà bạn sẽ hiển thị layout trong panel.

Và thêm script để mở thư viện media wordpress mỗi khi bạn bấm vào nút upload hình ảnh.

<script>
jQuery(document).ready(function($) {
     $('#hopafi_main_logo_upload').click(function(e) {
                e.preventDefault();
                var custom_uploader = wp.media({
                    title: 'Select Image',
                    button: {
                        text: 'Use Image'
                    },
                    multiple: false
                }).on('select', function() {
                    var attachment = custom_uploader.state().get('selection').first().toJSON();
                    $('#hopafi_main_logo').val(attachment.url);
                    //$('#my_image_preview').attr('src', attachment.url);
                    $('#hopafi_main_preview').html('<img src="'+ attachment.url+'") >');
                }).open();
            });
            $('#hopafi_main_logo_remove').click(function(e){
                e.preventDefault();
                $('#hopafi_main_logo').val('');
                $('#hopafi_main_preview').html('<p style="background-color: #edeff0; border: 1px dashed #b4b9be; line-height:90px;text-align:center">Upload Logo</p>');
            });
});

Và html tương ứng

<div class="form-field term-group">
                                <input type="hidden" id="hopafi_main_logo" name="hopafi_main_logo" class="custom_media_url" value="<?php echo get_option( 'hopafi_main_logo' ); ?>">
                                <div id="hopafi_main_preview">
                                    <?php if(get_option( 'hopafi_main_logo' )){ 
                                            echo '<img src="'. get_option( 'hopafi_main_logo' ) .'" alt="">';
                                        }else{ 
                                            echo '<p style="background-color: #edeff0; border: 1px dashed #b4b9be; line-height:90px;text-align:center">Upload Logo</p>';
                                        }
                                    ?>
                                </div>
                                <p class="mt-3">
                                <input type="button" class="button button-secondary " id="hopafi_main_logo_upload" name="" value="<?php _e( 'Add Image', 'hero-theme' ); ?>" />
                                <input type="button" class="button button-secondary " id="hopafi_main_logo_remove" name="" value="<?php _e( 'Remove Image', 'hero-theme' ); ?>" />
                                </p>
                            </div><!-- /.logo -->

Chọn danh sách trang bài viết

Tương tự như trên bỏ <?php $pages = get_pages(); ?> vào function hopafi_plugin_settings_page

Và html select bài đăng từ danh sách trang bài viết

<div class="form-floating">
                                <select class="form-select w-100" id="floatingSelect"  name="hopafi_page_content" aria-label="Floating label select example">
                                    <option value="">Select</option>
                                    <?php
                                    foreach ( $pages as $page ) {
                                        $selected = (get_option('hopafi_page_content') == $page->ID) ? 'selected' : '';
                                        echo '<option value="' . $page->ID . '" ' . $selected . '>' . $page->post_title . '</option>';
                                    }
                                    ?>
                                </select>
                                <label for="floatingSelect">Post on homepage</label>
                            </div>

Như vậy là chúng ta đã có thể tạo template page cho wordpress bằng plugin mà không cần phải thêm template page trực tiếp vào trong source code.

Thức khuya nhiều nên mệt vì vậy phần sau đăng hơi cẩu thả, ai kỹ tính lỡ đọc bài này mong thông cảm.

Để lại bình luận

Email của bạn sẽ được bảo mật.