1

I want to call a function on particular page like 'contact-us' from function.php of child theme.

i tried this function

 if( is_page('contact-us')) {

    echo "hello check"; 
     //either in about us, or contact, or management page is in view
 } else {
     echo "Not working";
 }

But getting else part on every page.

 if(is_page(37)){
     echo "page 37";
 } else {  echo "Not working" }

Getting else part

$current_url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

  $contactUsId = url_to_postid( $current_url ); 

  if($contactUsId == '37'){

echo "hello";
}

But this works , can any one one help me to know why first two function print else part.

2

The problem is that you're trying to use is_page(), a conditional function intended only to run adjacent to the query, too early. Try running your code inside a callback that 1) only fires on the front-end, 2) fires after the page has partially loaded. For instance, wp_head.

function prefix_run_on_contact_us() {
    if( is_page('contact-us')) {
        echo "hello check"; 
        //either in about us, or contact, or management page is in view
    } else {
        echo "Not working";
    }
}
add_action( 'wp_head', 'prefix_run_on_contact_us' );
| improve this answer | |
  • I also suggest making sure you've enabled WP_DEBUG while testing things like this. If you try to use is_page() before $wp_query is set, a _doing_it_wrong() notice describing this exact problem will get printed. ;-) – DrewAPicture Jun 28 '17 at 6:51
1

What hook do You use when You try use this functions? Did You think about it? It happen me all the time :) Here You have earliest possible hook in my opinion i tested few and they were too soon.

Solution 1:

add_action('parse_query', function () {

if( is_page('contact-us')) {

    echo "hello check";
    //either in about us, or contact, or management page is in view
} else {
    echo "Not working";
}});

Solution 2:

add_action('parse_query', function () {

    if( 'contact-us' == get_query_var('pagename') ) {
        echo "hello check";
        //either in about us, or contact, or management page is in view
    } else {
        echo "Not working";
    }
});
| improve this answer | |

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.