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 |1 Answer
Reset to default 3Both 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' );
readfile()
does support URL addresses; however, looking at your code, you should useplugin_dir_path()
and notplugin_dir_url()
. Just my 1 cent. ;) – Sally CJ Commented May 8, 2019 at 19:30