Eklenti ile WordPress'e Sayfa Şablonları Ekleyin


Güncelleme : Kod, WordPress 4.7+ üzerinde çalışacak şekilde yakın zamanda güncellendi

Hiç kendi sayfa şablonlarınızı oluşturmak istediniz, ancak temanın kendisine erişiminiz olmadı mı? Bir WordPress eklentisi yazarı olarak, eklentilerimi geliştirirken bu sorunu özellikle can sıkıcı buldum. Neyse ki çözüm oldukça basit! WordPress Sayfa Şablonlarını doğrudan PHP üzerinden dinamik olarak oluşturmak için ihtiyaç duyacağınız birkaç kod satırından sizi hızlı bir şekilde geçireceğim.

Bu makale için ilham ve kod çözümünün arkasındaki deha Tom McFarlin'den geliyor: GitHub'ında bulabileceğiniz orijinal kodunun düzenlenmiş sürümünü kullanıyorum. Neler olup bittiğini açıklamakta çok yardımcı olduğunu düşündüğüm için (kendi yorumumu da ekleyerek) onun yorumlarını burada tuttum – bunu kendimden daha iyi söyleyemezdim!

Kodun tamamını ve örnek bir eklentiyi bu yazının en altında bulabilirsiniz.

Başlayalım mı?

kod

PHP işlevimizi bir PHP Sınıfı kullanarak oluşturacağız. PHP Sınıfları konusunda bilgili olmayanlarınız için, Sınıf, birlikte çalışan işlevler ve değişkenler koleksiyonunu içeren bir nesne olarak tanımlanır. Sözdizimi ve teori hakkında daha fazla ayrıntı için PHP.net Giriş bölümüne bakın.

Sarmalayıcımız sadece 3 değişkene ihtiyaç duyacaktır:

  1. Eklenti Slug: Bu, eklenti için benzersiz bir tanımlayıcı olarak kullanılır.
  2. Sınıf Örneği: WordPress'in kafasına bu sınıfın bir örneğini eklediğimiz için, onu saklamamız daha iyi olur.
  3. Şablon Dizisi: Tahmin edebileceğiniz gibi, bu, şablon adlarını ve başlıklarını tutan bir dizidir.

