簡體   English   中英

在 Wordpress 主題中包含 PHP 文件的正確方法

[英]Proper way to include PHP files in Wordpress theme

我正在嘗試開發一個需要大量 PHP 函數和自定義類的 WordPress 主題。

我想知道在 WordPress 中包含其他 PHP 文件的最佳做法是什么。 示例:我是否列出要包含的每個文件:

  • 包括();
  • 要求一次()
  • ETC

當我查看其他開發人員主題時,我從未偶然發現一批“include() 語句,因此我相信我一定錯過了執行這些包含的一些標准方法。

您可以遵循任何方法。 但我建議您使用require來包含任何文件。

_s(又名下划線),它是主題入門工具包和 WordPress 的默認主題,例如TwentyFourteen、TwentyThirteen 等,使用require來包含文件。

請參閱 TweentyFourteen 主題中使用的示例代碼。

require get_template_directory() . '/inc/template-tags.php';

如果您正在使用子主題並且需要從子主題文件夾加載 php 文件,您應該使用get_stylesheet_directory()函數。 get_stylesheet_directory()

Include 將包含文件內容

如果找不到文件,Require 將拋出錯誤。

Include_once .. 檢查是否包含如果不包含則包含

Require_once 與 include_once 相同,但如果找不到文件則會出錯

因此,如果您是編寫該文件的人,則應該包含 .. 而不是 include_once。

我們通常對不必要的文件使用include。 需要重要文件。 例如footer.php 不會使腳本停止.. 但core.php 很重要。

為什么不將所有包含的文件放入一個文件(library.php)並將其包含在您的主題中? 通過這樣做,如果您需要更改某些內容,您可以只更改一個文件。 您也可以在 library.php 中使用條件標簽,如 if..else 來包含某些頁面的特定文件。

我還建議您將 require_once() 用於重要文件,以便在文件丟失時出現錯誤。 如果文件丟失時沒有錯誤,則使用該文件的函數將通過多個錯誤。

同樣,@Othman 建議您可以將 include 用於不太重要的文件。

另一種方法是分配一個文件並將其包含到您的函數中。php 以避免冗余

例如我的functions.php在我的根文件夾中,我從/inc dir和functions dir/獲取我的文件

include('inc/assets.php'); //Where i register all css and js
include('functions/index.php'); // Where are all functions are registered

wordpress codex https://codex.wordpress.org/Theme_Development#Including_Template_Files還有另一種方法

<?php get_template_part('template-parts/blog', 'content'); ?>

另請查看 wordpress 組織主題文件文檔https://developer.wordpress.org/themes/basics/organizing-theme-files/

assets (dir)
      - css (dir)
      - images (dir)
      - js (dir)
inc (dir)
template-parts (dir)
      - footer (dir)
      - header (dir)
      - navigation (dir)
      - page (dir)
      - post (dir)
404.php
archive.php
comments.php
footer.php
front-page.php
functions.php
header.php
index.php
page.php
README.txt
rtl.css
screenshot.png
search.php
searchform.php
sidebar.php
single.php
style.css

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM