WordPress Проблемы с интеграцией Ajax - PullRequest
2 голосов
/ 08 марта 2019

Я создаю WP Fiche страницу с плагином.Содержимое этой страницы требует много переменных и функций, которые содержатся в другом файле important_file.php.Вот почему я помещаю все в функцию content_fiche() и использую require_once('important_file.php').

Проблема в том, что я хочу управлять формами содержимого моей страницы с помощью JQuery Ajax и вызывать функции, содержащиеся в файле important_file.php.

Я не хочу изменять файл important_file.php, поскольку я его не кодировал.

<?php
class fiche_content{
    private $file_base;

    function __construct(){
        $this->file_base = plugin_dir_path( dirname( __FILE__ ) ) . 'fiche.php'; 
        $this->init();
    }   

    function init() {
        add_action('wp_enqueue_scripts', array($this,'scripts_js'));
        add_action('wp_loaded', array($this, 'add_page_fiche'));
    }  

    function scripts_js(){
        wp_enqueue_script('fiche_scripts', plugins_url('JS/scripts.js', __FILE__), array('jquery'), '1.0', true);
        wp_localize_script('fiche_scripts', 'ajax_object', array('ajaxurl' => admin_url( 'fiche.php' ),
        ));
    }

    function add_page_fiche() {
        $new_page = array(
            'post_title'    => wp_strip_all_tags( 'Fiche Projet' ),
            'post_content'  => $this->content_fiche(),
            'post_status'   => 'publish',
            'post_author'   => 1,
            'post_type'     => 'page'
        );
        wp_insert_post( $new_page );
    }    

    function content_fiche(){
        require_once ( '.../important_file.php');
        $foo = $var_in_important_file;      
        $html = '<div>'. $foo .'</div>';
        $html .= '<form id="form" method="POST">
                      <input type="hidden" name="build" value="1" />
                      <input type="submit" name="submit_build" value="Submit" />
                </form>';
        return $html;

Вот мой JS-файл, который должен управлять формой:

jQuery(document).ready(function($) {
    $(document).on('submit', '#form',function(e){
        $.post({
            url: my_ajax_object.ajax_url,
            data: {
                data,
                'action': 'function_in_important_file'
            },
            done: function(result) {
            }
        });
    });
});

Чтобы подключить мою JS-отправку к функциям PHP, я обычно просто делаю, но этого недостаточно:

add_action( 'wp_ajax_function_in_important_file', 'function_in_important_file' ); 

Очевидно, что файл ajax не может получить доступ к important_file.php и его функциям.Это мой первый раз с плагином ООП, так что как мне поступить, я понятия не имею.

1 Ответ

0 голосов
/ 11 марта 2019

Вот руководство по WordPress Ajax функции

    class fiche_content{
        private $file_base;

        function __construct(){
            $this->file_base = plugin_dir_path( dirname( __FILE__ ) ) . 'fiche.php'; 
            $this->init();
        }   

        function init() {
            add_action('wp_enqueue_scripts', array($this,'scripts_js'));
            //add_action('wp_loaded', array($this, 'add_page_fiche'));

            // Register the Ajax action to bind the corresponding WordPress function

            add_action( "wp_ajax_nopriv_function_in_important_file", array ( $this, 'add_page_fiche' ) );
            add_action( "wp_ajax_function_in_important_file",        array ( $this, 'add_page_fiche' ) );



        }  

        function scripts_js(){
            wp_enqueue_script('fiche_scripts', plugins_url('JS/scripts.js', __FILE__), array('jquery'), '1.0', true);
            wp_localize_script('fiche_scripts', 'ajax_object', array('ajaxurl' => admin_url( 'fiche.php' ),
            ));
        }

        function add_page_fiche() {
            $new_page = array(
                'post_title'    => wp_strip_all_tags( 'Fiche Projet' ),
                'post_content'  => $this->content_fiche(),
                'post_status'   => 'publish',
                'post_author'   => 1,
                'post_type'     => 'page'
            );
            wp_insert_post( $new_page );
        }    

        function content_fiche(){
            require_once ( '.../important_file.php');
            $foo = $var_in_important_file;      
            $html = '<div>'. $foo .'</div>';
            $html .= '<form id="form" method="POST">
                          <input type="hidden" name="build" value="1" />
                          <input type="submit" name="submit_build" value="Submit" />
                    </form>';
            return $html;
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...