Files

55 lines
1.5 KiB
PHP

<?php
/**
* Generic page-template URL helpers.
*
* Page-template assignment is the source of truth for resolving public URLs
* for custom page templates (submit form, etc.).
*
* @package AKSRT
*/
defined('ABSPATH') || exit;
if (!function_exists('aksrt_get_page_url_by_template')) :
/**
* Resolve the first published page that uses a given page template file.
*
* @param string $template_file Relative theme template path (e.g. templates/pages/page-submit.php).
*/
function aksrt_get_page_url_by_template(string $template_file): string {
$template_file = ltrim(str_replace('\\', '/', $template_file), '/');
if ($template_file === '') {
return '';
}
static $cache = [];
if (array_key_exists($template_file, $cache)) {
return $cache[$template_file];
}
$pages = get_posts([
'post_type' => 'page',
'post_status' => 'publish',
'posts_per_page' => 1,
'orderby' => 'menu_order title',
'order' => 'ASC',
'no_found_rows' => true,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'meta_key' => '_wp_page_template',
'meta_value' => $template_file,
]);
$url = '';
if (!empty($pages[0]) && $pages[0] instanceof WP_Post) {
$permalink = get_permalink($pages[0]);
if (is_string($permalink) && $permalink !== '') {
$url = $permalink;
}
}
$cache[$template_file] = $url;
return $url;
}
endif;