| 1 |
<?php |
| 2 |
|
| 3 |
namespace Elementor\Modules\AtomicWidgets\Ajax; |
| 4 |
|
| 5 |
use Elementor\Core\Common\Modules\Ajax\Module as Ajax; |
| 6 |
use Elementor\Plugin; |
| 7 |
|
| 8 |
if ( ! defined( 'ABSPATH' ) ) { |
| 9 |
exit; |
| 10 |
} |
| 11 |
|
| 12 |
class Render_Element_Action { |
| 13 |
const ACTION = 'render_atomic_element'; |
| 14 |
|
| 15 |
public function register( Ajax $ajax ): void { |
| 16 |
$ajax->register_ajax_action( self::ACTION, fn ( $request ) => $this->handle( $request ) ); |
| 17 |
} |
| 18 |
|
| 19 |
public function handle( $request ): array { |
| 20 |
$post_id = isset( $request['editor_post_id'] ) ? (int) $request['editor_post_id'] : 0; |
| 21 |
$element_data = $request['data'] ?? null; |
| 22 |
|
| 23 |
if ( ! $post_id || ! is_array( $element_data ) ) { |
| 24 |
throw new \Exception( 'Invalid request payload.' ); |
| 25 |
} |
| 26 |
|
| 27 |
$document = Plugin::$instance->documents->get_with_permissions( $post_id ); |
| 28 |
|
| 29 |
$editor = Plugin::$instance->editor; |
| 30 |
$is_edit_mode = $editor->is_edit_mode(); |
| 31 |
$editor->set_edit_mode( true ); |
| 32 |
|
| 33 |
Plugin::$instance->db->switch_to_query( [ |
| 34 |
'p' => $post_id, |
| 35 |
'post_type' => 'any', |
| 36 |
], true ); |
| 37 |
|
| 38 |
Plugin::$instance->documents->switch_to_document( $document ); |
| 39 |
|
| 40 |
do_action( 'elementor/atomic_widgets/before_render', $document ); |
| 41 |
|
| 42 |
try { |
| 43 |
$render_html = $this->render_element( $element_data ); |
| 44 |
} finally { |
| 45 |
do_action( 'elementor/atomic_widgets/after_render', $document ); |
| 46 |
$editor->set_edit_mode( $is_edit_mode ); |
| 47 |
Plugin::$instance->db->restore_current_query(); |
| 48 |
} |
| 49 |
|
| 50 |
return [ |
| 51 |
'render' => $render_html, |
| 52 |
]; |
| 53 |
} |
| 54 |
|
| 55 |
private function render_element( array $element_data ): string { |
| 56 |
$element = Plugin::$instance->elements_manager->create_element_instance( $element_data ); |
| 57 |
|
| 58 |
if ( ! $element ) { |
| 59 |
throw new \Exception( 'Element could not be instantiated.' ); |
| 60 |
} |
| 61 |
|
| 62 |
ob_start(); |
| 63 |
$element->print_element(); |
| 64 |
return (string) ob_get_clean(); |
| 65 |
} |
| 66 |
} |
| 67 |
|