The Importance of WP Localize Script
The importance of wp_localize_script is when you can pass data directly from PHP to JavaScript.
Functions is very easy to handle there are only 3 parameters required :
$handle
(string) (Required) Script handle the data will be attached to.
$object_name
(string) (Required) Name for the JavaScript object. Passed directly, so it should be qualified JS variable. Example: ‘/[a-zA-Z0-9_]+/’.
$l10n
(array) (Required) The data itself. The data can be either a single or multi-dimensional array.
Custom Post Type Templates from Plugin Folder?
You can use single_template
filter hook.
function load_movie_template( $template ) { global $post; if ( 'movie' === $post->post_type && locate_template( array( 'single-movie.php' ) ) !== $template ) { /* * This is a 'movie' post * AND a 'single movie template' is not found on * theme or child theme directories, so load it * from our plugin directory. */ return plugin_dir_path( __FILE__ ) . 'single-movie.php'; } return $template; } add_filter( 'single_template', 'load_movie_template' );
How to add a custom field to quick edit
There are a few steps to create the custom quick edit box and custom column
- create a custom meta key (assumed that you have 1 already)
- add custom admin column title and data (assumed that you want to shows the custom meta key in the column, if not, you may also modify a bit of the logic to accomplish the same effect because the principal is the same)
- add custom quick edit box
- add save logic
- load script to modify original inline-edit-post function in order to support custom meta value
- prepare the script file
Introduction to D3.js
This tutorial is meant for D3 v5-v7.
This tutorial is a quick intro to D3.js, a Javascript library for creating interactive data visualizations in the browser. D3 is built on top of common web standards like HTML, CSS, and SVG.
This is not designed to be a deep dive — this tutorial will teach you how to learn D3 and give you a high-level understanding of this powerful tool.
D3 V6 force-directed graph with directional straight arrows
a fork on the classic original because I found the straigth arrows to be more pleasant (especially if using a single color) by changing linkArc() and increasing the arrow length by a little using forceCollide(). I also increased the radius and the text positioning.
D3 Force layout
Broadly speaking there are 4 steps to setting up a force simulation:
- create an array of objects
- call
forceSimulation
, passing in the array of objects - add one or more force functions (e.g.
forceManyBody
,forceCenter
,forceCollide
) to the system - set up a callback function to update the element positions after each tick
Modernizing JavaScript Code in WordPress
I’ve just had a nice experience improving and modernizing a large JavaScript codebase in a WordPress plugin. The original code was written in an old-fashioned way with jQuery in a single large file. Using modern EcmaScript and tools like Webpack, I was able to split it into modules and improve the code structure. The new code is much more readable and maintainable, and of course, fewer bugs. In this tutorial, I’ll show you how I did that.
ES6 Tutorial
ECMAScript 2015 or ES2015 is a significant update to the JavaScript programming language. It is the first major update to the language since ES5 which was standardized in 2009. Therefore, ES2015 is often called ES6.
cola.js. Constraint-Based Layout in the Browser
cola.js (A.K.A. «WebCoLa») is an open-source JavaScript library for arranging your HTML5 documents and diagrams using constraint-based optimization techniques.
It works well with libraries like D3.js, svg.js, and Cytoscape.js. The core layout is based on a complete rewrite in Javascript of the C++ libcola library.
It also has an adaptor for d3.js that allows you to use cola as a drop-in replacement for the D3 force layout. The layout converges to a local optimum unlike the D3 force layout, which forces convergence through a simple annealing strategy. Thus, compared to D3 force layout:
- CoLa achieves higher quality layout;
- is much more stable in interactive applications (no «jitter»);
- it allows user specified constraints such as alignments and grouping;
- it can automatically generate constraints to:
- avoid overlapping nodes; or
- provide flow layout for directed graphs;
- it may be less scalable to very large graphs.
Can I use… WebM video format
WebM video format. Multimedia format designed to provide a royalty-free, high-quality open video compression format for use with HTML5 video. WebM supports the video codec VP8 and VP9.
Global 79.04% + 18.82% = 97.86%
How to check a user watched the full video in html5 video player
Basic check is simple, wait for the ended
event. This is so simple you can just google it.
Now to check that user played full video an extensive analysis would be needed checking if he played every second of it. That’s not necessary however, it should be enough that user:
- played as many seconds as the video is long
- played to the end of the video
This snippet demonstrates exactly that. The video will not be marked as fully played if you just skip to the end. Playing the beginning over and over will also not mark it fully played
WordPress.org Strongly Urges Theme Authors to Switch to Locally Hosted Webfonts
In light of a recent German court case, which fined a website owner for violating the GDPR by using Google-hosted webfonts, WordPress.org’s themes team is updating its recommendations for hosting webfonts. Most theme authors have been enqueuing Google Fonts from the Google CDN for better performance, but this method exposes visitors’ IP addresses.
“The themes team strongly encourages the theme authors to update their themes,” Themes Team representative @benachi said in a recent announcement. “We recommend updating by switching to locally hosted webfonts. Luckily Google Fonts can be downloaded and bundled in a theme. Bundled font files allow users to host webfonts locally and comply with GDPR.”
Hexwords
Why bother with a random green when you can choose to be a #BADA55!
Lorem Picsum. The Lorem Ipsum for photos
Just add your desired image size (width & height) after the service URL, and you’ll get a random image:
https://picsum.photos/200/300
Making Autocomplete Search in WordPress With Code
The autocomplete is generated with help from jQuery UI Autocomplete, a script that is included in WordPress as default.
How to enable HTTP/2 support in Apache
Enable HTTP/2 module
Apache’s HTTP/2 support comes from the mod_http2 module. Enable it from:
a2enmod http2
apachectl restart
If above commands do not work in your system (which is likely the case in CentOS/RHEL), use LoadModule directive in httpd configuration directory to enable http2 module.
Add HTTP/2 Support
We highly recommend you enable HTTPS support for your web site first. Most web browser simply do not support HTTP/2 over plain text. Besides, there are no excuses to not use HTTPS anymore. HTTP/2 can be enabled site-by-site basis. Locate your web site’s Apache virtual host configuration file, and add the following right after the opening
Protocols h2 http/1.1
Is No-Code the Future of Creating Websites?
Pros of No-Code Platforms
- An immediate solution to problems you have in terms of website development because you will be able to create software solutions without having to hire expert programmers.
- Regardless of your degree, career, or position in a business, you can now build a website by yourself that will add value to your craft or business.
- Building a website is faster and cheaper. Hiring developers will cost you a lot of money and with no-code, you will be able to cut the cost.
- It will save you months and months of working since you can now build a website straight away without the need to code.
- You will have creative freedom on what you want to add to your website since the process is more visual.
- Obviously, with no-code, web developers will have less on their plates and can focus more on streamlining processes or creating new innovations.
Cons of No-Code Platforms
- Security breaches with no-code are unavoidable, and once the platform you are using is affected by this factor, your website will be compromised as well.
- You don’t have the full authority with using no-code networks, so basically you are taking a risk in using such platforms.
- You will not be able to customize software using the no-code platform.
- You have to adapt your business process based on the capability feature of the no-code network or platform you are using.
«Corporate Memphis»: ¿Por qué todas las webs parecen iguales?
…decenas de revistas, cuentos, webs y aplicaciones comerciales con una estética similar a la de la ilustración que decora este artículo. A ese estilo se le conoce como «Alegria» o «Corporate Memphis». Es un producto de la precarización y la devaluación del trabajo y tiene decenas de variantes y versiones, todas igualmente exánimes y repetitivas.
El resultado es un cambio cualitativo. Cualquiera puede hacer una ilustración dentro de los códigos visuales del «Corporate Memphis». Ya no es solo que el ilustrador -uno de los últimos artesanos- se haya proletarizado, ni siquiera que una vez proletarizado haya sido expulsado de la oficina y se haya precarizado al extremo vendiendo horas de trabajo en una plataforma. Ahora el ilustrador como tal es ya innecesario.
La automatización combinatoria de un código estándar de imágenes pre-diseñadas permitirá que ilustrar se convierta en una tarea más del desarrollador web. Una entre otras muchas que ya se han automatizado o están en camino de hacerlo. Porque el desarrollador es el primero que ha sufrido la estandarización y procedimentación automatizada de su trabajo. Ahora, Inteligencia Artificial mediante, está siendo alienado incluso de la algoritmia.
Build super fast web scraper with Python x100 than BeautifulSoup
Web scraper is a technique for extracting structured information from a web page. With Python, you can build a efficient web scraper by using BeautifulSoup, requests and other libraries. However, these solution is not fast enough. In this article, I will show you some tips to build a super fast web scraper with Python.
Run a WP-CLI command as a given WordPress user
Use the –user=
PHP setcookie “SameSite=Strict”?
You can use the $options array to set the samesite value, for example:
setcookie($name, $value, [
‘expires’ => time() + 86400,
‘path’ => ‘/’,
‘domain’ => ‘domain.com’,
‘secure’ => true,
‘httponly’ => true,
‘samesite’ => ‘None’,
]);
The value of the samesite element should be either None, Lax or Strict.
Setting Cookies in WordPress
So how do you set cookies in WordPress? With core constants:
COOKIEPATH — Server path in which the cookie will be available on.
COOKIE_DOMAIN — The (sub)domain that the cookie is available to.
Setting cookies in WordPress, especially the expiration is a cinch using one of the core time constants, available since v3.5:
MINUTE_IN_SECONDS = 60 seconds
HOUR_IN_SECONDS = 3,600 seconds
DAY_IN_SECONDS = 86,400 seconds
WEEK_IN_SECONDS = 604,800 seconds
MONTH_IN_SECONDS = 2,629,746 seconds
YEAR_IN_SECONDS = 31,556,952 seconds
Don’t forget to add the current timestamp to one of these constants, for example:
// 5 minutes into the future
$five_minutes = current_time( ‘timestamp’ ) + ( MINUTE_IN_SECONDS * 5 );
How to Create a Custom WordPress Gutenberg Block: Tutorial Series
In the first parts we focus on the basics. We set up a development environment with running compilation of our code. And the basics of how to register a block and the necessary PHP parts of it as well. We’ll learn about the huge library of components and methods available to us from WordPress Gutenberg.
Moving on we’ll learn about how to add sections and settings for our block in the editor sidebar (Inspector) as well as customizing the toolbar. Along the way we’ll touch a lot of different input types and how to use Gutenberg’s component for these. And of course we’ll learn how to save, update and output the saved information to our block – and how that works behind the scenes.
At the end we’ll look at more advanced things like dynamic blocks and how to use PHP to render the block output. And finally how to make post queries inside the editor – allowing the user to select a post from a list for render.
Intercept WordPress API Requests
Say you want to intercept a response from any WordPress API call before it gets returned to the user? For example, you want to block /users/ route or append additional content to a /posts/ response. Simply call the rest_pre_echo_response filter and you can modify all responses!
wp-rest-polylang
Adds value `lang` and `translations` to WP REST api response for each Post and Page request for site running the Polylang Pro plugin.
Adds polylang_translations and keeps lang to WP REST api response for each Post and Page request for site running the Polylang Pro plugin.
Extending Gutenberg With SlotFill and Filters
SlotFill is a modernized take on classic interface “hooks and filters”—a convention for empowering developers to extend the publishing interface outside of the block editor itself—that found its way into WordPress.
Gutenberg : override core blocks rendering
The easiest way to achieve this, is to consider the gallery as a Dynamic block and re-declare its render through PHP:
One thousand and one way to extend Gutenberg today
Extensibility is key, and we can’t build the next generation of the WordPress Editor without making it extensible. What does “making it extensible” mean? Does this mean providing hooks and filters in JavaScript the same way we do in PHP? Does this mean allowing plugins to extend and tweak any UI component used by Gutenberg? Does this mean adding filters to the REST API? Does this mean Giving access to an Editor object to manipulate the editor’s content?
There’s no clear answer to all these questions. Extensibility is a very difficult problem and unless you build it with real use-cases in mind, you’re more likely to get it wrong. (and being stuck with it for a long time).
Paged.js for creating printable documents with HTML and CSS
just came across paged.js, a JavaScript library specifically made to make it easy to use HTML and CSS to make websites that look nice when printed or saved as PDFs, and it looks really interesting.
Pelican Static Site Generator, Powered by Python
Pelican is a static site generator that requires no database or server-side logic.
What does apply_filters(…) actually do in WordPress?
apply_filters($tag, $value) passes the ‘value’ argument to each of the functions ‘hooked’ (using add_filter) into the specified filter ‘tag’. Each function performs some processing on the value and returns a modified value to be passed to the next function in the sequence.
How to Create URL Slug from String in PHP
function slugify($urlString) {
$search = array(‘Ș’, ‘Ț’, ‘ş’, ‘ţ’, ‘Ş’, ‘Ţ’, ‘ș’, ‘ț’, ‘î’, ‘â’, ‘ă’, ‘Î’, ‘ ‘, ‘Ă’, ‘ë’, ‘Ë’);
$replace = array(‘s’, ‘t’, ‘s’, ‘t’, ‘s’, ‘t’, ‘s’, ‘t’, ‘i’, ‘a’, ‘a’, ‘i’, ‘a’, ‘a’, ‘e’, ‘E’);
$str = str_ireplace($search, $replace, strtolower(trim($urlString)));
$str = preg_replace(‘/[^\w\d\-\ ]/’, », $str);
$str = str_replace(‘ ‘, ‘-‘, $str);
return preg_replace(‘/\-{2,}’, ‘-‘, $str);
}
Sending multiple non-blocking cURL requests with PHP.
In this tutorial, I will show you how to send multiple non-blocking / asynchronous cURL requests using PHP. Furthermore, I will also show you how to get the output and HTTP response code for each request.
How to set, change, and recover a MySQL root password
To reset the password for MySQL you first must create a new file with the following contents:
ALTER USER ‘root’@’localhost’ IDENTIFIED BY ‘PASSWORD’;
Where PASSWORD is the new password to be used. Save that file as ~/mysql-pwd.
Next, stop the MySQL daemon with the command:
sudo systemctl stop mysql
With the daemon stopped, issue the command:
sudo mysqld -init-file=~/mysql-pwd
Once your command prompt is returned, restart the MySQL daemon with the command:
sudo systemctl start mysql
You should now be able to log into the MySQL command prompt with the new admin password like so:
mysql -u root -p
When prompted, type the admin password and you’re good to go.
Leveraging System Fonts on the Web
the CSS fonts spec has a couple (new to me) generic font families, like ui-serif and ui-sans-serif, aimed at providing finer-grained controls for specifying OS-level fonts. This allows developers the power to integrate their UIs with the look and feel of the underlying operating system. To suggest Apple user agents render text on screen with the “New York” serif font, developers can specify: font-family: ui-serif.
Open Graph: Take Control of How Social Media Shares Your Web Pages
The namespace conception in HTML is similar to other web languages; it prevents ambiguity on the data structure. It refers to which semantic vocabularies or syntax should be used when the namespace is present in the document. In our case, the og namespace refers to the Open Graph Protocol, while the fb namespace refers to Facebook-own Open Graph specification.
Alternatively, we can use the prefix attribute to define these namespaces.
Twitter Cards and Open Graph
Twitter card tags look similar to Open Graph tags, and are based on the same conventions as the Open Graph protocol. When using Open Graph protocol to describe data on a page, it is easy to generate a Twitter card without duplicating tags and data. When the Twitter card processor looks for tags on a page, it first checks for the Twitter-specific property, and if not present, falls back to the supported Open Graph property. This allows for both to be defined on the page independently, and minimizes the amount of duplicate markup required to describe content and experience.
Note that while Open Graph recommends specifying the “og” RDFa Core 1.1 CURIE prefix mapping via , no such markup is required for Twitter cards and its use of the twitter: prefix in a HTML meta element’s name attribute. Open Graph protocol also specifies the use of property and content attributes for markup () while Twitter cards use name and content. Twitter’s parser will fall back to using property and content, so there is no need to modify existing Open Graph protocol markup if it already exists.
The example below uses a mix of Twitter and Open Graph tags to define a summary card: