首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我无法访问wordpress插件的自定义模板中的帖子

我无法访问wordpress插件的自定义模板中的帖子
EN

Stack Overflow用户
提问于 2020-09-19 01:41:48
回答 1查看 52关注 0票数 0

我添加了以下代码,以便为我的食谱单页面使用自定义模板

代码语言:javascript
运行
复制
function override_single_template( $single_template ){
    global $post;
    if ($post->post_type == "recipes"){
        $single_template  = plugins_url('/recipe-single-page-template.php',__FILE__);
    }
    return $single_template;
}
add_filter( 'single_template', 'override_single_template',10);

在我的模板中,我添加了以下代码

代码语言:javascript
运行
复制
<?php
/*
Template Name: recipe-single-page-template
Template Post Type: recipes
*/
require_once("../../../wp-load.php");
?>

<?php get_header(); ?>

<?php echo $post->ID?>

<?php get_footer(); ?>

但是我没有访问post,回显post id将导致以下错误

代码语言:javascript
运行
复制
Trying to get property of non-object

var转储$post输出为空

代码语言:javascript
运行
复制
NULL

下面的代码将打印出我的自定义模板地址

代码语言:javascript
运行
复制
$current_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
echo $current_url;

顶级代码结果:

代码语言:javascript
运行
复制
https://charter.test/wp-content/plugins/recipe-plugin/templates/single-recipes.php

现在我该怎么办?

EN

回答 1

Stack Overflow用户

发布于 2020-09-19 06:45:46

您是否正在尝试将名为recipes的自定义帖子类型重定向到自定义模板?你不需要重写,默认情况下wordpress有一个内置的动态内容显示系统。

在您的示例中,在显示配方时,它将首先搜索single-recipe.php,如果未找到,则回退到single.php,如果未找到,则回退到404.php,最后再到index.php

您只需创建一个名为single-recipe.php的文件。

你的第二个问题是在你的文件中没有显示循环,你必须告诉wordpress,如果一个帖子存在,它应该检索它并将它呈现给你。为此,我们使用环路系统。

您的single-recipe.php文件应该如下所示:

代码语言:javascript
运行
复制
<?php
/**
* Get theme header
*/
get_header();

/**
* Start loop
*/
if ( have_posts() ):
while ( have_posts() ):
the_post();

/**
* If we find a post, output the tilte
*/
echo the_title().'<br/>';

/**
* End loop
*/
endwhile; 
endif;

/**
* Get theme footer
*/
get_footer(); ?>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63960474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档