Connect with us

WORDPRESS

Making 43% of the Web More Dynamic with the WordPress Interactivity API – WordPress.com News

Published

on

Making 43% of the Web More Dynamic with the WordPress Interactivity API – WordPress.com News

Creating rich, engaging, and interactive website experiences is a simple way to surprise, delight, and attract attention from website readers and users. Dynamic interactivity like instant search, form handling, and client-side “app-like” navigation where elements can persist across routes, all without a full page reload, can make the web a more efficient and interesting place for all.

But creating those experiences on WordPress hasn’t always been the easiest or most straightforward, often requiring complex JavaScript framework setup and maintenance. 

Now, with the Interactivity API, WordPress developers have a standardized way for doing that, all built directly into core. 

The Interactivity API started as an experimental plugin in early 2022, became an official proposal in March 2023, and was finally merged into WordPress core with the release of WordPress 6.5 on April 2, 2024. It provides an easier, standardized way for WordPress developers to create rich, interactive user experiences with their blocks on the front-end.

ELI5: The Interactivity API and the Image Block

Several core WordPress blocks, including the Query Loop, Image, and Search blocks, have already adopted the Interactivity API. The Image block, in particular, is a great way to show off the Interactivity API in action. 

At its core, the Image blocks allow you to add an image to a post or page. When a user clicks on an image in a post or page, the Interactivity API launches a lightbox showing a high-resolution version of the image.

The rendering of the Image block is handled server-side. The client-side interactivity, handling resizing and opening the lightbox, is now done with the new API that comes bundled with WordPress. You can bind the client-side interactivity simply by adding the wp-on--click directive to the image element, referencing the showLightbox action in view.js.

You might say, “But I could easily do this with some JavaScript!” With the Interactivity API, the code is compact and declarative, and you get the context (local state) to handle the lightbox, resizing, side effects, and all of the other needed work here in the store object.

