WordPress Rest API extensions for going headless WP
I love the WordPress Rest API and switching more and more from theme development to a headless WP approach, with an nice front-end framework. Right now I’m favoring Nuxt.js, which is build on Vue.js (check out wuxt, my very own dockerized nuxt/wp development environment).
For using WPs full strength with the Rest API I’ve collected/build a useful snippet library with WordPress Rest API extensions. I’ll try to maintain the following list as development goes on. All of the following extensions can be embedded in the functions.php
file. If you wondering about the wuxt_ prefix, I’ve got the code from my Wuxt project and the prefix is as good as anyone.
How to detect the user browser ( Safari, Chrome, IE, Firefox and Opera ) using JavaScript ?
Detecting the Safari browser: The user-agent of the Safari browser is “Safari”. This value is passed to indexOf() method to detect this value in the user-agent string. One additional check is required in the case of the Safari browser as the user-agent of the Chrome browser also includes the Safari browser’s user-agent. If both the user-agents of Chrome and Safari are in the user-agent, it means that the browser is Chrome, and hence the Safari browser value is discarded.
Browser detection using the user agent
When considering using the user agent string to detect which browser is being used, your first step is to try to avoid it if possible. Start by trying to identify why you want to do it.
interact.js: JavaScript drag and drop, resizing, and multi-touch gestures for modern browsers
interact.js takes a slightly different approach compared to most drag and drop libraries. To give you as much control as possible, it tries to provide a simple, flexible API that gives you all the pointer event data you’ll need to move elements around.
The library doesn’t even do any moving at all! This is great because you decide exactly what feedback your users get. You can drag elements, draw on a canvas or (if you really need to) scroll the page.
Resizable & Draggable Dialog In Pure JavaScript
A vanilla JavaScript library to create a draggable & resizable dialog popup without any frameworks or libraries (e.g. jQuery UI).
To move, drag from the title bar of the dialog box.
To resize, drag from any edge or any corner of the dialog box.
Comparing Various Ways to Hide Things in CSS
Developers most commonly use display: none
to hide the content on the page. Unfortunately, this way of hiding content isn’t bulletproof because now that content is now “inaccessible” to screen readers. It’s tempting to use it, but especially in cases where something is only meant to be visually hidden, don’t reach for it.
Traducción con Pods de WordPress y WPML
en el caso de que se estén empleando plugins para el desarrollo de una solución WordPress que no sean compatibles con WPML, por ejemplo PODS, una solución interesante, es duplicar el mismo post o tipo de contenido, que ha sido creado con elementos del plugin incompatible y aprovechar cada versión para cada uno de los idiomas que hemos configurado para nuestro sitio, diferenciando cada post con una nomenclatura, por ejemplo con el diminutivo (_en, _es, _fr) del idioma en el slug o (-EN, -ES, -FR) en el nombre del mismo.
Para que luego WordPress distnga cual de esos bloques o contenidos pertenece al idioma concreto, utilizamos la constante ICL_LANGUAGE_CODE, definida por WPML, que se pueden emplear como parte del nuestro tema, para poder invocar el contenido de un post u otro en dependencia del idioma actual con el que se está navegando en nuestro sitio, idioma almacenado en la constante antes mencionada.
De esta manera un ejemplo podría ser:
if (ICL_LANGUAGE_CODE == 'en')
3D TagCloud.js rotating with mouse
const TagCloud = require('TagCloud'); const container = '.tagcloud'; const texts = [ '3D', 'TagCloud', 'JavaScript', 'CSS3', 'Animation', 'Interactive', 'Mouse', 'Rolling', 'Sphere', '6KB', 'v2.x', ]; const options = {}; TagCloud(container, texts, options);
Response: json() method
The json()
method of the Response
interface takes a Response
stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON
.
const myList = document.querySelector("ul"); const myRequest = new Request("products.json"); fetch(myRequest) .then((response) => response.json()) .then((data) => { for (const product of data.products) { const listItem = document.createElement("li"); listItem.appendChild(document.createElement("strong")).textContent = product.Name; listItem.append(` can be found in ${product.Location}. Cost: `); listItem.appendChild(document.createElement("strong")).textContent = `£${product.Price}`; myList.appendChild(listItem); } }) .catch(console.error);
EventTarget: addEventListener() method
The Function.prototype.bind()
method lets you establish a fixed this
context for all subsequent calls — bypassing problems where it’s unclear what this
will be, depending on the context from which your function was called. Note, however, that you’ll need to keep a reference to the listener around so you can remove it later.
class Something { name = "Something Good"; constructor(element) { // bind causes a fixed `this` context to be assigned to `onclick2` this.onclick2 = this.onclick2.bind(this); element.addEventListener("click", this.onclick1, false); element.addEventListener("click", this.onclick2, false); // Trick } onclick1(event) { console.log(this.name); // undefined, as `this` is the element } onclick2(event) { console.log(this.name); // 'Something Good', as `this` is bound to the Something instance } } const s = new Something(document.body);
Medusa: Building blocks for digital commerce
Thousands of developers use Medusa’s open-source commerce modules and tools to build rich, reliable, and performant commerce applications without reinventing core commerce logic.
We build modularized commerce logic like carts, products, and order management and provide tools to orchestrate them for powerful ecommerce websites, POS applications, commerce-enabled products, and everything in between.
Our modules are incredibly portable and can run in modern JavaScript environments, unlocking new infrastructure for unparalleled scalability and performance, while bringing commerce enablement to new layers of your stack.
Avoid invisible text during font loading
font-display
is an API for specifying font display strategy. swap
tells the browser that text using this font should be displayed immediately using a system font. Once the custom font is ready, the system font is swapped out.
Reduce web font size
Web font optimization is a critical piece of the overall performance strategy. Each font is an additional resource, and some fonts may block rendering of the text, but just because the page is using WebFonts doesn’t mean that it has to render slower. On the contrary, optimized fonts, combined with a judicious strategy for how they are loaded and applied on the page, can help reduce the total page size and improve page rendering times.
The Shapes of CSS
CSS is capable of making all sorts of shapes. Squares and rectangles are easy, as they are the natural shapes of the web. Add a width
and height
and you have the exact size rectangle you need. Add border-radius
and you can round that shape, and enough of it you can turn those rectangles into circles and ovals.
Evaluating Web Accessibility Overview
When developing or redesigning a website or web application, evaluate accessibility early and throughout the development process to identify accessibility problems early, when it is easier to address them.
There are evaluation tools that help with evaluation. However, no tool alone can determine if a site meets accessibility standards. Knowledgeable human evaluation is required to determine if a site is accessible.
WordPress: how to add a default title to your posts
This came up on the Fediverse: @kev@log.kevquirk.com wanted to automatically add titles to the posts on his microblog.
This automation would have to be compatible with all the editors, including the mobile app.
I think may be a fairly common request when one uses their WordPress site as microblogging platform. When you share quick updates with your friends, be it a picture, a video, a sentence or two, you don’t really want to have to think of a title for that update. The editor should enable you to share, not get in the way.
aria-label use
The aria-label should be used to provide a text alternative to an element that has no visible text on the screen.
aria-label
is an attribute defined in the WAI-ARIA(opens in a new tab) specification. This specification extends native HTML, allowing you to change the way an HTML element is «translated» into the accessibility tree.
A Complete Guide to Flexbox
This complete guide explains everything about flexbox, focusing on all the different possible properties for the parent element (the flex container) and the child elements (the flex items).
Variable fonts guide
Variable fonts are an evolution of the OpenType font specification that enables many different variations of a typeface to be incorporated into a single file, rather than having a separate font file for every width, weight, or style.
The heart of the new variable fonts format is the concept of an axis of variation describing the allowable range of that particular aspect of the typeface design. So the ‘weight axis’ describes how light or how bold the letterforms can be; the ‘width axis’ describes how narrow or how wide they can be; the ‘italic axis’ describes if italic letterforms are present and can be turned on or off accordingly, etc. Note that an axis can be a range or a binary choice. Weight might range from 1–999, whereas italic might be 0 or 1 (off or on).
Set array pointer to a specific key or value in PHP
What PHP lacks is the ability to set the array pointer to an arbitrary key or value. There are ways to move forward and backward in the array but not a dedicated function to set the internal pointer to a specific key. Fortunately we can make it work, but it’s pretty archiac. We’ll need to loop through the array and look for what we want.
pods_api_post_save_pod_item or save_post not working on frontend
////// // This is a logging function for any debugging task // NOTES: Youy must have the following lines in the wp-config.php file in the root folder, which // puts a debug.log text file under the wp-content folder under root // // // define( 'WP_DEBUG', true ); // define( 'WP_DEBUG_DISPLAY', false ); // define( 'WP_DEBUG_LOG', true ); // // NOTES: install Error Log Viewer Plugin by bestwebsoft to view log from admin menu // for error logging if (!function_exists('write_log')) { function write_log ( $log ) { if ( true === WP_DEBUG ) { if ( is_array( $log ) || is_object( $log )) { error_log( print_r( $log, true )); } else { error_log( $log ); } } } } // //////
Python | Introduction to Web development using Flask
Flask is an API of Python that allows us to build up web-applications. It was developed by Armin Ronacher. Flask’s framework is more explicit than Django’s framework and is also easier to learn because it has less base code to implement a simple web-Application. A Web-Application Framework or Web Framework is the collection of modules and libraries that helps the developer to write applications without writing the low-level codes such as protocols, thread management, etc. Flask is based on WSGI(Web Server Gateway Interface) toolkit and Jinja2 template engine.
Navigating the New Era of AI-Assisted Code Generation in WordPress
WordPress plugin developers are adopting AI-powered tech and building it into their products, such as RankMath’s AI-generated suggestions for creating SEO-friendly content, WordPress.com’s experimental blocks for AI-generated images and content, and a Setary’s plugin that uses AI to write and bulk edit WooCommerce product descriptions. The wpfrontpage site is tracking these plugins but WordPress.org also lists dozens of plugins with AI, many of them created to write content or generate images.
Flask – (Creating first simple application)
To understand what Flask is you have to understand a few general terms.
WSGI Web Server Gateway Interface (WSGI) has been adopted as a standard for Python web application development. WSGI is a specification for a universal interface between the web server and the web applications.
Werkzeug It is a WSGI toolkit, which implements requests, response objects, and other utility functions. This enables building a web framework on top of it. The Flask framework uses Werkzeug as one of its bases.
jinja2 jinja2 is a popular templating engine for Python. A web templating system combines a template with a certain data source to render dynamic web pages.
Flask is a web application framework written in Python. Flask is based on the Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects.
How To Create Horizontal Scrolling Containers
The Flexbox Method
.scrolling-wrapper-flexbox {
display: flex;
flex-wrap: nowrap;
overflow-x: auto;
.card {
flex: 0 0 auto;
}
}
How To Build A ChatGPT Chatbot For Your Website In Minutes
Although the plugin is free, getting access to OpenAI’s server is not. It’s very reasonably priced – most basic questions and answers will cost a fraction of a cent – but if you’ve got a heavily trafficked site or visitors making excessive use of the chatbot, costs can quickly ramp up.
How to Highlight the Search Terms in Results in WordPress
In an attempt to make your WordPress search even more user friendly, you can highlight the search terms in the results. We did this for one of our clients, so we thought it would be useful for other users. In this article we will show you how you can highlight search terms in the results in WordPress.
Converting my OTF font into multiple web fonts with this bash script
I came across this use-case where we had to use a specific custom font but it was only available in .otf
. However, we want to support multiple formats to ensure even deprecated browsers can load the font. Otf has a global coverage of 97.89% but we didn’t want to take any chances of the font not loading as it’s a crucial feature in our app.
I wanted to convert the font to support the following browsers:
- woff2 – Latest browsers
- woff – Modern browsers
- ttf – Apple and mobile OS
svg– older safari and ios support- eot – older IE support
GraphQL. A query language for your API
GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.
Headless content management system
A headless Content Management System, or headless CMS, is a back end-only web content management system that acts primarily as a content repository. A headless CMS makes content accessible via an API for display on any device, without a built-in front end or presentation layer. The term ‘headless’ comes from the concept of chopping the ‘head’ (the front end) off the ‘body’ (the back end).
how to disable download video option
Just add controlsList="nodownload"
in your video tag.