不管您是否将代码添加到函数中,您的代码都不会被执行。php文件或将其注册为独立插件,因为它不使用WordPress调用其任何函数hook.
为了让您的代码被识别为插件,有一些preliminaries 您需要遵循以下步骤,即在/wp-content/plugins/folder安装中创建一个子文件夹,将代码保存在文件中并向其中添加一个标题。
创建一个子文件夹,我们称之为my-first-plugin,将代码保存在名为my-first-plugin.php 在该子文件夹中,并向其添加以下标题,
/*
Plugin Name: My First Plugin
Plugin URI: https://developer.wordpress.org/plugins/the-basics/
Description: Basic WordPress Plugin Header Comment
Version: 1.0
Author: You Name Here
Author URI: https://developer.wordpress.org/
License: GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: my-first-plugin
*/
然后在文件底部插入以下代码
register 您的插件,
register_activation_hook( __FILE__, \'activate_my_first_plugin\' );
function activate_my_first_plugin(){
new My_Class();
}
这将激活您的插件,并在仪表板中激活插件时创建My\\u Class对象。
总之,这是您的文件的外观,
<?php
/*
Plugin Name: My First Plugin
Plugin URI: https://developer.wordpress.org/plugins/the-basics/
Description: Basic WordPress Plugin Header Comment
Version: 1.0
Author: You Name Here
Author URI: https://developer.wordpress.org/
License: GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: my-first-plugin
*/
Class My_Class{
/* Constructor for setting values to the propeties. Make sure to select the right breakpoint with the right image*/
public function __construct($imgPath, $landscapeSelectors, $portraitSelectors, $figureClass, $landscapeBreakpoints, $portraitBreakpoints) {
$this->setImgPath($imgPath);
$this->setLandscapeSelectors($landscapeSelectors);
$this->setPortraitSelectors($portraitSelectors);
$this->setFigureClass($figureClass);
$this->setLandscapeBreakpoints($landscapeBreakpoints);
$this->setPortraitBreakpoints($portraitBreakpoints);
}
/* The picture element is build inside here */
public function createHeroImage() {
/* Set the base of the figure */
$this->setHeroImage("<figure style=\'margin-bottom: -7px;\' class=\'".$this->getFigureClass()[\'figure\']."\'>
<picture class=\'".$this->getFigureClass()[\'figure-div\']."\'>
");
$this->landscapeImage();
$this->portraitImage();
$this->setHeroImage($this->getHeroImage() . "<img id=\'hero-image\' style=\'object-fit: cover; height: calc((16 / 9) * 100%)\' alt=\'".$this->getImgPath()[\'landscapeImage\'][\'alt\']."\' src=\'".$this->getImgPath()[\'portraitImage\'][\'sizes\'][$this->getLandscapeSelectors()[0]]."\'>");
$this->setHeroImage($this->getHeroImage() . "</picture>
</figure>");
return $this->getHeroImage();
}
} //ebd My_Class
register_activation_hook( __FILE__, \'activate_my_first_plugin\' );
function activate_my_first_plugin(){
new My_Class();
}
注:
我将您的代码包装在我的\\u类声明中,我假设您正在创建php class, 因为您的代码公开了构造函数您的构造函数需要多个在插件激活时不可用的参数,通常的做法是使用构造函数中的各种WordPress挂钩注册方法调用。因此,您现在需要了解WordPress中的哪一点execution cycle 您希望代码运行。由于你没有解释清楚,我不能再帮你了。你需要这样做,
公共函数\\uu construct(){add\\u action(\'init\',array(\'this,\'initialise\');add\\u action(some other hook,array(\'this,call my method));}
公共函数initialise(){//首页请求初始化时调用的方法。}
请注意,您需要将方法调用与类实例一起包装在一个数组中,array($this, method-call), 以便钩子在当前实例中调用该方法