Despite the fact that there is nothing wrong with PHP and JavaScript, I personally find it rather inconvenient to read and modify, and also makes it difficult to move this code. For example, if you decide to export this JavaScript to an external file, which has many advantages:
<script src="myjs.js.php"></script>
This becomes awkward if your JavaScript needs to know certain values ββin order to calculate in_category('Collection') , since you need to start using GET parameters (if you are not dependent on session variables that can get quite complex and unpredictable, especially with queries resources):
<script src="myjs.js.php?random_vars_required=123"></script>
Another thing to be wary of is that when it has a JavaScript file that changes its contents depending on the server-side logic, you have to be careful that the browser caches (to avoid these problems, this basically means that you have to change the request url for every possible result of the js file). i.e.
<script src="myjs.js.php?collection=true"></script> <script src="myjs.js.php?collection=false"></script>
Another drawback is mixing PHP with JS, and you will probably end up duplicating PHP code in many places that go against the DRY principal. This is why the proposed "javascript export data" is a much nicer idea. However, it is best to avoid variables in the global js namespace if possible. Avoiding a global namespace can seem complicated, although if you need to share logic with multiple JavaScript files and don't want to export your variables to the top of each file.
another opportunity
If the logic you are testing is purely logical, and it also focuses on page classification (or sub-region classification), the following is a good way to deal with what you are trying to achieve. This is nice mainly because it holds your PHP and HTML together and your JS is separate.
In any template that you use to create external HTML, you should put the following:
<?php $classes = array(); if ( in_category('Collection') ) { $classes[] = 'collection'; } $classes = implode(' ', $classes); ?> <body class="<?php echo $classes; ?>"></body>
Then in your JavaScript / jQuery:
if ( $('body.collection').length ) { /// if collection sub page } else { /// else do otherwise }
If you do not want to add a class to the body element, you can always define your logical check based on what already exists on one version of the page, and not on another. Although I personally like to keep things clean and resort to such checks when I know that HTML markup will not change in the future.
Almost all browsers that the larger world needs to worry about today support multiple element classes. So this means that even if you have a few things you want to check, if that makes sense, you can put these classes in your html or body tag and use the jQuery Sizzle implementation to find them for you.