‘Run snippet everywhere’ doesn’t place any restrictions on where the snippet runs on your site.
If it looks like your code is not running on the back-end, it’s because your code doesn’t affect the back-end. A common mistake here is using wp_head
instead of admin_head
when adding CSS/JS.
Thread Starter
pickme
(@pickme)
I am using the following code in the snippet field:
function hide_checkbox_li() {
if ( is_page ( array( '140', '141' ) ) ) {
?>
<script type="text/javascript">
jQuery code here
</script>
<?php
}
}
add_action('wp_footer', 'hide_checkbox_li', 100);
add_action('admin_head', 'hide_checkbox_li', 10);
I want the code to run on frontend only for pages with ID’s 140 and 141 as well as WP backend. Adding an additional add_filter function will this be correct and secure?
Thank you
-
This reply was modified 1 year, 5 months ago by
pickme.
If you want to load the code in the footer, you can use admin_footer
instead of admin_head
.
The problem is that your is_page()
check is restricting the code to the front-end. Adding in an is_admin()
check separated by the OR ||
operator will allow it to run in both environments:
function hide_checkbox_li() {
if ( is_admin() || is_page( array( '140', '141' ) ) ) {
?>
<script type="text/javascript">
//jQuery code here
</script>
<?php
}
}
add_action( 'wp_footer', 'hide_checkbox_li', 100 );
add_action( 'admin_head', 'hide_checkbox_li', 10 );
Thread Starter
pickme
(@pickme)
Perfect!
I will use admin_footer
for the code to be placed at bottom of page to speedup loading of wp backend.
I tested and works! 🙂
I was checking WordPress Code Reference for this solution since I noticed that the code cannot run on both environments when using is_page
.
Today I read this article about is_admin
https://dev.to/lucagrandicelli/why-isadmin-is-totally-unsafe-for-your-wordpress-development-1le1
Could you please let me know if using is_admin will make wordpress insecure?
Thank you very much for your help @bungeshea !
-
This reply was modified 1 year, 5 months ago by
pickme.
No, the advice in that article does not apply here, because you are just using is_admin()
to determine whether to output some content in a particular part of your site.
The article you linked it specifically talking about using is_admin()
for security checks, e.g. to check whether a user has administrator permissions, which is not what we are doing.
Thread Starter
pickme
(@pickme)
That’s what I thought but I was not completely sure!
Thanks a lot for your help and clarifying this @bungeshea 🙂
-
This reply was modified 1 year, 5 months ago by
pickme.