İşte koddalar:

 class PageTemplater { /** * A Unique Identifier */ protected $plugin_slug; /** * A reference to an instance of this class. */ private static $instance; /** * The array of templates that this plugin tracks. */ protected $templates;

Sınıf Örneği Alın

Daha önce söylediğim gibi, add_filter() işlevini kullanarak WordPress başlığına sınıfımızın bir örneğini ekleyeceğiz. Bu nedenle, bu örneği bizim için döndürecek (veya yaratacak) bir yönteme ihtiyacımız olacak.

Bunun için 'get_instance' olarak adlandırılacak basit bir metoda ihtiyacımız olacak. Aşağıdan kontrol edin;

 /** * Returns an instance of this class. */ public static function get_instance() { if( null == self::$instance ) { self::$instance = new PageTemplater(); } return self::$instance; }

Bu, sınıfımız 'add_action()' kullanılarak WordPress başlığına eklendiğinde çağrılan yöntem olacaktır.

WordPress Filtreleri

Şimdi 'get_instance' yöntemini çözdük, gerçekten başlatıldığında ne olacağını çözmemiz gerekiyor.

WordPress başlatma zaman çizelgesindeki önemli noktalara sınıfımızın bir örneğini eklemek için WordPress'in yerleşik add_filter() işlevini kullanacağız. Bu yöntemi kullanarak, sayfa çağrıldığında WordPress'e hangi dosyanın şablon olarak kullanılacağını ve Sayfa Düzenleyicisi'ndeki açılır menüde görüntülenecek başlığı söylemek gibi, sayfa şablonlarımızın verilerini ilgili yuvalara ekleyeceğiz.

Bunun için '__construct' yöntemini kullanmamız gerekiyor (bu, sınıf başlatıldığında çalıştırılacaktır).

 /** * 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( 'goodtobebad-template.php' => 'It\'s Good to Be Bad', ); }

Burada 4 farklı şey oluyor (sadece değişkeni kullanıma hazırlayan ' $this->templates = array();' yok sayılıyor);

  1. Satır 9 – 13 : Bu filtre, 'page_attributes_dropdown_pages_args' kancasına 'register_project_templates' ekliyor. Bu, WordPress önbelleğini yeni şablonlarımızla dolduruyor ve WordPress'i sayfa şablonu dosyalarının gerçekten şablon dizininde olduğuna inandırarak 'kandırıyor'. Bu, sayfa şablonlarını sayfa düzenleyicideki sayfa öznitelikleri meta kutusundaki açılır listeye ekler.
  2. Satır 16 – 20 : Burada önceki kod bloğuyla aynı şeyi yapıyoruz, ancak bu sefer sayfa şablonumuzu (seçilmişse) kaydedilen gönderi verilerine de ekliyoruz.
  3. Satır 23 – 28 : Bu filtre, 'view_project_template' kancasına 'template_include' ekliyor. Bu çok önemli bir işlevdir; bu, WordPress'e sayfa şablonu dosyanızın gerçekte nerede olduğunu söyler. WordPress, son sayfayı oluşturmak için bunun sağladığı yolu kullanacaktır.
  4. Satır 31 – 34 : Bu basit olsa da çok önemlidir. Bu, eklenmesini istediğiniz sayfa şablonlarını ve sayfa şablonu dosyasının bulunduğu dosyaya göre yolu (örneğin, 'something.php') belirttiğiniz yerdir. Bir örnek ekledim (bu örnek eklentide kullanılacak). Genel bir örnek için aşağıya göz atın:
 $this->templates = array( 'FILE_PATH_AND_NAME' => 'TEMPLATE_TITLE', 'awesome-template.php' => 'Awesome', 'templates/organised-template.php' => 'Organised', );

(Ye, Uyu,) Kodla, Gerektiği kadar tekrarla.

register_project_templates()

Bu yöntemden daha önce bahsetmiştim; bakalım gerçekte ne yapıyor.

Esasen, bu yöntemin amacı, sayfa şablonlarımızla ilgili verileri doğru yerlere ekleyerek WordPress'in önbelleğini manipüle etmektir. Önce koda bir göz atın, sonra size bunun üzerinden bahsedeceğim.

 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; }

Tamam öyleyse. 4. sıra bakılacak ilk yerdir. Tahmin edebileceğiniz gibi, bir 'önbellek anahtarı' oluşturuyoruz. Bu bizim sayfa şablonu verileri için benzersiz bir tanımlayıcı olarak kullanılacaktır. md5() işlevini kullanmak, herhangi bir çakışmayı önlemek için yalnızca benzersiz bir dize tanımlayıcısı oluşturur.

Daha sonra, 8. satırda, sayfa şablonu önbelleğini arıyor ve alıyoruz (zaten varsa): bu, bir dizi yol ve başlık döndürecektir. 9-11 satırlarında önbellek sorgusundan herhangi bir çıktı olup olmadığını kontrol ederiz. Evet ise, harika. Değilse, önbellekte birleştireceğimiz verileri tutmak için yerel bir dizi oluşturun.

Bir sonraki adım çok önemli. 14. satırda mevcut sayfa şablonu önbelleğini sileriz . Endişelenmeyin, hiçbir veri kaybolmaz – bunlar $templates değişkeninde saklanır.

18. satırda mevcut sayfa şablonları önbelleğini yeni girişlerimizle birleştiriyoruz ve 22. satırda tüm sayfa şablonu önbelleğini WordPress sistemine yeniden yerleştiriyoruz.

Basit!

view_project_template ()

Artık son yöntemimize geçiyoruz; Burası WordPress'e gerçek sayfa şablonu dosyasının nerede olduğunu söylediğimiz yer.

 /** * Checks if the template is assigned to the page */ public function view_project_template( $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; } $file = plugin_dir_path(__FILE__). 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; }

