【问题标题】:Wordpress Plugin Dynamic Error PageWordpress 插件动态错误页面
【发布时间】:2013-01-10 11:36:56
【问题描述】:

我可以在 Wordpress 插件中使用什么操作或过滤器来动态替换 404 错误页面的内容(即不是页眉或页脚)?

基本上,我正在寻找与 the_content filter 等效的 404 错误页面,它将过滤现有页面的内容。

感谢您的宝贵时间。

注意:我知道我可以手动修改当前主题的404错误页面,但这不是我想要达到的效果。

【问题讨论】:

  • 很好的问题,但有点棘手,因为在404.php 模板中似乎没有共同的元素,我们可以以一种通用的方式挂钩......哦,一个想法突然出现,将研究。

标签: php plugins filter wordpress


【解决方案1】:

来自这个 WordPress 答案:How to control output of custom post type without modifying theme?

插件文件:

<?php
/*
Plugin Name: Plugin 404 Page
Plugin URI: http://stackoverflow.com/questions/14539884
Description: Use the plugin's template file to render a custom 404.php
Author: brasofilo
Author URI: https://wordpress.stackexchange.com/users/12615/brasofilo
Version: 2013.26.01
License: GPLv2
*/
class Universal_Template
{
    public function __construct()
    {       
        $this->url = plugins_url( '', __FILE__ );   
        $this->path = plugin_dir_path( __FILE__ );
        add_action( 'init', array( $this, 'init' ) );
   }

    public function init() 
    {
        add_filter( 'template_include', array( $this, 'template_404' ) );
    }

    public function template_404( $template ) 
    {
        if ( is_404() )
            $template = $this->path . '/404.php';

        return $template;
    }
}

$so_14539884 = new Universal_Template();

并且在插件文件夹中,有一个名为404.php的文件:

<?php
/**
 * The template for displaying 404 pages (Not Found).
 *
 * @package WordPress
 * @subpackage Twenty_Twelve
 * @since Twenty Twelve 1.0
 */

get_header(); ?>

    <div id="primary" class="site-content">
        MY 404!
    </div><!-- #primary -->

<?php get_footer(); ?>

【讨论】:

    【解决方案2】:

    解决方法取决于 404.php 文件的内容。如果这个文件包含静态文本,比如

    _e( 'It seems we can&rsquo;t find what you&rsquo;re looking for...', 'twentyeleven' );
    

    您可以添加自己的过滤器

    apply_filters( 'my_404_content', 'Default 404 message' );
    

    在functions.php(或插件)中

    add_filter( 'my_404_content', 'replace_404_message' );
    function replace_404_message($message) {
        return 'Error 404 - '.$message;
    }
    

    如果 404.php 使用内置的 WP 功能来显示页面内容,您应该检查它们支持哪些过滤器。

    【讨论】:

      【解决方案3】:

      您也许可以添加带有条件is_404 部分的the_content 过滤器:

      function content_404($content) {
        if (is_404()) {
          // do some stuff with $content
        }
        // no matter what,
        return $content;
      } 
      
      add_filter( 'the_content', 'content_404' );
      

      请注意,这确实假设404.php 页面模板有一个the_content 模板标签。

      【讨论】:

      • 有趣...不幸的是,似乎太多的404.php 模板不包含the_content 模板标签。无论如何,谢谢您的意见!
      猜你喜欢
      • 1970-01-01
      • 2012-12-14
      • 2016-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-08
      • 1970-01-01
      相关资源
      最近更新 更多