Question

I am creating a theme and i have added custom hooks to make the developement easier. when using the code in functions it works in all pages. the code is below

add_action('before_footer','post_prev_nex');
function post_prev_nex(){
    the_post_navigation();
}

But when i try to put a conditional, it doesnt work.

if (is_singular()) {
    add_action('before_footer','post_prev_nex');
function post_prev_nex(){
    the_post_navigation();
}
}

what is the problem here. Thanks in advance

Was it helpful?

Solution

Put condition inside your function:

add_action('before_footer','post_prev_nex');
function post_prev_nex() {
    if (is_singular())
       the_post_navigation();
}

In your version is_singular() is executed when functions.php file is loaded, not while displaying the page.

OTHER TIPS

is_singular() won't work when placed directly into functions.php or a plugin, because WordPress has not determined what content is actually being requested when it loads themes and plugins. You need to perform the check later by putting it inside an action callback that occurs after WordPress has determined what the content is.

The simplest solution then is just to use the function inside the callback:

function post_prev_nex() {
    if ( is_singular() ) {
        the_post_navigation();
    }
}
add_action('before_footer','post_prev_nex');
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top