actions: {
			showLightbox() {
				const ctx = getContext();

				// Bails out if the image has not loaded yet.
				if ( ! ctx.imageRef?.complete ) {
					return;
				}

				// Stores the positons of the scroll to fix it until the overlay is
				// closed.
				state.scrollTopReset = document.documentElement.scrollTop;
				state.scrollLeftReset = document.documentElement.scrollLeft;

				// Moves the information of the expaned image to the state.
				ctx.currentSrc = ctx.imageRef.currentSrc;
				imageRef = ctx.imageRef;
				buttonRef = ctx.buttonRef;
				state.currentImage = ctx;
				state.overlayEnabled = true;

				// Computes the styles of the overlay for the animation.
				callbacks.setOverlayStyles();
			},
...

The lower-level implementation details, like keeping the server and client side in sync, just work; developers no longer need to account for them.

This functionality is possible using vanilla JavaScript, by selecting the element via a query selector, reading data attributes, and manipulating the DOM. But it’s far less elegant, and up until now, there hasn’t been a standardized way in WordPress of handling interactive events like these.

With the Interactivity API, developers have a predictable way to provide interactivity to users on the front-end. You don’t have to worry about lower-level code for adding interactivity; it’s there in WordPress for you to start using today. Batteries are included.

How is the Interactivity API different from Alpine, React, or Vue?

Prior to merging the Interactivity API into WordPress core, developers would typically reach for a JavaScript framework to add dynamic features to the user-facing parts of their websites. This approach worked just fine, so why was there a need to standardize it?

At its core, the Interactivity API is a lightweight JavaScript library that standardizes the way developers can build interactive HTML elements on WordPress sites.

Mario Santos, a developer on the WordPress core team, wrote in the Interactivity API proposal that, “With a standard, WordPress can absorb the maximum amount of complexity from the developer because it will handle most of what’s needed to create an interactive block.”

The team saw that the gap between what’s possible and what’s practical grew as sites became more complex. The more complex a user experience developers wanted to build, the more blocks needed to interact with each other, and the more difficult it became to build and maintain sites. Developers would spend a lot of time making sure that the client-side and server-side code played nicely together.

For a large open-source project with several contributors, having an agreed-upon standard and native way of providing client-side interactivity speeds up development and greatly improves the developer experience.

Five goals shaped the core development team’s decisions as they built the API: 

  1. Block-first and PHP-first: Prioritizing blocks for building sites and server side rendering for better SEO and performance. Combining the best for user and developer experience.
  2. Backward-compatible: Ensuring compatibility with both classic and block themes and optionally with other JavaScript frameworks, though it’s advised to use the API as the primary method. It also works with hooks and internationalization.
  3. Declarative and reactive: Using declarative code to define interactions, listening for changes in data, and updating only relevant parts of the DOM accordingly.
  4. Performant: Optimizing runtime performance to deliver a fast and lightweight user experience.
  5. Send less JavaScript: Reduce the overall amount of JavaScript being sent on the page by providing a common framework that blocks can reuse.  So the more that blocks leverage the Interactivity API, the less JavaScript will be sent overall.

Other goals are on the horizon, including improvements to client-side navigation, as you can see in this PR.

Interactivity API vs. Alpine

The Interactivity API shares a few similarities to Alpine—a lightweight JavaScript library that allows developers to build interactions into their web projects, often used in WordPress and Laravel projects.

Similar to Alpine, the Interactivity API uses directives directly in HTML and both play nicely with PHP. Unlike Alpine, the Interactivity API is designed to seamlessly integrate with WordPress and support server-side rendering of its directives.

With the interactivity API, you can easily generate the view from the server in PHP, and then add client-side interactivity. This results in less duplication, and its support in WordPress core will lead to less architectural decisions currently required by developers. 

So while Alpine and the Interactivity API share a broadly similar goal—making it easy for web developers to add interactive elements to a webpage—the Interactivity API is even more plug-and-play for WordPress developers.

Interactivity API vs. React and Vue

Many developers have opted for React when adding interactivity to WordPress sites because, in the modern web development stack, React is the go-to solution for declaratively handling DOM interactivity. This is familiar territory, and we’re used to using React and JSX when adding custom blocks for Gutenberg.

Loading React on the client side can be done, but it leaves you with many decisions: “How should I handle routing? How do I work with the context between PHP and React? What about server-side rendering?”

Part of the goal in developing the Interactivity API was the need to write as little as little JavaScript as possible, leaving the heavy lifting to PHP, and only shipping JavaScript when necessary.

The core team also saw issues with how these frameworks worked in conjunction with WordPress. Developers can use JavaScript frameworks like React and Vue to render a block on the front-end that they server-rendered in PHP, for example, but this requires logic duplication and risks exposure to issues with WordPress hooks.

For these reasons, among others, the core team preferred Preact—a smaller UI framework that requires less JavaScript to download and execute without sacrificing performance. Think of it like React with fewer calories.

Luis Herranz, a WordPress Core contributor from Automattic, outlines more details on Alpine vs the Interactivity API’s usage of Preact with a thin layer of directives on top of it in this comment on the original proposal.

Preact only loads if the page source contains an interactive block, meaning it is not loaded until it’s needed, aligning with the idea of shipping as little JavaScript as possible (and shipping no JavaScript as a default).

In the original Interactivity API proposal, you can see the run-down and comparison of several frameworks and why Preact was chosen over the others.

What does the new Interactivity API provide to WordPress developers?

In addition to providing a standardized way to render interactive elements client-side, the Interactivity API also provides developers with directives and a more straightforward way of creating a store object to handle state, side effects, and actions.

Graphic from Proposal: The Interactivity API – A better developer experience in building interactive blocks on WordPress.org

Directives

Directives, a special set of data attributes, allow you to extend HTML markup. You can share data between the server-side-rendered blocks and the client-side, bind values, add click events, and much more. The Interactivity API reference lists all the available directives.

These directives are typically added in the block’s render.php file, and they support all of the WordPress APIs, including actions, filters, and core translation APIs. 

Here’s the render file of a sample block. Notice the click event (data-wp-on--click="actions.toggle"), and how we bind the value of the aria-expanded attributes via directives.

<div
	<?php echo get_block_wrapper_attributes(); ?>
	data-wp-interactive="create-block"
	<?php echo wp_interactivity_data_wp_context( array( 'isOpen' => false ) ); ?>
	data-wp-watch="callbacks.logIsOpen"
>
	<button
		data-wp-on--click="actions.toggle"
		data-wp-bind--aria-expanded="context.isOpen"
		aria-controls="<?php echo esc_attr( $unique_id ); ?>"
	>
		<?php esc_html_e( 'Toggle', 'my-interactive-block' ); ?>
	</button>

	<p
		id="<?php echo esc_attr( $unique_id ); ?>"
		data-wp-bind--hidden="!context.isOpen"
	>
		<?php
			esc_html_e( 'My Interactive Block - hello from an interactive block!', 'my-interactive-block' );
		?>
	</p>
</div>

Do you need to dynamically update an element’s inner text? The Interactivity API allows you to use data-wp-text on an element, just like you can use v-text in Vue.

You can bind a value to a boolean or string using wp-bind– or hook up a click event by using data-wp-on–click on the element. This means you can write PHP and HTML and sprinkle in directives to add interactivity in a declarative way.

Handling state, side effects, and actions

The second stage of adding interactivity is to create a store, which is usually done in your view.js file. In the store, you’ll have access to the same context as in your render.php file.

In the store object, you define actions responding to user interactions. These actions can update the local context or global state, which then re-renders and updates the connected HTML element. You can also define side effects/callbacks, which are similar to actions, but they respond to state changes instead of direct user actions.

import { store, getContext } from '@wordpress/interactivity';

store( 'create-block', {
	actions: {
		toggle: () => {
			const context = getContext();
			context.isOpen = ! context.isOpen;
		},
	},
	callbacks: {
		logIsOpen: () => {
			const { isOpen } = getContext();
			// Log the value of `isOpen` each time it changes.
			console.log( `Is open: ${ isOpen }` );
		},
	},
} );

Try it out for yourself

The Interactivity API is production-ready and already running on WordPress.com! With any WordPress.com plan, you’ll have access to the core blocks built on top of the Interactivity API. 

If you want to build your own interactive blocks, you can scaffold an interactive block by running the below code in your terminal:

npx @wordpress/create-block@latest my-interactive-block --template @wordpress/create-block-interactive-template 

This will give you an example interactive block, with directives and state handling set up. 

You can then play around with this locally, using wp-env, using a staging site, or by uploading the plugin directly to your site running a plugin-eligible WordPress.com plan

If you want a seamless experience between your local dev setup and your WordPress.com site, try using it with our new GitHub Deployments feature! Developing custom blocks is the perfect use case for this new tool.

The best way to learn something new is to start building. To kick things off, you may find the following resources a good starting point:


Join 106.9M other subscribers

Source link

Keep an eye on what we are doing
Be the first to get latest updates and exclusive content straight to your email inbox.
We promise not to spam you. You can unsubscribe at any time.
Invalid email address

WORDPRESS

14 Print-on-Demand Tips You Can’t Afford to Ignore | Printful

Published

on

By

If you’re looking for print-on-demand tips, you’re either just starting out or want to improve your existing store. Regardless of which you are, …

Source link

Keep an eye on what we are doing
Be the first to get latest updates and exclusive content straight to your email inbox.
We promise not to spam you. You can unsubscribe at any time.
Invalid email address
Continue Reading

WORDPRESS

Visual Composer review 2024: A free website builder dedicated to WordPress

Published

on

By

In our detailed Visual Composer review we explore this top website builder tailored specifically for WordPress users. Visual Composer stands out as a versatile and powerful plugin that lets businesses and creative individuals build stunning and highly functional websites without any coding knowledge. As a WordPress plugin, it seamlessly integrates with the platform, offering a simple drag-and-drop interface for building and customizing web pages.

Our expertise in site building and WordPress plugins allows us to provide trustworthy advice on Visual Composer’s capabilities and features. With years of experience in evaluating website builders and design tools, our insights aim to guide readers like yourself in making smart decisions about their online presence.

Source link

Keep an eye on what we are doing
Be the first to get latest updates and exclusive content straight to your email inbox.
We promise not to spam you. You can unsubscribe at any time.
Invalid email address
Continue Reading

WORDPRESS

WordPress Filter Tags Explained – Crocoblock

Published

on

By

WordPress Filter Tags Explained - Crocoblock

Is it possible to organize content on a WordPress site or blog so that it is quickly found by users and better indexed by search engines?

Of course! Use WordPress tag filters.

Tags are an underrated WordPress tool because more and more website owners and developers are using categories to organize content. But there are other ways, and tags can also help users find what they’re looking for, especially if you have a lot of content.

In this article, we will discuss tags, how they can help you, how to add them to your WordPress site, and how to use them for filtering content.

Table of Contents

Tags are an essential feature of WordPress, similar to keywords. You can combine different publications using a specific parameter, topic, or word and assign them a tag. When the user clicks on this tag, they will be taken to the section where different materials are collected, and materials that have this tag are displayed.

For example, if a WooCommerce website is dedicated to furniture, clicking on the “leather sofa” tag will allow the user to use the WooCommerce tag filter and see a page where leather sofas are collected.

This feature improves the user experience and helps search engines better understand your site’s content and relevance to potential visitors.

Both categories and tags serve the purpose of organizing content on a WordPress site. They represent two types of WordPress taxonomy: hierarchical and non-hierarchical. 

A category is a hierarchical type of taxonomy, and a tag is non-hierarchical. 

This means that while you can have parent and child categories, you can’t have parent and child tags. 

Both categories and tags are used to classify and organize content on a WordPress site, but they serve slightly different purposes. Categories are often used for broad topics or themes because you can create a broader category, e.g., “Continents,” then add a “Countries” child category there, and then create the “Cities” child category. Just like folders on your computer. 

Tags, in turn, are usually used for more specific or granular topics when nesting is not needed, or, vice versa, for very broad ones, which don’t need more specifying. For example, you have a blog with articles, videos, and podcasts about visual art. Also, you have different categories organized by movements, styles, etc. But you also want to filter posts by content types. So, you can add “Videos,” “Articles,” and “Podcasts” tags. Thus, users can select both topics and content types. Default WordPress posts have to belong to a certain category (by default, “Uncategorized”). But if you create a custom post type (CPT), it’s up to you whether to create taxonomies for them or not. If you want to add CPTs or taxonomies for them, JetEngine is one of the most advanced solutions on the market for not only creating but also managing them.

JetEngine has way more features.
Explore them all.

Buy plugin

To add tags to your publication, create a new post/page/custom post, or click “Edit” on the existing one, and then in the right sidebar, add the desired tag:

adding tag to new post

You can add multiple tags at once by separating them with commas.

Check the tags before publishing your finished post to ensure everything is correct. If you don’t understand what tag to use yet, WordPress allows you to choose from the most popular ones.

NOTE

Choose only tags that directly relate to the publication and will help your readers navigate your site.

How to Filter Content Using Tags?

Filtering content by tags is fairly easy. One can use tag filters in the following ways: adding them to a menu, using a dedicated filter plugin, or writing custom code.

Tag menu

If you want to add tags to the menus, go to Appearance > Menus > Screen Options and check the box next to tags. Now, you can add tags to the menu. 

If you use tags a lot, making a separate menu containing them is a good idea and the simplest way to create a filter by tags. It can be displayed on a sidebar on one of the pages.

adding tags to the menuadding tags to the menu

Using a filter plugin

If you want a more advanced approach to content organization and want your site to have not only tags but also filters, use additional plugins, such as JetSmartFilters.

JetSmartFilters plugin homepageJetSmartFilters plugin homepage

The JetSmartFilters plugin allows you to create convenient filters on your page and filter your site content by various parameters. 

The plugin has an Active Tags feature, which allows you to display active tags and, accordingly, see the content based on these tags. For example, users choose “humor” and “paper” tags and see books with such parameters. In the Active tags field, they can see these tags. 

In this article, you will find detailed instructions on how to set up and activate this feature.

In addition, JetSmartFilters can help you add some other functionality related to tag filters. For instance: 

  1. Remove applied filters. If you need a button that helps you remove all applied filters at once, add it with the Remove Filters feature. You can place it just in the right place, and when clicked, users can remove all the filters they have applied earlier. Here are detailed instructions
  2. Active filters. If you want to show all active filters on the page, you can use the Active Filters widget. It showcases all currently applied filters and allows users to remove those that are not relevant one by one. Here are detailed instructions on how to use this feature.

Custom code

Last but not least, you can create tag filters by writing custom code. In this article, you can find a simple example of such a code. 

FAQ

How do I add tags to my site?

You can use WordPress’s built-in feature to add tags before publishing a post or employ additional plugins. Plugins usually have more functionality for organizing content on the site.

What is tag filtering?

Tag filtering allows users to filter content by specific keywords and view only the pages and posts they want. A Tag filter in WordPress filters posts containing specific tags from your dashboard and search results.

How do I set tags?

Look at your new content’s topic and add related keywords. Choose words that will be relevant to your topic to help your users find the information they’re looking for faster. There must be frequently used words for your topic.

In Conclusion

Tags are a helpful option for quickly categorizing and organizing your content. They help users navigate within their areas of interest and help site owners deliver information correctly.

Tags are a built-in feature of WordPress that can be used without additional skills or plugins.

Of course, tags won’t replace filters or categories, but they help improve the user experience, so using them on blogs and other content-rich website types is a good idea.

Source link

Keep an eye on what we are doing
Be the first to get latest updates and exclusive content straight to your email inbox.
We promise not to spam you. You can unsubscribe at any time.
Invalid email address
Continue Reading

Trending