How to implement JS callback for acf_register_block() - wordpress

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>";
};
}

Related

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

WordPress: hooks into mouse events?

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.

WordPress Filter: Replace full content before page renders

I'm trying to mesh Mustache Templating Engine with WordPress. So far, I have been very successful using the_content as a filter to parse my template tags e.g. {{ something }}.
However, if let’s say, a developer hardcodes the template tags directly into the page template e.g. loop-page, the_content doesn’t capture the hardcoded tags.
Is there a filter that will allow me to capture the content of the whole page template including the content?
If you're writing a plugin, you can use PHP function ob_start() to cache whole buffered content. After that you can use callback function to return replaced content.
Use triggers (action's) init or after_setup_theme for your script.

Add dynamic content before the loop in Wordpress

I'm developing a content slider for Wordpress and I would know how is possible to put this content slider (as html content) into the body before the loop.
I tried to filter the content with add_filter('the_content', 'functionName), but I get the content slider before each post.
If you use add_filter('the_content'), your function will be called everytime the content of a post is output, whether a single post or a series of posts in a loop. If you need to "hook" before any post content is output in a page, the only dynamic parts of all WP themes you can reach are get_header() or get_sidebar() (or event get_footer). So your best luck would be not to use a filter with the content, but an action, with get_header, like this :
add_action('get_header', 'your_function'); // Add priority & param args if necessary
The problem is that this gets executed before header.php is called, and usually, the body tag is opened in header.php...
That is if you cannot modify the theme itself. Otherwise, you can easily add an action in the theme itself and execute it where you want.
Another technique would be to add your html content after document is ready, through JavaScript which you can output in the footer.

How do I load jQuery for only one specific page in my WordPress theme?

I'm fiddling with a WordPress theme. I'm aware I can use wp_enqueue_script in my header.php to load WordPress's supplied jQuery library.
I was just going to use wp_enqueue_script in my header, but it seems inefficient when I only want to use it on a particular Page (just on one single page with a particular page_id.)
Given that, what's the best way of including jQuery only on one particular Page?
Presumably I can't do page_id detection in header.php, because that won't be in The Loop, right? But I'm guessing I'm missing some fairly obvious method -- I'm fairly new to theme development...
Thanks!
Yes you can, is_page doesn't need to be called in The Loop, since it doesn't change when The Loop runs. So is_page(42) will only return TRUE if you're on the page with id 42. It also works with the page title or name (slug), which might be more future-proof if you ever replace delete this page and replace it with a new one with the same slug.
here is an article about dynamic body ids
http://perishablepress.com/press/2009/05/26/dynamic-body-class-id-php-wordpress/
after you get your page name you can add a conditional statement in your template index.php that says something like this in your page header or before the closing body tag:
// $page_name would be the page name you extracted with a function from the post
if($page_name === 'about'){
echo '<script type="text/javascript" src="jquery.js"></script>'
}

Resources