1: <?php
2: /**
3: * Routes EPL Single Listing / Listing Card / Archive Page Elementor documents
4: * into EPL's existing template pipeline.
5: *
6: * @package EPL
7: * @subpackage PageBuilders/Elementor
8: * @since 3.6.0
9: */
10:
11: // Exit if accessed directly.
12: if ( ! defined( 'ABSPATH' ) ) {
13: exit;
14: }
15:
16: /**
17: * Free-Elementor equivalent of Elementor Pro's Theme Builder, built entirely
18: * out of EPL's own template bypass actions:
19: *
20: * - Single listings: hooks `epl_single_template` when a published EPL Single
21: * Listing document matches the current post type.
22: * - Listing cards: renders an EPL Listing Card document on demand, only where
23: * a widget explicitly opts a loop into one (EPL Archive Results, EPL
24: * Listing Advanced, EPL Listings) — there is no site-wide auto-applied card.
25: * - Archive pages: swaps only the resolved template file on `template_include`
26: * for a page assigned as the listings archive, leaving the real main query,
27: * pagination and canonical URL untouched.
28: *
29: * Elementor Pro's Theme Builder always wins when a matching condition exists
30: * for the same location, via `elementor_location_exits()`.
31: */
32: class EPL_Elementor_Template_Router {
33:
34: /**
35: * Template IDs currently rendering, keyed by ID, to guard against
36: * recursive self-embedding.
37: *
38: * @var array
39: */
40: private static $rendering_cards = array();
41:
42: /**
43: * Template IDs whose per-document CSS has already been printed this
44: * request, keyed by ID.
45: *
46: * @var array
47: */
48: private static $css_rendered = array();
49:
50: /**
51: * Stack of Listing Card document IDs that widgets (e.g. EPL Archive
52: * Results, EPL Listing Advanced) have explicitly chosen for their own
53: * loop. A stack (not a single value) so a widget's own loop can safely
54: * nest inside another's without clobbering the outer choice.
55: *
56: * There is no site-wide "default card" — a card only ever renders where
57: * a widget explicitly opts into one here. Forcing a card (designed to
58: * sit in a grid column) onto every EPL loop indiscriminately — including
59: * ungridded ones like the plain [listing] shortcode — broke its layout,
60: * so that auto-upgrade path was removed entirely.
61: *
62: * @var int[]
63: */
64: private static $card_override_stack = array();
65:
66: /**
67: * The epl_loop_template_listing callback, hooked only while a card override is active.
68: *
69: * @since 3.6.0
70: * @var callable|null
71: */
72: private static $card_listener = null;
73:
74: /**
75: * Archive page currently routed for this request, for the wrapper
76: * template to read.
77: *
78: * @var int
79: */
80: private static $active_archive_page_id = 0;
81:
82: /**
83: * Resolved single-template IDs, keyed by post type, for this request.
84: *
85: * @var array
86: */
87: private $single_template_cache = array();
88:
89: /**
90: * Constructor.
91: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
92: */
93: public function __construct() {
94: add_action( 'wp', array( $this, 'maybe_route_single' ), 20 );
95:
96: // Hooked on `init`, not `wp`, so the `epl_loop_template_listing`
97: // listener is attached in every context that can call
98: // `epl_property_blog()` — including the Elementor editor's own
99: // admin-ajax canvas render, which never fires the front-end-only
100: // `wp` action but still needs card overrides to render for an
101: // accurate WYSIWYG preview.
102: add_action( 'init', array( $this, 'hook_card_override_listener' ), 20 );
103: add_filter( 'template_include', array( $this, 'maybe_route_archive' ), 10 );
104: add_filter( 'epl_elementor_preview_listing_id', array( $this, 'filter_preview_listing_id' ) );
105: }
106:
107: /**
108: * Whether Elementor Pro's Theme Builder has a matching condition for a
109: * location, so it can take priority over EPL's own routing.
110: *
111: * @param string $location Theme Builder location, e.g. 'single', 'archive'.
112: * @return bool
113: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
114: */
115: private static function pro_theme_builder_wins( $location ) {
116: return function_exists( 'elementor_location_exits' ) && elementor_location_exits( $location, true );
117: }
118:
119: /**
120: * Force a specific Listing Card document for the duration of the
121: * caller's own loop (e.g. EPL Archive Results' "Listing Card" control).
122: * Callers must always pair this with end_card_override(), even on early
123: * returns.
124: *
125: * @param int|array $override Either a single Listing Card document (post)
126: * ID applied to every listing type, or an
127: * array keyed by EPL post type (plus an
128: * optional `_default` key) for a per-listing-
129: * type override, e.g.
130: * `array( 'rural' => 123, '_default' => 456 )`.
131: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
132: * @since 3.6.0 Fix: hooks the card listener only while a widget's card is active.
133: */
134: public static function begin_card_override( $override ) {
135: if ( empty( self::$card_override_stack ) && self::$card_listener ) {
136: add_action( 'epl_loop_template_listing', self::$card_listener, 10, 1 );
137: }
138: self::$card_override_stack[] = is_array( $override ) ? $override : absint( $override );
139: }
140:
141: /**
142: * End a previously begun card override.
143: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
144: * @since 3.6.0 Fix: unhooks the card listener when no card is active.
145: */
146: public static function end_card_override() {
147: array_pop( self::$card_override_stack );
148: if ( empty( self::$card_override_stack ) && self::$card_listener ) {
149: remove_action( 'epl_loop_template_listing', self::$card_listener, 10 );
150: }
151: }
152:
153: /**
154: * The innermost active card override for a listing type, if any.
155: *
156: * @param string $post_type EPL post type of the listing currently rendering.
157: * @return int Template (post) ID, or 0 if none applies.
158: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
159: */
160: private static function get_card_override( $post_type = '' ) {
161: if ( empty( self::$card_override_stack ) ) {
162: return 0;
163: }
164:
165: $override = end( self::$card_override_stack );
166:
167: if ( ! is_array( $override ) ) {
168: return (int) $override;
169: }
170:
171: if ( $post_type && ! empty( $override[ $post_type ] ) ) {
172: return absint( $override[ $post_type ] );
173: }
174:
175: return ! empty( $override['_default'] ) ? absint( $override['_default'] ) : 0;
176: }
177:
178: /* ------------------------------------------------------------------ *
179: * Single listing routing.
180: * ------------------------------------------------------------------ */
181:
182: /**
183: * Hook the EPL Single Listing document matching the current listing's
184: * post type into `epl_single_template`, if one is published.
185: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
186: */
187: public function maybe_route_single() {
188: if ( EPL_Elementor::is_editor() || ! function_exists( 'is_epl_post_single' ) || ! is_epl_post_single() ) {
189: return;
190: }
191:
192: $post = get_post();
193: if ( ! $post || self::pro_theme_builder_wins( 'single' ) ) {
194: return;
195: }
196:
197: $template_id = $this->get_single_template_id( $post->post_type );
198: if ( ! $template_id || ! apply_filters( 'epl_elementor_single_template_enabled', true, $template_id, $post->post_type ) ) {
199: return;
200: }
201:
202: add_action(
203: 'wp_enqueue_scripts',
204: function () use ( $template_id ) {
205: \Elementor\Core\Files\CSS\Post::create( $template_id )->enqueue();
206: }
207: );
208:
209: add_action(
210: 'epl_single_template',
211: function () use ( $template_id ) {
212: echo '<div class="epl-elementor-single-template">';
213: echo \Elementor\Plugin::$instance->frontend->get_builder_content_for_display( $template_id, false ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Elementor content is sanitised on save.
214: echo '</div>';
215: }
216: );
217: }
218:
219: /**
220: * Resolve the EPL Single Listing document to use for a post type.
221: *
222: * Explicit `_epl_apply_post_types` matches are preferred over documents
223: * that apply to every listing type; ties are broken by most recently
224: * modified.
225: *
226: * @param string $post_type EPL post type.
227: * @return int Template (post) ID, or 0 if none.
228: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
229: * @since 3.6.0 Security: only templates by users who can edit theme options (administrators) are used.
230: */
231: private function get_single_template_id( $post_type ) {
232: if ( isset( $this->single_template_cache[ $post_type ] ) ) {
233: return $this->single_template_cache[ $post_type ];
234: }
235:
236: $forced = absint( apply_filters( 'epl_elementor_single_template_id', 0, $post_type ) );
237: if ( $forced ) {
238: $this->single_template_cache[ $post_type ] = $forced;
239: return $forced;
240: }
241:
242: $candidates = get_posts(
243: array(
244: 'post_type' => 'elementor_library',
245: 'post_status' => 'publish',
246: 'posts_per_page' => -1,
247: 'orderby' => 'modified',
248: 'order' => 'DESC',
249: 'fields' => 'ids',
250: 'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- elementor_library is small; matches existing EPL Elementor queries.
251: array(
252: 'key' => '_elementor_template_type',
253: 'value' => EPL_Elementor_Single_Document::TYPE,
254: ),
255: ),
256: )
257: );
258:
259: $fallback = 0;
260: foreach ( $candidates as $candidate_id ) {
261: // Only a template made by someone who manages the site's design can replace every listing page.
262: if ( ! user_can( (int) get_post_field( 'post_author', $candidate_id ), 'edit_theme_options' ) ) {
263: continue;
264: }
265:
266: $applies_to = (array) get_post_meta( $candidate_id, '_epl_apply_post_types', true );
267:
268: if ( in_array( $post_type, $applies_to, true ) ) {
269: $this->single_template_cache[ $post_type ] = (int) $candidate_id;
270: return $this->single_template_cache[ $post_type ];
271: }
272:
273: if ( ! $fallback && empty( $applies_to ) ) {
274: $fallback = (int) $candidate_id;
275: }
276: }
277:
278: $this->single_template_cache[ $post_type ] = $fallback;
279: return $fallback;
280: }
281:
282: /* ------------------------------------------------------------------ *
283: * Listing card rendering.
284: * ------------------------------------------------------------------ */
285:
286: /**
287: * Render an EPL Listing Card document for the current loop item.
288: *
289: * Safe to call repeatedly for different listings in the same loop: each
290: * template's CSS is only printed the first time it is used per request,
291: * and self-embedding is guarded against.
292: *
293: * @param int $template_id EPL Listing Card document (post) ID.
294: * @return bool True when the card was rendered, false when it could not be
295: * (missing, trashed, wrong type, or already rendering) so the
296: * caller can fall back rather than emit an empty listing.
297: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
298: */
299: public static function render_card( $template_id ) {
300: $template_id = absint( $template_id );
301:
302: if ( ! self::is_renderable_card( $template_id ) || isset( self::$rendering_cards[ $template_id ] ) ) {
303: return false;
304: }
305:
306: self::$rendering_cards[ $template_id ] = true;
307:
308: $with_css = empty( self::$css_rendered[ $template_id ] );
309: self::$css_rendered[ $template_id ] = true;
310:
311: if ( $with_css ) {
312: \Elementor\Core\Files\CSS\Post::create( $template_id )->enqueue();
313: }
314:
315: // Force nested dynamic/global elements to render fully inline rather
316: // than as an unresolved `[elementor-element]` placeholder, since this
317: // output does not pass back through `the_content`.
318: add_filter( 'elementor/element/should_render_shortcode', '__return_false' );
319: echo \Elementor\Plugin::$instance->frontend->get_builder_content_for_display( $template_id, false ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Elementor content is sanitised on save.
320: remove_filter( 'elementor/element/should_render_shortcode', '__return_false' );
321:
322: unset( self::$rendering_cards[ $template_id ] );
323:
324: return true;
325: }
326:
327: /**
328: * Whether a post ID is a usable EPL Listing Card document.
329: *
330: * A card chosen in a widget can be trashed or deleted later, and the widget
331: * keeps the stale ID until the page is re-saved.
332: *
333: * @param int $template_id Candidate card document (post) ID.
334: * @return bool
335: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
336: */
337: public static function is_renderable_card( $template_id ) {
338: $template_id = absint( $template_id );
339:
340: if ( ! $template_id || 'publish' !== get_post_status( $template_id ) ) {
341: return false;
342: }
343:
344: return EPL_Elementor_Loop_Card_Document::TYPE === get_post_meta( $template_id, '_elementor_template_type', true );
345: }
346:
347: /**
348: * Listen on `epl_loop_template_listing` so a widget's own explicit card
349: * override (see begin_card_override()) can render on this hook. There is
350: * no site-wide default card to fall back to — with no override active,
351: * this defers straight back to EPL's normal PHP template, identical to
352: * the hook not being attached at all.
353: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
354: * @since 3.6.0 Fix: no longer hooks epl_loop_template_listing on every request, which stopped epl_loop_template callbacks from themes and add-ons on Elementor sites.
355: */
356: public function hook_card_override_listener() {
357: // Hooked only while a widget renders with its own card (begin_card_override()), so themes
358: // and add-ons using epl_loop_template keep working everywhere else.
359: self::$card_listener = array( $this, 'render_card_override' );
360: }
361:
362: /**
363: * `epl_loop_template_listing` callback: render a widget's own card
364: * override when one is active, otherwise fall back to EPL's normal PHP
365: * loop template — exactly as if nothing were hooked on this action.
366: *
367: * @param array $vars The `epl_property_blog()` local variables (via `get_defined_vars()`).
368: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
369: */
370: public function render_card_override( $vars ) {
371: $post_type = isset( $vars['property']->post->post_type ) ? $vars['property']->post->post_type : '';
372: $override = self::get_card_override( $post_type );
373: if ( $override && self::render_card( $override ) ) {
374: return;
375: }
376:
377: $this->render_php_fallback( $vars );
378: }
379:
380: /**
381: * Reproduce `epl_property_blog()`'s own PHP-template fallback.
382: *
383: * @param array $vars The `epl_property_blog()` local variables (via `get_defined_vars()`).
384: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
385: */
386: private function render_php_fallback( $vars ) {
387: $template = isset( $vars['template'] ) ? $vars['template'] : 'default';
388: $default_value = isset( $vars['default_value'] ) ? $vars['default_value'] : 'default';
389: $template_name = apply_filters( 'epl_property_blog_template', 'loop-listing-blog-' . $template . '.php', $vars );
390: epl_get_template_part( $template_name, array(), 'loop-listing-blog-' . $default_value . '.php' );
391: }
392:
393: /**
394: * Editor-preview support: let an EPL Single Listing / Listing Card
395: * document's "Preview Listing ID" control drive `get_preview_property()`.
396: *
397: * @param int $requested_id Previously requested preview listing ID.
398: * @return int
399: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
400: */
401: public function filter_preview_listing_id( $requested_id ) {
402: if ( $requested_id || ! isset( \Elementor\Plugin::$instance->documents ) ) {
403: return $requested_id;
404: }
405:
406: $document = \Elementor\Plugin::$instance->documents->get_current();
407: if ( ! $document || ! in_array( $document->get_name(), array( EPL_Elementor_Single_Document::TYPE, EPL_Elementor_Loop_Card_Document::TYPE ), true ) ) {
408: return $requested_id;
409: }
410:
411: return absint( $document->get_settings( 'epl_preview_listing' ) );
412: }
413:
414: /* ------------------------------------------------------------------ *
415: * Archive pages.
416: * ------------------------------------------------------------------ */
417:
418: /**
419: * The archive page currently routed for this request, for the wrapper
420: * template to read.
421: *
422: * @return int Page ID, or 0.
423: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
424: */
425: public static function get_active_archive_page_id() {
426: return self::$active_archive_page_id;
427: }
428:
429: /**
430: * Swap in the Archive Page wrapper template when the current request is
431: * an EPL archive/search/taxonomy request and a page has been assigned.
432: *
433: * Registered at the same `template_include` priority as, but after,
434: * EPL's own `epl_load_core_templates()` so this sees EPL's resolved pick,
435: * and before Elementor Pro's Theme Builder (priority 11) so Pro keeps
436: * taking priority when it has a matching condition.
437: *
438: * @param string $template Template file resolved so far.
439: * @return string
440: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
441: */
442: public function maybe_route_archive( $template ) {
443: if ( EPL_Elementor::is_editor() ) {
444: return $template;
445: }
446:
447: $page_id = $this->resolve_archive_page_id();
448: if ( ! $page_id || self::pro_theme_builder_wins( 'archive' ) ) {
449: return $template;
450: }
451:
452: self::$active_archive_page_id = $page_id;
453:
454: add_action(
455: 'wp_enqueue_scripts',
456: function () use ( $page_id ) {
457: if ( class_exists( '\Elementor\Core\Files\CSS\Post' ) ) {
458: \Elementor\Core\Files\CSS\Post::create( $page_id )->enqueue();
459: }
460: }
461: );
462:
463: return EPL_PATH_TEMPLATES_POST_TYPES . 'elementor/archive-page.php';
464: }
465:
466: /**
467: * Work out which EPL listing type the current archive/search/taxonomy
468: * request is showing, so a per-listing-type archive page can be resolved.
469: *
470: * Post type archives report their own type directly. Search and taxonomy
471: * requests can legitimately span several listing types at once, so they
472: * only report a type when the query is scoped to exactly one — otherwise
473: * there is no single correct per-type page and the default is used.
474: *
475: * @return string Post type key, or '' when it cannot be narrowed to one.
476: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
477: */
478: private function get_queried_listing_type() {
479: $active = array_keys( epl_get_active_post_types() );
480:
481: foreach ( $active as $post_type ) {
482: if ( is_post_type_archive( $post_type ) ) {
483: return $post_type;
484: }
485: }
486:
487: $queried = get_query_var( 'post_type' );
488: $queried = array_values( array_intersect( array_filter( (array) $queried ), $active ) );
489:
490: return ( 1 === count( $queried ) ) ? sanitize_key( $queried[0] ) : '';
491: }
492:
493: /**
494: * Resolve the archive page assigned for the current request, honouring
495: * the "apply to search" / "apply to taxonomy" settings.
496: *
497: * @return int Page ID, or 0 if the archive page feature does not apply.
498: * @since 3.6.0 New: Elementor templates for free Elementor (beta).
499: * @since 3.6.0 Security: a password protected page isn't used as the archive.
500: */
501: private function resolve_archive_page_id() {
502: if ( 'yes' !== epl_get_option( 'epl_archive_page_enabled', 'no' ) ) {
503: return 0;
504: }
505:
506: $is_archive = function_exists( 'is_epl_post_archive' ) && is_epl_post_archive();
507: $is_search = function_exists( 'epl_is_search' ) && epl_is_search() && 'yes' === epl_get_option( 'epl_archive_page_apply_search', 'yes' );
508: $is_taxonomy = ( is_tax( 'location' ) || is_tax( 'tax_feature' ) || is_tax( 'tax_business_listing' ) ) && 'yes' === epl_get_option( 'epl_archive_page_apply_taxonomy', 'yes' );
509:
510: if ( ! $is_archive && ! $is_search && ! $is_taxonomy ) {
511: return 0;
512: }
513:
514: // A listing type can nominate its own archive page; otherwise the
515: // single site-wide "Listings Archive Page" is used for every type.
516: $page_id = 0;
517:
518: $queried_type = $this->get_queried_listing_type();
519: if ( $queried_type ) {
520: $page_id = absint( epl_get_option( 'epl_archive_page_id_' . $queried_type, '' ) );
521: }
522:
523: if ( ! $page_id ) {
524: $page_id = absint( epl_get_option( 'epl_archive_page_id', '' ) );
525: }
526:
527: $page_id = absint( apply_filters( 'epl_archive_page_id', $page_id, $queried_type ) );
528: if ( ! $page_id ) {
529: return 0;
530: }
531:
532: $page = get_post( $page_id );
533: if ( ! $page || 'page' !== $page->post_type || 'publish' !== $page->post_status || post_password_required( $page ) ) {
534: return 0;
535: }
536:
537: return $page_id;
538: }
539: }
540: