Custom page template how to check is_page from functions.php?

Have a custom page template and trying to make the excerpt length dynamical depending on what page you are in.

Functions.php

Read More
<?php

function custom_excerpt_length($length){
    if (is_page(15)) {
    return 20;
    } else {
    return 150; 
    }
}
add_filter ( 'excerpt_length', 'custom_excerpt_length');

?>

cant get is_page to work from functions in my custom template page.

If i try echo is_page(15); in the static custom template value is true.

i’am little confused. Is it possible to call is_page() from functions.php (WP 3.1.2)

Related posts

Leave a Reply

3 comments

  1. Using is_page() inside functions.php is fine, possible and working, and if you are echoing is_page(15) and getting true, that means you are on a page with the ID of 15.

    the problem could be the priority parameter of the add_filter call, form the codex:

    Make sure to set the priority
    correctly, else the default WordPress
    filter on this function will run last
    and override what you set here.

    so change your code to :

    add_filter ( 'excerpt_length', 'custom_excerpt_length',999);
    
  2. I found solution based on url_to_postid function

    $url = explode('?', 'http://'.$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
    $ID = url_to_postid($url[0]);
    

    With this I can get post/page ID within the functions.php file.

  3. This has nothing to do with it being in the functions file, but rather that the function is being called within ‘The Loop’ because it is attached to the excerpt filter. is_page() will always return false inside the loop, so it’s not useful there.