Wordpress插件动态错误页面

时间:2013-01-26 18:03:43

标签: php wordpress plugins filter wordpress-plugin

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

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

感谢您的时间。

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

3 个答案:

答案 0 :(得分:1)

解决方案取决于404.php文件的内容。如果此文件包含静态文本,例如

_e( 'It seems we can’t find what you’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功能来显示页面内容,您应该检查它们支持哪些过滤器。

答案 1 :(得分:1)

您可以使用条件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模板标记。

答案 2 :(得分: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(); ?>
相关问题