Вопрос

I am trying to do what should be really simple, but somehow this is driving me mad. I try to have a code snippet only run on the front page. My site is set to have a static front page so I think my key to success is the conditional tag is_front_page(). However, I cannot get it to run as no matter what I try, I always end up with an error message in the console saying “ReferenceError: Can’t find variable: is_front_page”.

Here is my very basic code that I am using to only test if the conditional tag is working:

<?php
add_action('wp', function(){; ?>
<script>
    window.addEventListener("load", function() {
        if( is_front_page() ){
            console.log("front page")
        };
    }); 
</script>
<?php });

I already spend hours browsing through the internet and found that conditional tags only work after certain elements have been loaded, hence I hooked the function in ‘wp’. Also, I have read that some similar issues were resolved by restoring the original wp_query, so I added <?php wp_reset_query();?>, but again, no change. I have also tried using is_home(), but ended up with the same error message. Also, I have disabled all plugins, no change. It is really strange as I don’t even get neither is_home() nor is_front_page() to run, so I figure there must be some rather general issue.

Any help is appreciated. Regards, happy easter and stay safe! Dominik

Это было полезно?

Решение

There are several issues with your code. is_front_page() is a PHP function, you need to call it within <?php ?>.

The script need to be printed in HTML in order to make it work. Try this..

function wpse_363853_run_on_front() {
    ?>
    <script>
        window.addEventListener("load", function() {
            <?php if( is_front_page() ){ ?>
            console.log("front page");
            <?php } ?>
        });
    </script>
    <?php
}
add_action( 'wp_head', 'wpse_363853_run_on_front', 99 );

Just a note, avoid using anonymous functions.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с wordpress.stackexchange
scroll top