首页 > 解决方案 > 如何在没有插件的情况下在管理页面中自定义 Wordpress 中的 404 页面?

问题描述

所以,我在主题文件夹中创建了 404.php 页面,现在想要显示应该可以在管理页面中编辑的内容。我在谷歌上找到的每条建议都说我需要插件,但我只想显示内容字段,仅此而已。我不想为这种琐碎的事情安装插件。我怎样才能做到这一点?

更新:
忘了提到 404 页面使用了其他页面也使用的代码块,并且还使用了the_field读取这些页面和 404 页面的自定义字段的函数。如果我创建另一个404 Content页面,这意味着我无法重用这些块,因为它们读取了页面的字段,而不是404 Content.

404.php

@include 'header.php'
...other code

头文件.php

<html lang="ru">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link rel="stylesheet" type="text/css" href="build/css/<?php the_field('style') ?>Styles.css">
    <?php wp_head(); ?>
  </head>
  <body>

因此,每个内容页面都有自定义字段,其中包含应加载的 css 文件的名称。如果我使用404 Content页面,这意味着我不能重用header.php文件,对吗?

标签: wordpresswordpress-themingcustom-wordpress-pages

解决方案


你当然不需要插件,有几种方法可以做到这一点。最简单的“捷径”方法是创建一个单独的“404 内容”页面,获取该页面的 ID,然后使用以下方法将内容导入您的404.php文件中:get_post()get_page_by_title()

404.php:

<?php
    /**
     * Handle 404 errors with this file
     */
    
    <!-- Some markup and/or functions here, get_header() etc. -->

    // Display Page Content
    $404_page = get_page_by_title( '404 Content' ); // Or use $page = get_post(123) where 123 is the ID of your 404 Content Page
    
    echo apply_filters( 'the_content', $404_page->post_content );

    <!-- Some markup and/or functions here, get_footer() etc. -->
?>

或者,您可以使用该is_404()功能以不同的方式处理 404 页面,但由于您已经拥有自定义的 404 页面404.php,因此上述方法可能是最简单的。


更新:

由于您的通用header.php文件需要 ACF 的the_field()功能,您可能需要稍微重构一下。您会在文档中注意到它允许 3 个参数,第二个是$post_id.

您可以在header.php文件中使用以下内容动态修改 ID:

if( is_404() ){
    $page = get_page_by_title( '404 Content' );
    $id   = $page->ID;
} else {
    $id = get_the_ID();
}

然后更新您the_field( 'some_field' )the_field( 'some_field', $id )


推荐阅读