I am creating a WP Fiche page with a plugin.
The content of this page requires many variables and functions that are contained in another file important_file.php
. That's why I put everything in the content_fiche()
function and I use require_once('important_file.php')
.
The problem is that I want to manage the forms of my page content with JQuery Ajax and call the functions contained in the file important_file.php
.
I don't really want to modify the file important_file.php
as I didn't code it.
<?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;
Here my JS file which should manage the form:
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) {
}
});
});
});
To connect my JS submit to the PHP functions, I usually just do, but gere it's not enough:
add_action( 'wp_ajax_function_in_important_file', 'function_in_important_file' );
Obviously the ajax file cannot access the important_file.php
and its functions. It's my first time with OOP plugin, so how should I proceed, I have no idea.