Tamam o zaman, bu yöntem global $post değişkenine (satır 6) karşı kontrol olacaktır. Gönderi için bir sayfa şablonunun ( '_wp_page_template' ) ayarlanıp ayarlanmadığını kontrol eder (yani bir sayfa olmalıdır). Değilse, boşverin – sayfa olmayanların sayfa şablonları olamaz.

16. satır, sayfa şablonu dosyasının konumunu belirtir. Yukarıda belirttiğim gibi, eklentinizin kök dizininde belirtilen sayfa şablonu dosyasını kontrol eder. (Bu, kolayca değiştirilebilir; aşağıya bakın.)

 // Just changing the page template path // WordPress will now look for page templates in the subfolder 'templates', // instead of the root $file = plugin_dir_path(__FILE__). 'templates/' .get_post_meta( $post->ID, '_wp_page_template', true );

Bundan sonra, 21 – 24 satırlarında, dosyanın gerçekten var olup olmadığını kontrol eden küçük bir doğrulamamız var. Evet ise, harika! Değilse, ah canım… WordPress şablon dosyasını bulamazsa, hatta boş bir ekran bile bulamazsa büyük olasılıkla bir PHP hata mesajı alırsınız. Bu belirtilerden herhangi biri tanıdık geliyorsa, ekrana $file değişkenini yazdırarak şablon dosya yolunu kontrol edin.

Bu kodu ticari olarak kullanmayı planlıyorsanız (ki bunu yapmakta özgürsünüz – kodun sürümüm lisanssız geliyor, bu nedenle istediğiniz gibi yapmakta özgürsünüz), hata işlemeye maksimum düzeyde zaman ayırmanızı gerçekten tavsiye ederim. güvenilirlik.

Bu budur. Dersimiz tamamlandığında yapılacak tek bir şey kaldı – onu WordPress başlığına ekleyin.

 add_action( 'plugins_loaded', array( 'PageTemplater', 'get_instance' ) );

Tüm yolu başardıysan tebrikler! Umarım söyleyeceklerimi faydalı bulmuşsunuzdur ve gelecekte bundan faydalanırsınız!

Tüm Kod

Körük, kolay kopyalama ve yapıştırma için eklentinin kodunun tamamıdır.

 <?php /* Plugin Name: Page Template Plugin : 'Good To Be Bad' Plugin URI: http://www.wpexplorer.com/wordpress-page-templates-plugin/ Version: 1.1.0 Author: WPExplorer Author URI: http://www.wpexplorer.com/ */ class PageTemplater { /** * 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 PageTemplater(); } 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( 'goodtobebad-template.php' => 'It\'s Good to Be Bad', ); } /** * 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 ) { // 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; } $file = plugin_dir_path( __FILE__ ). 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( 'PageTemplater', 'get_instance' ) );

Eklenti

Ayrıca tam kodu Github'da eklenti olarak indirebilirsiniz.

Editör Yakın Çekim

İşte eklentinin çalışırken yakından görünümü. Sayfa Nitelikleri altında eklenen sayfa şablonunu görüyor musunuz?

GTBB1

Copyright statement: Unless otherwise noted, this article is Collected from the Internet, please keep the source of the article when reprinting.

Check Also

Divi's Theme Builder ile Özel Global Başlık Nasıl Oluşturulur

Artık Tema Oluşturucu burada olduğuna göre, web sitenizi A'dan Z'ye kurmanıza yardımcı olacak yeni eğitimlere dalmak için sabırsızlanıyoruz. Buna Divi'nin yerleşik seçeneğini kullanarak özel başlıklar oluşturma da dahildir. Bu eğitimde Divi's Theme Builder'ı kullanarak global bir başlık oluşturmaya odaklanacağız. Bu sayfaya veya gönderiye farklı bir başlık atamadıysanız, web sitenizin her yerinde genel bir başlık görünecektir.

Bir Cevap Yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir