Sage 10 version of Virtual page with Rewirte Api without Custom Post Type - #4 by mmirus by @mmirus
Example of how to add a virtual page with Sage 10
In filters.php or wherever you like:
add_action('init', function () {
add_rewrite_endpoint('about', EP_PERMALINK);
});
add_filter('template_include', function ($template) {
global $wp_query;
if (!isset($wp_query->query_vars['about'])) {
return $template;
}
$app = app();
$app['sage.view'] = 'pages.about'; # For resources/views/pages/about.blade.php
$app['sage.data'] = [
'title' => 'About',
'description' => 'About description',
];
return $template;
}, 101);
add_filter('the_posts', function (array $posts, \WP_Query $query) {
if (!isset($query->query_vars['about'])) {
return $posts;
}
$title = 'about';
$post = [
'ID' => -100,
'post_title' => $title,
'post_name' => sanitize_title($title),
'post_content' => '',
'post_excerpt' => '',
'post_parent' => 0,
'menu_order' => 0,
'post_type' => 'page',
'post_status' => 'publish',
'comment_status' => 'closed',
'ping_status' => 'closed',
'comment_count' => 0,
'post_password' => '',
'to_ping' => '',
'pinged' => '',
'guid' => home_url($query->getUrl()),
'post_date' => current_time('mysql'),
'post_date_gmt' => current_time('mysql', 1),
'post_author' => 0,
'is_virtual' => true,
'filter' => 'raw',
];
return [
new \WP_Post((object)$post),
];
}, 10, 2);
Blade template located at resources/views/pages/about.blade.php
:
@extends('layouts.app')
@section('content')
👋
@endsection
Use sage-virtual-pages
We’ve created an Acorn package called sage-virtual-pages
that’s available to our GitHub sponsors to simplify adding virtual pages.
It supports outputting The SEO Framework meta data right now, and will soon also support sitemaps and Yoast.
Example config:
<?php
return [
[
'slug' => 'placeholder-virtual-page',
'title' => 'Placeholder Page',
'excerpt' => 'This is an example virtual page.',
'sitemap' => true,
],
];
Sponsor Roots on GitHub to get access to this package
Resources:
- https://metabox.io/how-to-create-a-virtual-page-in-wordpress/
- https://coderwall.com/p/fwea7g/create-wordpress-virtual-page-on-the-fly
- https://gist.github.com/gmazzap/1efe17a8cb573e19c086
- https://wordpress.stackexchange.com/questions/139071/plugin-generated-virtual-pages
- https://barn2.co.uk/create-fake-wordpress-post-fly/