How to call a filter hook in a PHP external file

2019-07-18 04:36发布

I'm trying to call a filter hook in a standalone PHP file in Wordpress.

This is the code of the file: my_external_file.php:

<?php
require( dirname(__FILE__) . '/../../../../../../../wp-load.php');

add_filter('init', 'test_function');

function test_function (){
    global $global_text_to_shown;

    $global_text_to_shown = 'Hello World';

}

global $global_text_to_shown;

$quicktags_settings = array( 'buttons' => 'strong,em,link,block,del,ins,img,ul,ol,li,code,spell,close' );

//This work fine, shown editor good.
wp_editor( $global_text_to_show, 'content', array( 'media_buttons' => false, 'tinymce' => true, 'quicktags' => $quicktags_settings ) );

//Load js and work fine the editor - wp_editor function.
wp_footer();

?>

The issue is that the filter isn't get executed hence the function doesn't get executed.

How can I execute the filter hook on this external PHP file?

1条回答
走好不送
2楼-- · 2019-07-18 05:31

First and main problem $global_text_to_show is not $global_text_to_shown.

The hook init is not a filter, it's an action: add_action('init', 'test_function');. See Actions and Filters are not the same thing.

Loading wp-load.php this way is... crappy code ;) See Wordpress header external php file - change title?.

The second main problem is why and what for do you you need this?
Anyway, init will not work, using the filter the_editor_content will. Although I don't understand the goal:

<?php
define( 'WP_USE_THEMES', false );
require( $_SERVER['DOCUMENT_ROOT'] .'/wp-load.php' );

// Requires PHP 5.3. Create a normal function to use in PHP 5.2.
add_filter( 'the_editor_content', function(){
    return 'Hello World';
});

$quicktags_settings = array( 'buttons' => 'strong,em,link,block,del,ins,img,ul,ol,li,code,spell,close' );

?><!DOCTYPE html>
<html>
<head>
<?php wp_head(); ?>
</head>
<body>
<?php 
    wp_editor( 
        '', 
        'content', 
        array( 
            'media_buttons' => false, 
            'tinymce' => true, 
            'quicktags' => $quicktags_settings 
        ) 
    );
    wp_footer();
?>
</body>
</html>
查看更多
登录 后发表回答