admin管理员组文章数量:1429436
Is there a way of loading a template file without having a post? I'm loading set of data via an API. Set up my index page but having a brain freeze with single template files as these posts are not in the WP registry/database.
// Template files
events-index.php
events-single.php
Events index:
<?php $events = $api_data // Data retrieved from API
if ( $upcoming_events->have_posts() ) :
while ( $upcoming_events->have_posts() ) : $upcoming_events->the_post();
$custom_link = sanitize_title( get_the_title() );
$custom_link = rtrim($custom_link, '/');
$custom_link .= '?' . get_the_ID(); ?>
<a href="<?php echo $custom_link; ?>">
// This link to a custom template file
<?php } ?>
Is there a way of loading a template file without having a post? I'm loading set of data via an API. Set up my index page but having a brain freeze with single template files as these posts are not in the WP registry/database.
// Template files
events-index.php
events-single.php
Events index:
<?php $events = $api_data // Data retrieved from API
if ( $upcoming_events->have_posts() ) :
while ( $upcoming_events->have_posts() ) : $upcoming_events->the_post();
$custom_link = sanitize_title( get_the_title() );
$custom_link = rtrim($custom_link, '/');
$custom_link .= '?' . get_the_ID(); ?>
<a href="<?php echo $custom_link; ?>">
// This link to a custom template file
<?php } ?>
Share
Improve this question
asked May 16, 2019 at 14:02
Abdul Sadik YalcinAbdul Sadik Yalcin
5571 gold badge4 silver badges8 bronze badges
2 Answers
Reset to default 2You could setup a custom rewrite rule using add_rewrite_rule and send these requests to a custom page.
Your URL structure could be /index-page/single-event-slug
The rule would point all of the single events to a separate page where you can then set your template events-single.php
.
Another option is to pass the events in as a query /index-page?event=single-event-slug
or /index-page?event=123
. You'd need to register this parameter with add_query_arg and then change your index template to use the event template via the template_include hook.
function prefix_register_query_var( $vars ) {
$vars[] = 'eid';
return $vars;
}
add_filter( 'query_vars', 'prefix_register_query_var' );
function prefix_rewrite_templates() {
if ( get_query_var( 'eid' ) ) {
add_filter( 'template_include', function() {
return get_template_directory() . '/events-single.php';
});
}
}
add_action( 'template_redirect', 'prefix_rewrite_templates' );
Add the $var
to the URL in the loop:
$url = add_query_arg( array(
'eid' => get_the_ID(),
) );
本文标签: Load template file without a post type
版权声明:本文标题:Load template file without a post type 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745487906a2660466.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论