最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Conditional tag doesn't work in WordPress plugin

programmeradmin1浏览0评论

I'm developing a plugin which can change the whole content of a special page in WordPress with an image. My plugin's code is here:

<?php
/**
 * Plugin Name: Test1234
 */
function set_header_page(){
    if( is_page('img') ){
    header("Content-Type: image/jpg");
    }    
}
add_action('init', 'set_header_page');

function replace_image_content(){
    if( is_page('img') ){
        $image = plugin_dir_url(__FILE__).'1404-1.jpg';
        readfile($image);
    }
}
add_action('wp_loaded', 'replace_image_content');

My problem is here: In both functions when I add if( is_page('img') ) nothing happens. Without if( is_page('img') ) I see my image in all pages. This shows me in my code everything depends on 'if(is_page( 'pagename' ) )'. How can I solve it?

Note that I tried it by if( $post->ID == 11 ), too.

Thank you in advance.

I'm developing a plugin which can change the whole content of a special page in WordPress with an image. My plugin's code is here:

<?php
/**
 * Plugin Name: Test1234
 */
function set_header_page(){
    if( is_page('img') ){
    header("Content-Type: image/jpg");
    }    
}
add_action('init', 'set_header_page');

function replace_image_content(){
    if( is_page('img') ){
        $image = plugin_dir_url(__FILE__).'1404-1.jpg';
        readfile($image);
    }
}
add_action('wp_loaded', 'replace_image_content');

My problem is here: In both functions when I add if( is_page('img') ) nothing happens. Without if( is_page('img') ) I see my image in all pages. This shows me in my code everything depends on 'if(is_page( 'pagename' ) )'. How can I solve it?

Note that I tried it by if( $post->ID == 11 ), too.

Thank you in advance.

Share Improve this question asked May 8, 2019 at 7:51 Ali BonyadiAli Bonyadi 32 bronze badges 1
  • readfile() does support URL addresses; however, looking at your code, you should use plugin_dir_path() and not plugin_dir_url(). Just my 1 cent. ;) – Sally CJ Commented May 8, 2019 at 19:30
Add a comment  | 

1 Answer 1

Reset to default 3

Both those hooks are too early to use is_page(). WordPress hasn't determined which page is being loaded yet, so it can't check the current page. Try template_redirect for both:

/**
 * Plugin Name: Test1234
 */
function replace_image_content(){
    if ( is_page( 'img' ) ) {
        header( 'Content-Type: image/jpg' );

        $image = plugin_dir_url(__FILE__) . '1404-1.jpg';

        readfile( $image );

        exit;
    }
}
add_action( 'template_redirect', 'replace_image_content' );
发布评论

评论列表(0)

  1. 暂无评论