个性化阅读
专注于IT技术分析

WordPress修改父代码

有人告诉我, 子主题是可行的方法, 但是你应该尽量不要触摸父模板文件, 并通过操作/过滤器挂钩进行修改。但是, 通常, 我发现我需要在没有现有钩子的地方插入<div class =” myclass”>或类似的东西。

有没有更好的方法来修改父代码?我发现最简单的方法就是复制要修改的文件(例如header.php), 然后进行所需的更改。当然, 如果父主题已更新, 则我的header.php将过时, 找到这些更改将很痛苦!


#1


有更好的方法来使用子主题, 这些主题不涉及从父主题复制文件并对其进行黑客攻击。

主题框架

你之前可能会遇到过主题框架, 例如Thesis, Carrington或Thematic。

主题框架背后的想法是, 它将通过以下方式为你开发儿童主题提供灵活的基础:

  • 提供干净, 牢固, 结构良好的父主题
  • 为你的标记提供其他挂钩, 以及
  • 在某些情况下, 提供允许你无需编码即可修改主题的管理工具。

http://codex.wordpress.org/Theme_Frameworks

功能覆盖

使用主题框架, 可以使用functions.php轻松覆盖现有功能。这样一来, 你就可以使用自己的自定义代码替换常见的功能(例如页眉和页脚), 并使用所选主题框架中未包含的功能来扩展主题。

以下是Thematic框架的一些示例(我在最近的项目中一直在使用Thematic):

  • http://www.catswhocode.com/blog/wordpress-how-to-easily-create-a-thematic-child-theme
  • http://www.showtimedesigner.com/01/2011/wordpress/helpful-thematic-functions-to-customize-your-wordpress-site

因此, 你需要在子主题中进行的所有修改就是你的style.css和functions.php。即使更新了Wordpress和基础的Parent主题, 这也可以使主题保持功能。


#2


这就是我所做的。这不是最干净的解决方案, 但可以。

下面的header.php文件实际上将父主题的header.php加载为字符串, 插入代码, 保存一个临时文件, 然后在其自身中包含该临时文件以供执行。

$whole_file = file_get_contents(__DIR__ . "/../parent/header.php"); // Load the header file and convert to string
$predecessor_line = '<body id="for-example">'; // We're inserting our code right after this line. As long as the parent theme doesn't update this line, we're good.
$split_file = explode($predecessor_line, $whole_file); // Slice the file at the $predecessor_line (The text used to slice disappears, so be sure to add it again)
$code_to_insert = '<div class="myclass">'; // This is the code you want to insert.
$new_file_content = $split_file[0] . $predecessor_line . $code_to_insert . $split_file[1]; // Piece everything together
$new_file = fopen("_temp_header.php", "w"); // Create a Temporary File
fwrite($new_file, $new_file_content); // Write The Temporary File
fclose($new_file); // Close the Temporary File
include("_temp_header.php"); // Include the Temporary File to execute
unlink("_temp_header.php"); // Delete the Temporary File
赞(0)
未经允许不得转载:srcmini » WordPress修改父代码

评论 抢沙发

评论前必须登录!