Удаление действия из нижнего колонтитула wp, вызываемого в классе, который находится внутри более крупного класса
Предыстория:
Привет, я использую Плагин обоснованной галереи, и я пытаюсь загрузить необходимые ресурсы только на тех страницах, где я использую галереи.
Проблема:
Плагин загружает некоторые встроенные элементы и скрипты, которые я не смог загрузить, когда не на нужной странице.
Вот код основного класса, который создает экземпляры других классов:
<?php
// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) {
exit;
}
$fspath = dirname(__FILE__) . '/includes/fs/config.php';
if ( file_exists($fspath) ) {
require_once $fspath;
}
if ( !class_exists( 'DGWT_JG_Core' ) ) {
final class DGWT_JG_Core {
private static $instance;
private $tnow;
public $detector;
public $settings;
public $gallery;
public $lightbox;
public $tilesStyle;
public static function get_instance() {
if ( !isset( self::$instance ) && !( self::$instance instanceof DGWT_JG_Core ) ) {
self::$instance = new DGWT_JG_Core;
self::$instance->constants();
if ( !self::$instance->check_requirements() ) {
return;
}
self::$instance->load_textdomain();
self::$instance->includes();
self::$instance->hooks();
self::$instance->detector = new DGWT_JG_MobileDetect;
self::$instance->settings = new DGWT_JG_Settings;
self::$instance->gallery = new DGWT_JG_Gallery;
self::$instance->lightbox = new DGWT_JG_Lightbox_Loader;
self::$instance->tilesStyle = new DGWT_TilesStyle_Loader;
}
self::$instance->tnow = time();
return self::$instance;
}
/**
* Constructor Function
*/
private function __construct() {
self::$instance = $this;
}
/*
* Check requirements
* @since 1.2.2
*/
private function check_requirements() {
if ( version_compare( PHP_VERSION, '5.3.0' ) < 0 ) {
add_action( 'admin_notices', array( $this, 'admin_notice_php' ) );
return false;
}
return true;
}
/**
* Setup plugin constants
*/
private function constants() {
$this->define( 'DGWT_JG_VERSION', '1.2.3' );
$this->define( 'DGWT_JG_NAME', 'Justified Gallery' );
$this->define( 'DGWT_JG_FILE', __FILE__ );
$this->define( 'DGWT_JG_DIR', plugin_dir_path( __FILE__ ) );
$this->define( 'DGWT_JG_URL', plugin_dir_url( __FILE__ ) );
$this->define( 'DGWT_JG_DOMAIN', 'justified-gallery' );
$this->define( 'DGWT_JG_SETTINGS_KEY', 'dgwt_jg_settings' );
$this->define( 'DGWT_JG_DEBUG', false );
}
/**
* Define constant if not already set
* @param string $name
* @param string|bool $value
*/
private function define( $name, $value ) {
if ( !defined( $name ) ) {
define( $name, $value );
}
}
/**
* Include required core files.
*/
public function includes() {
require_once DGWT_JG_DIR . 'includes/Utils/Helpers.php';
require_once DGWT_JG_DIR . 'includes/Utils/MobileDetect.php';
require_once DGWT_JG_DIR . 'includes/Install.php';
require_once DGWT_JG_DIR . 'includes/admin/settings/SettingsApi.php';
require_once DGWT_JG_DIR . 'includes/admin/settings/Settings.php';
require_once DGWT_JG_DIR . 'includes/RegisterScripts.php';
require_once DGWT_JG_DIR . 'includes/admin/admin.php';
require_once DGWT_JG_DIR . 'includes/admin/Promo/FeedbackNotice.php';
require_once DGWT_JG_DIR . 'includes/Gallery.php';
require_once DGWT_JG_DIR . 'includes/TilesStyle/Loader.php';
require_once DGWT_JG_DIR . 'includes/Lightbox/Loader.php';
}
/**
* Actions and filters
*/
private function hooks() {
add_action( 'admin_init', array( $this, 'admin_scripts' ) );
}
/*
* Enqueue admin sripts
*/
public function admin_scripts() {
// Register CSS
wp_register_style( 'dgwt-jg-admin-style', DGWT_JG_URL . 'assets/css/admin-style.css', array(), DGWT_JG_VERSION );
// Enqueue CSS
wp_enqueue_style( array(
'dgwt-jg-admin-style',
//'wp-color-picker'
) );
//wp_enqueue_script( 'wp-color-picker' );
}
/*
* Register text domain
*/
private function load_textdomain() {
$lang_dir = dirname( plugin_basename( DGWT_JG_FILE ) ) . '/languages/';
load_plugin_textdomain( DGWT_JG_DOMAIN, false, $lang_dir );
}
/*
* Notice: PHP version less than 5.3
*/
public function admin_notice_php() {
?>
<div class="error">
<p>
<?php
printf(__( '<b>Justified Gallery Plugin</b>: You need PHP version at least 5.3 to run this plugin. You are currently using PHP version %s. Please upgrade PHP version or uninstall this plugin.', 'justified-gallery' ), PHP_VERSION);
?>
</p>
</div>
<?php
}
}
}
// Init the plugin
function DGWT_JG() {
return DGWT_JG_Core::get_instance();
}
DGWT_JG();
Вот класс DGWT_JG_Gallery конструктор, который добавляет действие, которое я хотел бы удалить на ненужных страницах:
class DGWT_JG_Gallery {
/**
* Store array with options
* @var array
*/
public $options;
function __construct() {
$this->set_options();
add_filter( 'post_gallery', array( $this, 'post_gallery' ), 15, 3 );
add_action( 'wp_footer', array( $this, 'init_gallery' ), 90 );
}
Я добавил это в свою дочернюю тему function.php
function remove_justified_gallery() {
remove_action( 'wp_footer', array( $gallery, 'init_gallery' ), 90 );
// remove_action( 'wp_footer', 'include_modal', 90 );
// remove_action( 'wp_footer', 'gallery_init', 90 );
}
add_action( 'wp_head', 'remove_justified_gallery', 1);
Борьба здесь заключается в том, чтобы получить доступ к классу, который содержит функцию
В соответствии с кодексом , чтобы удалить функцию в классе из действия: https://codex.wordpress.org/Function_Reference/remove_action
Если действие было добавлено из класса, например с помощью плагина для его удаления потребуется доступ к классу через переменную, содержащую экземпляр класса. Если только функция не является статической , в этом случае вы можете вызвать класс и функцию напрямую.
Пример:
add_action( 'wp_head', 'remove_my_class_action' );
function remove_my_class_action(){
global $my_class;
remove_action( 'wp_footer', array( $my_class, 'class_function_being_removed' ) );
}
1 answers
Из-за того, как структурирован плагин, подключенная функция , по-видимому, в конечном счете существует в свойстве gallery
свойства instance
класса DGWT_JG_Core
.
При создании экземпляра DGWT_JG_Core
создается экземпляр класса DGWT_JG_Gallery
, который добавляется в свойство gallery
экземпляра DGWT_JG_Core
. Поэтому нам нужно удалить действие из свойства gallery
экземпляра DGWT_JG_Core
, созданного при запуске плагина.
Поскольку DGWT_JG_Core
является синглетоном существует только один экземпляр DGWT_JG_Core
, и мы можем получить к нему доступ с помощью метода get_instance()
. К счастью для нас, плагин определяет функцию, которая вызывает этот метод для нас. Это та функция DGWT_JG()
в конце.
Таким образом, чтобы иметь возможность удалить действие, мы используем DGWT_JG()
для получения экземпляра DGWT_JG_Core
и доступа к классу DGWT_JG_Gallery
через свойство gallery
:
function wpse_284486_remove_justified_gallery() {
$instance = DGWT_JG();
remove_action( 'wp_footer', array( $instance->gallery, 'init_gallery' ), 90 );
}
add_action( 'wp_head', 'wpse_284486_remove_justified_gallery', 0 );
Я протестировал это на поддельной версии классов, которые только что реализовали один хук, и это сработало. Я опубликую это здесь, чтобы вы могли может быть, посмотреть, что происходит:
class My_Test_Gallery {
function __construct() {
add_action( 'wp_footer', array( $this, 'init_gallery' ), 90 );
}
function init_gallery() {
echo 'Hello world!';
}
}
class My_Test_Plugin {
private static $instance;
public static function get_instance() {
if ( ! isset( self::$instance ) && ! ( self::$instance instanceof My_Test_Plugin ) ) {
self::$instance = new My_Test_Plugin;
self::$instance->gallery = new My_Test_Gallery;
}
return self::$instance;
}
private function __construct() {
self::$instance = $this;
}
}
function My_TP() {
return My_Test_Plugin::get_instance();
}
My_TP();
function wpse_284486_remove_justified_gallery() {
$instance = My_TP();
remove_action( 'wp_footer', array( $instance->gallery, 'init_gallery' ), 90 );
}
add_action( 'wp_head', 'wpse_284486_remove_justified_gallery', 0 );