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.

  • 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 May 8 at 19:30
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' );
  • Thank you so much. It works correctly. You are great!!! – Ali Bonyadi May 8 at 8:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.