WordPress: hooks into mouse events? - wordpress

I've spent a few hours on this but I'm not getting anywhere. I'm just starting on Wordpress, and I'd like a simple page where I click on something (a list item) and a textual description appears in a div somewhere else on the same page.
This would be trivial if I was writing plain HTML and JS, but I can't get my head around how to integrate this into WordPress. As far as I can make out, I have to write a plugin, but I can't find any handlers for mouse events in the hooks API. Or should I just hardcode an onclick into the HTML, and find somewhere to put some JavaScript code to handle it? Any advice appreciated...

Wordpress doesn't have mouse events/hooks. Wordpress hooks apply to the backend only, they are a way to interact with the WP core which is written in PHP (executed on the server, not the client).
Mouse events happen on the client side, so to achieve what you want you should register a Javascript file with wordpress via wp_register_script (http://codex.wordpress.org/Function_Reference/wp_register_script) and add your Javascript behaviour there.
You don't have to write a plugin, just add wp_register_script logic in your functions.php.

Vlad Cazacu is right, we dont have any hooks for javascript events and i am not sure if there is any option in other server side languages as well besides node.js. Anyways you can use jquery in the normal way with registering and enqueing the file. But if you want to have advanced interactivity then there are functions in wordpress that can do that for instance there's this function wp_localize_script, it is used with ajax to grabs the data as a javascript array/object and then converts it into php array/object which is then available to use in wordpress/php.

In short -
Add an id (and a styling class) to whatever you want a handler for
in the HTML
Register handlers in JS, as follows:
function fp_onload_js() {
var id = document.getElementById('myID');
id.addEventListener(
"click",
function() { myEventListener(); },
false);
}
Register/enqueue the file which contains your JS, in functions.php:
add_action('wp_enqueue_scripts', 'theme_enqueue_stuff');
function theme_enqueue_stuff() {
...
wp_enqueue_script(
'myHandle',
get_template_directory_uri() . '/path_to_my_js_file.js');
}
The tricky bit: you have to make sure that the event listener code is run after WordPress has constructed the DOM, after the IDs have been created. You need to run the JS after the page loads (see here). Basically, also in functions.php:
add_action('wp_footer', 'fp_onload_php');
function fp_onload_php() {
?>
<script type="text/javascript">
fp_onload_js();
</script>
<?php
}
And make sure you don't use the 'visual' tab in the WordPress editor - it will mess up your carefully-crafted HTML.

Related

How to implement JS callback for acf_register_block()

I'm currently in the process of updating a website so that it supports Wordpress Blocks (5.0+) via Advanced Custom Fields. I have a block which needs some JS and was wondering if there is a way to implement a JS callback either via acf_register_block() or register_block_type() so that a JS function is called when the block is added to a page in the CMS?
For anyone else looking, the easiest way so far would be to call the existing JS function for your block from within the block render template itself, however it should only call the function if the admin page is showing (so that it doesn't show inline scripts on the front end).
eg.
function slider_block_html(){
//html output here
if(is_admin()){
echo "<script>sliderInit();</script>";
};
}

WordPress Template "X": Change html inside of <head>

I'm pretty new to WordPress and want to remove some unneeded js/css files that are loaded inside of the html-head of the page.
In wp-content/themes/x/framework/views/header/base.php I found the following code:
<head>
<?php wp_head(); ?>
</head>
This obviously doesn't help me at all. I have no idea what WordPress' "wp_head()"-function does next. Isn't there some simple file where I can just write/edit simple HTML for the "head" somewhere?
wp_head() is a function that fires the wp_head action hook. Wordpress is built on action hooks and filters, which means that not only can plugins and themes add things to your setup through these hooks, but you have the ability to remove things as well. Most of this is done programmatically (in PHP) instead of there just being an html template, although that's not always the case... but it IS the case in your case.
Scripts and styles, for the most part, are enqueued through the wp_enqueue_scripts action hook. You'll want to perform your script removals here.
The problem is, you'll have to know the name the script was registered as before you can remove it. For instance, jQuery is registered as 'jquery'. Pretty simple, right? However, not all scripts are going to be that simple, and you'll have to browse through the code to find the registered handles (names) for those scripts. Styles are a bit easier, as when you inspect your page in the browser, styles will have an id attribute set to 'example-style-css'. Wordpress appends the '-css' to registered and enqueued styles, so the name of your style is actually 'example-style'.
In your theme's functions.php, you can dequeue scripts and styles so they won't be included on your page like so:
function stack_46669800_dequeue(){
wp_dequeue_script('the-script-you-want-to-remove');
wp_dequeue_style('the-style-you-want-to-remove');
}
add_action('wp_enqueue_scripts','stack_46669800_dequeue',100);
(Notice the 100 in the add_action function here... This is the 'priority', or the order in which all added actions are fired. Most are at 10, so I changed the priority here to 100 so this would be fired presumably later than whatever is enqueueing your unwanted scripts. You can't dequeue something that hasn't been enqueued yet.)

WordPress using different CSS - is this possible?

Bit is a basic question here but can someone confirm that this statement be confirmed: WordPress Pages (certain templates created within) can pull different CSS and JS?
Or - does WordPress only permit universal CSS + JS to be pulled across the entire site?
Thanks for clearing this up.
Depends on what plugin and themes you use. The WordPress/PHP functions wp_enqueue_style() and wp_enqueue_script() can be used literally by everyone (core, themes, plugins, you) to request WordPress to load styles or JavaSctript. You can combine this with WordPress functions to check whether the current page is something you want to filter for (post type, post, front-page, category archive, template, etc.). Here is an example to load a custom style if on front page :
if (is_front_page()) {
wp_enqueue_style('custom-frontpage', 'my/path/to/frontpage.css');
}
You will have to hook this piece of code to the wp_enqueue_script action so that WordPress executes it at the appropriate time. Here is an example using an anonymous function:
add_action('wp_enqueue_scripts', function() {
if (is_front_page())
wp_enqueue_style('custom-frontpage', 'my/path/to/frontpage.css');
});
You can also register your code as a "normal" function and pass the functions name to add_action() instead.
Edit: Enabling and disabling plugins is a bit more difficult, since you can never know how they implement their features without examining the source code. Here are my thoughts on this:
The plugin likely uses the above method (wp_enqueue_styles, wp_enqueue_scripts) to register it's styles and scripts. The plugin, since it assumes to be needed on all pages and posts, does this on every page without the conditional checking described earlier.
You could do one of the following to stop the plugin from doing this:
Identify the place where the plugin loads the styles and scripts and add the if-statement to only do so if the post-ID matches your desired post-ID. This method is bad since your changes are lost every time the plugin is updated.
Write a "counter plugin" (you could just add it to your theme or find a plugin that allowes you to add PHP to your page) that "dequeues" the style and script added by the plugin with inversed conditional tag
The counter-plugin approach would look as follows:
function custom_unregister_plugin() {
if (not the desired blog post) {
wp_dequeue_style('my-plugin-stylesheet-handle');
wp_dequeue_script('my-plugin-script-handle');
}
}
Make sure this function is executed after the enqueuing-code of your plugin by giving it a low priority in the same hook (999 is just an example, test it yourself):
add_action('wp_enqueue_scripts', 'custom_unregister_plugin', 999);
With wp_enqueue_style() you can add stylesheet (https://developer.wordpress.org/reference/functions/wp_enqueue_style/)
You can use it after detecting which template is used
function enqueue_custom_stylesheet() {
if(get_page_template() == 'contact.php')
wp_enqueue_style( 'contact-style', get_template_directory_uri().'/contact.css' );
}
add_action( 'wp_enqueue_scripts', 'enqueue_custom_stylesheet' );
You can use wp_enqueue_style for your CSS, wp_enqueue_script for your JS, wp_localize_script to pass variables from PHP to JS.
You can call these with hooks like:
funtion enqueue_my_stuff()
{
// your enqueue function calls
}
add_action('wp_enqueue_scripts','enqueue_my_stuff'); //front end
add_action('admin_enqueue_scripts','enqueue_my_stuff'); //admin panel
add_action('login_enqueue_scripts','enqueue_my_stuff'); //login screen

Bullet proof way to avoid jquery conflicts on wordpress plugins

I have been developing wordpress plugins for a while now and i always seem to get the following issues with all my plugins Jquery conflicts issues.
I have tried so many different ways to avoid these but i always get users contacting me saying when they have installed one off my plugins it has stopped another plugin from working aahhhhh.
I really want to get this sorted because i understand how frustrating this can be for people.
I always set and option or include wordpresses jquery, below is just an example not working code.
add_action( 'init', array( $this, 'include_jquery' ) );
function include_jquery(){
wp_deregister_script('jquery');
wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"), false, '1.7.1');
wp_enqueue_script('jquery');
}
Ok so after issues with this i now have a select option in the plugin admin to toggle yes or no to include jquery or not i know it is automatically installed but some users remove this, this works for some people but not all.
if you include the wordpress jquery i know you have to run your jquery with the following.
jQuery(document).ready(function ($) {
jQuery instead of the dollar sign $
i understand and have used jquery no conflict and tried and tested some if not all off these
http://api.jquery.com/jQuery.noConflict/
$.noConflict();
jQuery(document).ready(function($) {
// Code that uses jQuery's $ can follow here.
});
This as with the others works for some but not all users with conflicts arising still with certain users.
I am hoping that from this post some of us wordpress plugin developers could help out and post a bullet proof way to use wordpress and jquery within our plugins without getting conflict issues.
Thanks
Doesn't it work with a closure?
(function($){
// your plugin code
})(jQuery);
Read these parts of the codex :
Load a default WordPress script from a non-default location
jQuery noConflict wrappers
You should use wp_enqueue_scripts hook instead of init.
And you should use jQuery.noConflict(); instead of $.noConflict();.

Wordpress: Add to wp_head() from page

In Wordpress, I have a page template that uses a specific JS file and CSS file that no other part of the site uses. On this specific template page, is there any way to add these items to the head, before wp_head is called?
I realize I could use is_page_template() in a conditional but my head file is getting out of control.
If you look here http://codex.wordpress.org/Plugin_API/Action_Reference you can see that the hook called just before wp_head is get_header
So what you need to do is: add an action called on that hook, test if you are on the page that you want and if you are add the script and the css
This would happen in a plugin (not in the theme files like header.php or functions.php) and it would look something like this:
// call the function that adds your current script
add_action('get_header', 'add_that_script');
function add_that_script()
{
if (is_page(SOME_PAGE_IDENTIFIER)) // this is the page you need; check http://codex.wordpress.org/Function_Reference/is_page on how to use this function; you can provide as a parameter the id, title, name or an array..
{
wp_register_script( 'mycustomscript', 'http://www.example.com/script.css'); // register your script
wp_enqueue_script( 'mycustomscript' ); // enqueue it to be added in the head section
wp_register_style( 'mycustomstyle', 'http://www.example.com/example.css'); // register your css
wp_enqueue_style( 'mycustomstyle' ); // enqueue it to be added in the head section
}
}
You just need to replace the id for your page and the urls to the js file and to the css. Sure, maybe you want to test some other way if you are on the right page, but I think that this shows the idea.
What about using?
if(is_page('Your Page Name')):
// do something for me
endif;
i believe u can do it from functions.php. it's tidier if you do it from there. i suggest, unless that js file is really big, you are better off including it everywhere and use wp-minify to group all js files together into one.

Resources