This category is for all advanced level students, who would like to code at an extensive level. Different methods of coding and many more aspects of coding could be learnt via this category. Hope you all enjoy.
Adding a hash to a file suffix is a common way to force the browser to update its cache.
Angular for example offers this option by default in its build process. Whenever you bundle your code with Angular you will see a hash suffix to the bundled files, which are results of hash functions on the file contents. You can then immediately deploy these files about browser caching without concerns.But not all frameworks offer this.
Svelte does not automatically bundle files with hash suffixes. You would need to install rollup-plugin-hash, for example. But I feel that a better method is to add the hash after bundling instead.
Often, after I bundle my code, I will need to copy it somewhere else on my machine before I deploy it to a live server. To do this I use gulp. Gulp is a great tool to create tasks and automate your work. My copy-output task using Gulp looks like this:
var fs = require('fs');
var gulp = require('gulp');
const del = require('del');
var json = JSON.parse(fs.readFileSync('./dist_folder_details.json')); // this file contains the destination of the bundles on my machine
gulp.task('copy-output', async () => {
var distFolder = json['dist-folder-js'];
await del([distFolder + '/**', '!' + distFolder],
{force: true}); // I used del (
https://www.npmjs.com/package/del) to remove
the current content
await new Promise((resolve, reject) => {
gulp.src('./public/build/*.js')
.pipe(gulp.dest(distFolder)) // I am copying the
new build files to the destination
.on("end", resolve);
});
});
So, all I need to do in order to add a hash suffix is to use gulp-hash:
var fs = require('fs');
var gulp = require('gulp');
const del = require('del');
var hash = require('gulp-hash'); // require it
var json = JSON.parse(fs.readFileSync('./dist_folder_details.json'));
var json = JSON.parse(fs.readFileSync('./dist_folder_details.json'));
gulp.task('copy-output', async () => {
var distFolder = json['dist-folder-js'];
await del([distFolder + '/**', '!' + distFolder],
{force: true});
await new Promise((resolve, reject) => {
gulp.src('./public/build/*.js')
.pipe(hash()) // Use it
.pipe(gulp.dest(distFolder))
.on("end", resolve);
});
});
Now hashing is integrated into my deploy process. No need to install framework-specific hashing packages.
Thoughts? Comments? Suggestions? Please let me know below!!
I wanted to check what would be easier: implementing a progress bar with jQuery or with Svelte. So I implemented both. I intended to create a progress bar that goes through some list of items so it would also have control buttons, one for start, one for pausing and another for resetting.
The control buttons need to be user friendly, so when the progress bar is loading the start button and reset button need to be disabled, when paused the pause button should be disabled and when done the reset button should be the only one to be enabled.
As you can see I’m struggling to maintain the logic I wanted, the code is both complicated to write and read.
Attempt 02- with custom events:
With custom events, the code is a little longer but much more readable and conceptually easier to write. I basically have the progress bar listen to four events: loading, pause, reset, and done. Each of the buttons trigger these events, and the ‘done’ event is triggered when we’re completed with all the items. Final code looks like this:
To sum up, without custom events jQuery is not easy to construct, but custom events make it a little better. Next: Svelte.
Svelte
I’m rather new to Svelte but I managed to create my progress bar with three components. The top component is the app itself which contains all of the logic connecting the control buttons to the progress bar. Upon starting the app I will go through some prefixed number of items (in this case 5), and will set a timeout between each to simulate some asynchronous action.
The other two components are the control buttons and the progress bar.
In order to get it right I had to import the bootstrap SCSS into my app:
As you can see, the main logic here deals with disabling and enabling the buttons whenever necessary. But svelte does make it simpler. So given that it took me only about an hour’s work, I believe Svelte is the way to go and definitely deserves a thumbs up.
In a previous post we added a “Select All” button to the Woocommerce product table. In this tutorial, we will create an asynchronous action that retrieves all of the table product Ids without refreshing the page.
add_action('current_screen', function($screen){
if($screen->id == "edit-product"){
?>
<script>
document.addEventListener("DOMContentLoaded", function() {
jQuery("#posts-filter").on("submit", function(ev){
var action1 = jQuery("[name=action]").val();
if(action1!="my-action") return;
ev.preventDefault();
//this is where we serialize the form
var unindexed_array =jQuery("#posts-filter").serializeArray();
var indexed_array = {};
jQuery.map(unindexed_array, function(n, i){
indexed_array[n['name']] = n['value'];
});
jQuery.ajax({
url: "admin-ajax.php",
type: 'GET',
dataType: 'json', // added data type
data: indexed_array,
success: function(res) {
console.log(res);
},
error: function(res){
console.log(res)
}
});
})
});
</script>
<?php
}
});
You can see that we are listening to the form submit event, and checking the value of the action field (don’t forget there is also the action2 field which you may also want to implement). We then check if the action value matches my-action and if so we serialize the form and submit it with an ajax GET request.
In order for the server to handle this we will add the following action:
add_action("wp_ajax_my-action", function(){
global $wp_query;
add_filter("edit_posts_per_page", function($ppp){
return -1;
});
wp_edit_posts_query();
$posts = $wp_query->posts;
$ret = [];
foreach($posts as $post){
$ret[] = $post->ID;
}
wp_send_json($ret);
});
You can notice two things. Firstly, we use the filter edit_posts_per_page to make sure we get all of the ids. Second we call wp_edit_posts_query() and get the results with $wp_query->posts.
Now that we have all of the Ids, we can do whatever we like (probably more asynchronous actions). But for now, we just log them to the console.
I wanted to share how I created a “Select All” button to a WordPress table. Generally, WordPress doesn’t have a button to select the entire current table. You can usually select only a prefixed number.
Basically, this is what the expected result should look like.
How to set it up?
After some work, I’m gonna walk you through the process. Its not hard to create the PHP side. So let’s focus on the javascript first.
Initially, create some variables:
var allSelected = false;
var itemCount = jQuery(".displaying-num").first().text(); var doAction1Text = jQuery("#doaction").val();
var doAction2Text = jQuery("#doaction2").val();
I simply got the values of the amount of items in the table and the text values of the submit buttons.
Notice that the menu has inline-flex display and that initially the menu itself has display none.
Next, I will detach the original checkbox and attach my menu instead:
var regularSelectAll = jQuery("#cb-select-all-1").detach();
jQuery("#cb").append(selectDropdown);
jQuery("#select-all-dropdown").append(regularSelectAll);
jQuery("#select-all-dropdown").after(selectAllMenu);
In order to get the proper look, you will need the following Cascading Style Sheets(CSS):
#select-all-menu{
margin-left: -10px;
position: absolute;
/* make the menu appear above the background: */
z-index: 100;
}
Finally, add some click event binding. I want that clicking on the dropdown arrow to toggle the appearance of the menu. I also want to click anywhere outside which results in closing the menu:
That’s it! We now have the UI ready. All we need to do now is to create the PHP side. For that, we have inserted the hidden input (Did you notice where we did that?) and now our form will also submit it with the key apply-on-everything . To use it we can just apply the filter edit_posts_per_page and return -1: