【问题标题】:How can I customize 404 page in Wordpress in admin page without plugins?如何在没有插件的情况下在管理页面中自定义 Wordpress 中的 404 页面?
【发布时间】:2018-08-08 17:04:52
【问题描述】:

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

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

404.php

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

header.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 文件,对吧?

【问题讨论】:

    标签: wordpress wordpress-theming custom-wordpress-pages


    【解决方案1】:

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

    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.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 )

    【讨论】:

    • 你能贴出你的 404 文件的代码吗?很难准确理解您的意思。
    • 啊,我明白了,你试过我的解决方案了吗? $page-&gt;post_content 变量实际上只包含放在可视化编辑器中的内容。它不会抓取整个页面的标记,因此您可以重复使用自定义字段并在其周围包含您想要的其他文件
    • 是的,我明白这一点,但在这种情况下,我应该重构 header.php 以使用 $page-&gt;some_field 而当前版本的 header.php 使用 the_field 函数。
    • 哦,我误会了。我有点好奇为什么每一页都有自己的风格——但我离题了。我已经通过编辑更新了答案。本质上,您可以将任何想要的 ID 传递给the_field,这样如果是 404 页面,您可以更新它,否则使用当前 ID。
    猜你喜欢
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 2012-07-22
    • 2014-09-15
    • 2014-01-26
    相关资源
    最近更新 更多