How to call a filter hook in a PHP external file

可紊 提交于 2019-12-24 02:13:19

问题


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:


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>


来源:https://stackoverflow.com/questions/18512186/how-to-call-a-filter-hook-in-a-php-external-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!