I've a problem. My plan is it to create a new class object inside a WordPress template to pass a variable from the post object to it:
<?php
/**
* Template Name: Ticket
*/
defined( 'ABSPATH' ) || exit;
new Test( $post->ID );
Inside my class I'm defining an action that adds a AJAX function inside the class:
class Test {
public function __construct( $ticket_id ) {
$this->ticket_id = $ticket_id;
$this->register();
}
/**
* Register all hooks
*/
public function register(): void {
add_action( 'wp_ajax_test', array( $this, 'test' ) );
}
public function test(): void {
error_log($this->ticket_id);
}
}
The problem is that the AJAX function is not reachable. Maybe it's added too late? Because when I create a new class object directly in my functions.php
file, it's working. In this case I don't know how to get my post id inside my class.
Thanks for helping me out!
First things first:
With separation of concern in mind, you should not use your template to register anything. Your template should be as stupid as possible, as it is only there to render/display things.
Still, you have to call the register function:
$testClass = new Test( $post->ID );
$testClass->register();
WordPress has a live cycle. I'm not sure if you are able to add a new action there.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.