Tag: Useful

Logical Properties for Useful Shorthands

Michelle Barker with my favorite sorta blog post: short, practical, and leaves you with a valuable nugget for your time. Here, she gets into logical property shorthands in CSS, particularly those that set lengths just on a single axis, say only the block (vertical) axis or just the inline (horizontal) axis.

I say “block” and ”inline” because, as far as logical properties are concerned, the x-axis could just as well behave like a vertical axis depending on the current writing-mode.

So, where we’ve always had padding, margin, and border shorthands that can support a multi-value syntax, none of them allow us to declare lengths on a specific axis without also setting a length on the other axis.

For example:

/* This gives us margin on the inline axis */ margin: 0 3rem;

…but we had to set the other axis in order to get there. With logical properties, however, we have additional shorthands for each axis meaning we can cue up the margin-inline shorthand to work specifically on the inline axis:

margin-inline: 3rem;

Michelle mentions my favorite logical property shorthand in passing. How many times do you position something to this sort of tune:

.position-me {   position: absolute;   top: 0;   right: 0;   bottom: 0;   left: 0; }

We can get those four lines into in with inset: 0. Or we could target the block and inline axis directly with inset-block and inset-inline, respectively.

While we’re talking shorthands, I always like to put a word of caution about ”accidental” CSS resets. Just one of the common CSS mistakes I make.

To Shared LinkPermalink on CSS-Tricks

Logical Properties for Useful Shorthands originally published on CSS-Tricks. You should get the newsletter.


, , ,

Useful Tools for Visualizing Databases on a Budget

A diagram is a graphical representation of information that depicts the structure, relationship, or operation of anything. Diagrams enable your audience to visually grasp hidden information and engage with them in ways that words alone cannot. Depending on the type of project, there are numerous ways to use diagrams. For example, if you want to depict the relationship between distinct pieces, we usually use an Entity Relationship Diagram (ERD). There are many great tools that can help you sketch out your database designs beautifully.

In this article, I will be sharing some of my favorite tools that I use to curate my data structures and bring my ideas to life.

Google Docs Drawing

The drawing function in Google Docs allows you to add illustrations to your pages. You can add custom shapes, charts, graphs, infographics, and text boxes to your document with the built-in drawing tool.

Screenshot of database entity relationships using Google Docs.

Sketching with Google Docs

Although it is simple to add a graphic to your Google Docs, the procedure is not totally visible. Here’s how:

1 . Open a new document on Google Docs.

Screenshot of a new document in Google Docs.

2 . Click on the insert button and select Drawing . Then, from the drop-down option, choose New to open the drawing screen.

Screenshot of adding a new Drawing in Google Docs.

3 . You can use the toolbox on this screen to add text boxes, select lines, and shapes, and modify the colors of your drawing.

Screenshot of selecting an Arrow in Google Docs.

4 . You may also use the cursor to adjust the size of your drawings and the color of your designs by using the toolbox at the top of your screen.

Screenshot of customizing a drawing in Google Docs.

5 . When finished, click the Save and close button. You can click on the “File” toolbar displayed on the top of your screen to download your document.


Cost Free.
CLI? GUI? Online? Online.
Requires an Account? Yes, a Google account is required.
Collaborative Editing? Yes, with Google Drive sharing.
Import SQL Not Applicable.
Export SQL Not Applicable.
Export Formats .doc, .pdf, .rtf, .odt, .txt, .html, .epub
Generate Shareable URL Yes.

Google Docs offers amazing convenience. However, diagramming databases is not something it was intended for. You may find yourself frustrated with redrawing arrows and relationships if you are making frequent edits to your model.


Graphviz is a free graph visualization software that allows us to express information diagrammatically.

Screenshot of database entity relationships using Graphviz.

Graphviz implements the DOT language. The DOT language is an abstract grammar that makes use of terminals, non terminals, parentheses, square brackets, and vertical bars. More information about the DOT language can be found in its documentation.


Cost Free.
CLI? GUI? Online? CLI.
Visual Studio Code, Eclipse, and Notepad++.
Graphical Interfaces.
Requires an Account? No.
Collaborative Editing? Not Applicable.
Import SQL Yes, using SQL Graphviz.
Export SQL Yes, using SQL Graphviz.
Export Formats .gif, .png, .jpeg, .json, .pdf and more
Generate Shareable URL Not Applicable.

Graphviz has an impressive and supportive community. However, a high level of SQL support is only available when you install additional third-party software. This overhead may make it less approachable to users that are not comfortable setting up their computer to support these tools.


ERDPlus is a database modeling tool that allows you to create Entity Relationship Diagrams, Relational Schemas, Star Schemas, and SQL DDL statements.

Screenshot of database entity relationships using ERDPlus.

It includes a brief guide on how to create your ER diagrams, which is especially useful for beginners. You can also easily convert your created ER diagrams to relation schemas.


Cost Free.
CLI? GUI? Online? Online.
Requires an Account? Not required, but recommended for saving.
Collaborative Editing? Not Applicable.
Import SQL No.
Export SQL Yes, with the support of SQL DDL statements.
Export Formats .png
Generate Shareable URL Not Applicable.

ERDPlus is suited for SQL. It does lack additional export formats and ability to share with teams, but these features are not necessary with import and export.


Diagrams.net (previously Draw.io) is a free online diagramming tool that can be used to create flowcharts, UML diagrams, database models, and other types of diagrams.

Screenshot of database entity relationships using Diagrams.net.


Cost Free.
CLI? GUI? Online? Desktop and Online.
Requires an Account? Not required, but recommended for saving.
Collaborative Editing? Sharing requires Google Drive or OneDrive.
Import SQL Yes.
Export SQL No.
Export Formats .png, .jpeg, .svg, .pdf, .html and more.
Generate Shareable URL Yes, export as URL an option.

Diagrams.net is designed to support many different workflows. Its ability to easily integrate with third-party integrations such as Trello, Quip, Notion, and others distinguishes it from the other options. The ability to share and collaborate may make it work well for collaborative teams.


This article is based on using free database tools that could help visualize your ideas and their capabilities with limitations to great details on how to use these tools.

In my research, I also came across other excellent tools with free trials available for creating database diagrams like Lucidchart, EDrawMax, and, DrawSQL. However, these free trials have limitations which may make them less suited for developers working on multiple projects.

I strongly recommend that you read the documentation for each of these tools to determine what works best for you and, most importantly, to avoid any difficulties in using these tools.

Thank you for taking the time to read this far, and I hope you found what you were looking for. Have a wonderful day!

Useful Tools for Visualizing Databases on a Budget originally published on CSS-Tricks. You should get the newsletter.


, , , ,

Useful Tools for Creating AVIF Images

AVIF (AV1 Image File Format) is a modern image file format specification for storing images that offer a much more significant file reduction when compared to other formats like JPG, JPEG, PNG, and WebP. Version 1.0.0 of the AVIF specification was finalized in February 2019 and released by Alliance for Open Media to the public.

In this article, you will learn about some browser-based tools and command line tools for creating AVIF images.

Why use AVIF over JPGs, PNGS, WebP, and GIF?

  • Lossless compression and lossy compression
  • JPEG suffers from awful banding
  • WebP is much better, but there’s still noticeable blockiness compared to the AVIF
  • Multiple color space
  • 8, 10, 12-bit color depth


Jake Archibald, wrote an article a few years back on this new image format and also helped us to identify some disadvantages to compressing images, normally you should look out for these two when compressing to AVIF:

  1. If a user looks at the image in the context of the page, and it strikes them as ugly due to compression, then that level of compression is not acceptable. But, one tiny notch above that boundary is fine.
  2. It’s okay for the image to lose noticeable detail compared to the original unless that detail is significant to the context of the image.

See also: Addy Osmani at Smashing Magazine goes in-depth on using AVIF and WebP.

Browser Solutions


Screenshot of Squoosh.
Screenshot of Squoosh.

Squoosh is a popular image compression web app that allows you to convert images in numerous formats to other widely used compressed formats, including AVIF.

  • File-size limit: 4MB
  • Image optimization settings (located on the right side)
  • Download controls – this includes seeing the size of of the resulting file and the percentage reduction from the original image
  • Free to use


Screenshot of AVIF.io.
Screenshot of AVIF.io.

AVIF.io is an image tool that doesn’t require any form of code. All you need to do is upload your selected images in PNG, JPG, GIF, etc. and it would return compressed versions of them.

  • Conversion settings (located on the top-right of upload banner)
  • Free to use

You can find answers to your questions on the AVIF.io FAQ page.

Command Line Solutions


avif-cli by lovell lets you take AVIF images stored in a folder and converts them to AVIF images of your specified reduction size.

Here are the requirements and what you need to do:

  • Node.js 12.13.0+

Install the package:

npm install avif

Run the command in your terminal:

npx avif --input="./imgs/*" --output="./output/" --verbose
  • ./imgs/* – represents the location of all your image files
  • ./output/ – represents the location of your output folder
  • Free to use
  • Speed of conversion can be set

You can find out about more commands via the avif-cli GitHub page.


sharp (also maintained by lovell) is another useful tool for converting large images in common formats to smaller, web-friendly AVIF images.

Here are the requirements and what you need to do:

  • Node.js 12.13.0+

Install the package:

npm install sharp

Create a JavaScript file named sharp-example.js and copy this code:

const sharp = require('sharp')  const convertToAVIF = () => {     sharp('path_to_image')     .toFormat('avif', {palette: true})     .toFile(__dirname + 'path_to_output_image') }  convertToAVIF()

Where path_to_image represents the path to your image with its name and extension, i.e.:


And path_to_output_image represents the path you want your image to be stored with its name and new extension, i.e.:


Run the command in your terminal:

node sharp-example.js

And there! You should have a compressed AVIF file in your output location!

  • Free to use
  • Images can be rotated, blurred, resized, cropped, scaled, and more using sharp

See also: Stanley Ulili’s article on How To Process Images in Node.js With Sharp.


AVIF is a technology that front-end developers should consider for their projects. These tools allow you to convert your existing JPEG and PNG images to AVIF format. But as with adopting any new tool in your workflow, the benefits and downsides will need to be properly evaluated in accordance with your particular use case.

I hope you enjoyed reading this article as much as I enjoyed writing it. Thank you so much for your time and I hope you have a great day ahead!

Useful Tools for Creating AVIF Images originally published on CSS-Tricks. You should get the newsletter.


, , , ,

6 Useful Bookmarklets to Boost Web Development

A bookmarklet is a JavaScript-based bookmark that adds to a web browser. I’d like to show you some awesome web browser hacks to aid your web development workflow and how to convert those hacks into time-saving bookmarklets.

  1. Activating design mode
  2. Applying a background to everything
  3. Simulating events
  4. Setting cookies
  5. Toggling classes
  6. Color widget bookmark
  7. What other bookmarklets can you think of?

Activating design mode

Design mode (styled as designMode since it’s a JavaScript property) is for who like to experiment with variations of copy on a live website. For example, copywriters who like to observe how content reads within the flow of the website’s design, or, say, designers who want to ensure that text fits comfortably within a certain space at a certain font size.

JavaScript has a mightily simple feature that can render an entire HTML document editable. It works exactly like HTML’s contenteditable="true" name-value attribute (or contentEditable="true" in JavaScript) but for the whole document. If you’d like to see how it works, start by entering the browser’s console using the relevant keyboard shortcut:

  • Chrome: Option + + J / Shift + CTRL + J
  • Firefox: Option + + K / Shift + CTRL + K
  • Safari: Option + + C / Shift + CTRL + C

Next, type document.designMode="on" into the console, hit Return, and then click on any text element. You’ll see that this text element (and all other text elements) are now editable simply by clicking on them. This method of editing text on a live website is much faster than having to open DevTools, then right-clicking and selecting the “Edit Text” option… and much less tiresome.

Showing an edited version of the CSS-Tricks guide landing page using the design mode bookmarklet.
“Guides and Thangs” — my favorite part of CSS-Tricks

While I’m not sure that “design mode” is the most accurate description of the feature, it’s super useful nonetheless and it’s actually been around for a really long time, surprisingly.

And what’s even an even faster way to enable it? A bookmarklet, of course! Create a bookmark using javascript: document.designMode="on";void 0; as the URL.

Showing the bookmarklet installation.

Applying a background to everything

When HTML elements don’t have backgrounds, it can be difficult to visualize their bounds and/or accurately measure the distance between them and other elements. Developers might want to better visualize bounds when dealing with optical imbalance (i.e. when something “looks off” even though it’s not), margin collapse (when certain margins are ignored), various issues with display:/float:/position:, and more.

Applying backgrounds means applying a semi-transparent background to all HTML elements in order to better visualize their bounds and spacings. It’s something many of us commonly do by opening up DevTools then typing a CSS declaration like selector { background: rgb(0 0 0 / 10%); } into the “Styles” box. But again, it’s really tiresome and repetitive — and something we can simplify with a bookmarklet.

Once again, to create a bookmark, we’re going to make a URL. Here’s what we can use for this one:

javascript: document.querySelectorAll("*").forEach(element => element.style.background="rgb(0 0 0 / 10%)");

We’re using a semi-transparent background because the transparency stacks, which ensures that every nested element is distinguishable and the distances between them can be measured.

Showing the CSS-Tricks guides landing page with all backgrounds fill with varying shades of gray.
Apply a background to everything to see what’s happening.

Simulating events

Have you ever had to test a web event that first requires a series of interactions, or certain conditions to be met? It’s super time-consuming to have to test or debug these kinds of functionalities. This event simulation bookmarklet can be used to instantly trigger specific events, making testing a breeze.

Simulating an event means coding a “throwaway” button that triggers a JavaScript event, making it much easier to quickly and repeatedly test the event without having to meet any usual user-facing conditions, like needing to be logged in.

Assuming that you have your JavaScript event listeners set up, create a bookmark for each event that you’d like to trigger/simulate and submit the following URL:

javascript: document.querySelector("SELECTOR").click();

Replace “SELECTOR” with your unique selector, replace “click” with “focus” or “blur” (when necessary), or extend the snippet to make it trigger more complex events, like scroll.

Setting cookies

Cookies are tokens that are stored on a website visitor’s computer by the website that they’re visiting. Cookies contain data that can be read by the website that created them until they’ve exceeded their expiration date or have been deleted. The mere existence of a cookie can determine whether or not a visitor is logged in, whereas the data itself can store user information.

An example of a scenario where you might want to set a cookie using a bookmarklet is when you want to force a logged-in state during website testing. Websites often look very different for users that are logged in, however, logging in and out eventually becomes very tedious, so this bookmarklet can save quite a bit of time.

Manually writing expires= dates for cookies is awkward as heck, but luckily this create-your-own-set-cookie-bookmarklet app can generate a bookmarklet for a specific cookie, if you know its exact name.

Toggling classes

You may want to add or remove a class from an HTML element in order to trigger a fresh state or a change in appearance, otherwise known as toggling classes. Class toggling happens behind the scenes of most live websites, but it can also be used during testing to skip having to meet certain user-facing conditions.

Class toggling can be used to trigger changes in appearance (e.g. alternative themes or states) and even animations, but it can be a little fiddly when doing it with developer tools when it’s only for testing reasons (i.e. the website doesn’t actually function that way for users). Similar to the other bookmarklets, use this one to rapidly toggle classes and save yourself time.

Create the following bookmarklet to target all elements that match your chosen “SELECTOR”, which, in turn, toggles the “CLASS.”

javascript: document.querySelectorAll("SELECTOR").forEach(element => element.classList.toggle("CLASS"));

Color widget bookmark

While not technically a “bookmarklet,” this bookmarkable data URI by Scott Jehl opens up an <input type="color"> in a new tab:

data:text/html;charset=utf-8,%3Chtml%3E%3Ctitle%3EColor Picker%3C%2Ftitle%3E%3Cinput type%3D"color"%3E%3C%2Fhtml%3E

Why is that cool? Well, how many times have you needed to grab a color value off a page, only to find yourself cracking open DevTools, clicking through a bunch of elements, and pouring over CSS properties to find the value? Better to run this little guy, click the element, and get a color right away!

What other bookmarklets can you think of?

Are there any overly repetitive web development workflows that require you to use the web browser’s sometimes-awkward developer tools? If so, it’s super easy to create your own time-saving bookmarklets. Just remember to start the URL with javascript:!

And if you’ve made a bookmarklet to simplify your workflow, I’d love to see it! Share them here in the comments and let’s get a nice collection going.

6 Useful Bookmarklets to Boost Web Development originally published on CSS-Tricks. You should get the newsletter.


, , ,

A Chrome Extension for Cloudinary That Helps You Pluck Out Useful Media URLs From Your Library Quickly

(This is a sponsored post.)

Cloudinary is a host for your digital assets like images and video. If you don’t already know them, you should, because you can build it into the asset management you almost certainly need to do if you run any size of website. Cloudinary helps you serve the assets as efficiently as technologically possible, meaning optimization, resizing, CDN hosting, and goes further in allowing interesting transforms on those assets.

If you already use it, unless you use it entirely through the APIs, you’ll know Cloudinary has a Media Library that gives you a UI dashboard for everything you’ve ever uploaded to Cloudinary. This is where you find your assets and open them up to play with the settings and transformations and such (e.g. blur it — then serve in the best possible format with automatic quality adjustments). You can always pop over to cloudinary.com to use this. But wouldn’t it be nice if this process was made a bit easier?

That clutch moment where you get the URL of the image you need.

There are all sorts of moments while bopping the web around doing our jobs as developers where you might need to get your fingers on an asset URL.

Gimme that URL!

Here’s a personal example: we have a little custom CMS thing for building our weekly email The CodePen Spark. It expects a URL to an image.

This is the exact kind of moment that the brand new Chrome Media Library Extension could help. Essentially it gives you a context menu you can use right in the browser to snag a URL to an asset. Right click, Insert and Asset URL.

It pops up a UI right inline (where you are on the web) of your Media Library, and you pick an image from there. Find the one you want, open it up, and you can either “edit” it to customize it to your liking, or just Insert it straight away.

Then it plops the URL right onto the site (probably an input) where you need it.

You can set up defaults to your liking, but I really like how the defaults are f_auto and q_auto which are Cloudinary classics that you’ll almost surely want. They mean “serve in the best possible format” and “optimize it intelligently”.

Sharon Yelenik introduced it on the Cloudinary blog:

Say your team creates social posts on a browser tab on an automated marketing application. To locate a media asset, you must open another tab to search for the asset within the Media Library, copy the related URL, and paste it into the app. In some cases, you even have to download an asset and then upload it into the app.

Talk about a classic example of menial, mundane, and repetitive chores!

Exactly. I like the idea of having tools to optimize workflows that should be easy. I’d also call Cloudinary a bit of a technical/developer tool, and there is an aspect to this that could be set up on anyone’s machine that would allow them to pick assets from your Media Library easily, without any access control worries.

If all this appeals to you:

Or see more at Cloudinary Labsdocumentation, and blog post.

A Chrome Extension for Cloudinary That Helps You Pluck Out Useful Media URLs From Your Library Quickly originally published on CSS-Tricks. You should get the newsletter and become a supporter.


, , , , , , , , , ,

How to Use Native Custom Fields in WordPress (and 5 Useful Examples)

Custom Fields in WordPress are arbitrary bits of data that you can apply to Posts, Pages, and Custom Post Types in WordPress. Metadata, as it were, in the form of key/value pairs. For example:

  • Key: subtitle / Value: They are more than they are cracked up to be
  • Key: header_color_override / Value: #e52e05
  • Key: property_url / Value: https://example.com/123

WordPress has their own documentation of this feature, so I’m not trying to replicate that. I’d just like to show you essentially what custom fields in WordPress are, how they work, how to use them, and some use cases from my own personal experience.

Table of Contents

How to Add/Edit/Remove Custom Fields in WordPress

The UI for Custom Fields in WordPress looks like this:

Showing that Custom Fields in WordPress appear below the content area of the block editor in the admin user interface.

If you don’t see it, it’s possible you may need to go under the three-dots menu, Preferences, and then find the toggle for Custom Fields and turn it on.

Showing the option to enable Custom Fields in WordPresss in the Block Editor Preferences settings. It is at the first toggle beneath the Additional settings.
The UI forces you to refresh the page when turning this feature on and off.

To add a Custom Field, type in the Key (labeled “Name”) and Value, then click Add Custom Field.

Showing a Custom Field in WordPress with a name of favorite_food and a value of burrito. There a button below the name input to add the custom field.

After it’s added, you can delete or update it from buttons below the Key/Name:

Showing a Custom Field in WordPress with a name of favorite_food and a value of burrito. There are two buttons below the name to delete or update the custom field.

After you have used Custom Fields, the keys will form into a dropdown menu for easier selection.

Showing the dropdown menu that opens when clocking on the Name field of a custom field in WordPress, allowing you to select an existing custom field.

Why use Custom Fields?

Custom Fields, along with Custom Post Types, are what make WordPress a CMS out-of-the-box rather than being limited to a simple blogging platform.

Here on CSS-Tricks, believe it or not, we use over 100 Custom Fields to do different things on this site. We tend to reach for them for relatively simple things, and it’s nice as it’s a core feature of WordPress that will continue to work forever without too much worry about compatibility or awkward technical debt.

The big idea is to open up templating possibilities. Imagine you have a page for real estate listings that has:

  • Address
  • Listing price
  • Bedrooms
  • Bathrooms
  • etc.

With custom fields, you have all that information available as discreet little chunks of data that you can echo (i.e. display) into a page template wherever you need to. That’s much more flexible than having all that data in the post content itself, even with the Block Editor.

WordPress Custom Fields use case examples

Custom Fields in WordPress can be used for so many different things! But let’s look at a five practical use cases that we have implemented here on CSS-Tricks.

1. Display additional information

Say you are publishing a video and want to have the running time of the video available to display. That’s as easy as saving the running_time as a Custom Field and displaying it wherever you’d like:

A side-by-side showing a published post on the left with the running time of a video circled in red, and the WordPress admin on the right with the running time custom field circled in the block editor showing the exact same information that is published in the post.
Note other Custom Fields in use here, like the youtube field, which we have so that we can output where the

2. Hide/Show Different Content/Features

Let’s say you want to be able to collapse the Comments area sometimes on different blog posts. You could set a custom field called should_toggle_comments and set a value of true. That’s what we do here on CSS-Tricks. In our comments.php template, we output a <ol> of all the comments, but if this custom field is there, we wrap the whole thing in a <details> element, collapsing it by default:

<?php if (get_post_meta($ post->ID, 'should_toggle_comments', true)) { ?> <details class="open-all-comments">   <summary>Toggle All Comments (there are a lot!)</summary>   <?php } ?>      <ol class="commentlist" id="commentlist">       <?php wp_list_comments('type=comment&avatar_size=512&callback=csstricks_comment'); ?>     </ol>    <?php if (get_post_meta($ post->ID, 'should_toggle_comments', true)) { ?>   </details> <?php } ?>

3. Special pull quotes

Say you have a special Category archive that displays a group of posts that contain the same category, then use a custom template for that category, like category-fancypants.php. Maybe you yank out a custom quote from each article as a custom field called main-pullquote:

<blockquote>   <?php     echo get_post_meta($ post->ID, 'main-pullquote', true);   ?> </blockquote>

That’s what we do for our annual end-of-year series:

A side by side showing the the main pull quote custom field in WordPress circled in red, and the category archive on the right with a red arrow pointing to the corresponding pull-quote that displays on the page.

4. Customize an RSS feed

We build a couple of totally custom RSS feeds here on CSS-Tricks that are different from what WordPress offers out of the box — one for videos and one for newsletters. The video feed in particular relies on some WordPress Custom Fields to output special data that is required to make the feed work as a feed for our video podcast.

Side by side showing the rss videos template in code on the left with the custom field part circled in red, and the RSS feed open in the browser on the right with an arrow pointing to where the corresponding code renders as the video enclosure.
The location of the video and the duration are both kept in custom fields

5. Hide/Show Author

Our sponsored posts here on CSS-Tricks are sometimes written to sound largely like an announcement from a company. They were written like that on purpose and likely have been written by multiple people by the time its actually published. A post like that doesn’t really need to be “by” someone. But sometimes sponsored posts are definitely authored by a specific person, even sometimes in the first person, which would be weird without showing a byline. That’s why we use a showSponsorAuthor custom field, to show that author if we need it.

<div class="sponsored-post-byline">   ❥ Sponsored   <?php if (get_post_meta($ post->ID, 'showSponsorAuthor', true)) { ?>     (Written by <?php the_author(); ?>)   <?php } ?> </div>

Above is a part of a template. We always mark a sponsored post as sponsored in the byline (example), but only optionally do we visually show the author (example), controlled by a custom field.

The APIs for displaying Custom Fields in WordPress

Most commonly, you’re looking to display the value of a single field:

<?php echo get_post_meta($ post->ID, 'mood', true); ?>

That true at the end there means “give me a single value,” meaning that even if there are multiple custom fields with the same name, you’ll only get one. To get multiple of the same name, use false, like:

<?php $ songs = get_post_meta($ post->ID, 'songs', false); ?> <h3>This post inspired by:</h3> <ul>   <?php foreach($ songs as $ song) {     echo '<li>'.$ song.'</li>';   } ?> </ul>

If you want to just dump them all out (probably mostly useful for debugging), you can do that like this:

<?php the_meta(); ?>

Although, note that this skips custom fields that start with an underscore (_), so you might consider this approach instead.

Querying for Custom Fields in WordPress

Say you wanted to query for all posts that have some particular custom field. That’s possible!

<?php $ the_query = new WP_Query(array(   'meta_key' => 'example_field_name'   'meta_value' => 'example_field_value' // as a string!  ));  if ($ the_query->have_posts()) {   while ($ the_query->have_posts()) {     $ the_query->the_post();     echo '<div>' . get_the_title() . '</div>';   } }  wp_reset_postdata();

The example above will run a query for posts that have both a custom field of example_field_name and where that field has a value of example_field_value. You could do either/or.

There is a lot more you can do here. You can use comparisons, you can get the values as numbers, and even query for multiple fields at once. We detail all that in Custom Loop/Query Based on Custom Fields.

Limiting Custom Fields in the Name dropdown

The UI dropdown for existing Custom Fields in WordPress is capped at something like 30 fields. So, if you have more than 100 different keys, the dropdown menu will look arbitrarily cut off. You can increase that number with a filter in functions.php or a plugin:

function customfield_limit_increase( $ limit ) {   $ limit = 150;   return $ limit; } add_filter( 'postmeta_form_limit', 'customfield_limit_increase' );

Any other Block Editor concerns?

The main concern is when you can’t see the custom fields UI at all. We covered how to turn it back on (because it might default to off), so always check that. The Advanced Custom Fields plugin also turns it off, so if you’re using that plugin, note there is a line below to help turn it back on (in the case you use both, as we do).

I’m not sure there is a standard way to show the value of a custom field within a block in the block editor either. If you know of a clear way, leave a comment!

Relationship to Advanced Custom Fields

The UI for native Custom Fields in WordPress is pretty… underserved. It’s not fancy, it’s got rough edges (we find that Custom Fields have a weird way of duplicating themselves on multiple post saves, for example). It doesn’t seem like Custom Fields, while native, are a particularly first-class feature of WordPress.

Advanced Custom Fields (ACF) changes that in a big way. The spirit remains the same: attach data to content. But rather than the simple string-based key-value interface that we’ve detailed, you essentially model the data with different types and it builds really nice custom UI for you to use to input that data, even integrating directly with the Block Editor.

Imagine a podcast website where each post is an individual episode. The Block Editor might be nice for written content about the episode, but probably not a good idea for all of the metadata that goes with it. The list of guests, the duration, the location of the MP3 file, the sponsor, time jump links, etc. Custom Fields are great for that, but since there are so many, you’ll be well served by Advanced Custom Fields here instead of using native Custom Fields in WordPress. Here’s a setup example of what you get as we do on the ShopTalk Show podcast:

Side by side showing the settings for custom fields in the Advanced Custom Fields plugin on the left, and those custom fields displayed on the right in the  WordPress Block Editor of a new post.

ACF, probably in an attempt to encourage using it directly and not confusing people with the native Custom Fields interface, removes the native Custom Fields interface. If you’re like us and use both types of fields, you’ll need to bring the native Custom Fields UI back to the post editor with a filter that ACF provides:

add_filter('acf/settings/remove_wp_meta_box', '__return_false');

If you use native Custom Fields in WordPress at all, you’ll want that in your functions.php file or a functionality plugin.

Note for plugin developers

Use the underscore hiding technique.

Some plugins use the Custom Fields API as a place to store post-specific data. I think that’s OK, but I’d like to implore plugin developers to always use underscore-and-plugin-prefixed custom field names when doing so.

When custom fields start with an underscore, they aren’t shown in the UI. Meaning for those of us who use the Custom Fields UI directly, it’s not cluttered with fields created by other plugins. The exception, of course, is if you intend users to be able to control what the plugin does with the Custom Field values. In that case, fine, leave those few non-underscore-prefixed fields.

_bobs_plugin_internal_value_1 // Hidden in UI _bobs_plugin_internal_value_2 // Hidden in UI bobs_plugin_config  // Shows in UI  _adrians_plugin_internal_value_1  // Hidden in UI _adrians_plugin_internal_value_2 // Hidden in UI

More examples using Custom Fields in WordPress

What do you use them for?

Do you use Custom Fields in WordPress? I’m particularly curious about native custom field usage.

How to Use Native Custom Fields in WordPress (and 5 Useful Examples) originally published on CSS-Tricks. You should get the newsletter and become a supporter.


, , , , ,

Useful and Useless Code Comments

Jim Nielsen:

If somebody says a comment isn’t adding any value, I would ask: to whom?

Personally, I’ve never liked the advice that writing obvious comments is bad practice—probably because I write obvious comments all the time.

Jim showed off some examples of “code comments that are at the same level of fidelity as the code itself.” Those are the hardest calls with code comments.

// this function adds two numbers function add(a, b) {   return a + b; }

Easy to point at that and call it not useful. I tend not to leave this type of comment, but it’s fair play for Jim to question that. Comments can be used for a wide swath of people whom may at some point interact with that code, so why gate-keep it?

[…] comments can serve a very different purpose when they’re being read vs. when they’re being written. Those are almost two different kinds of activities.

I’d add they serve a different purpose when re-visiting old code vs actively working. Also different when you’re trying to code review versus directly contribute.

Direct Link to ArticlePermalink

The post Useful and Useless Code Comments appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.


, , ,

Is “is” Useful?

God I’m funny.

Anytime we have fairly repetitive selectors that have a common parent, it’s probably a place we can use the :is() pseudo-selector.

Holger Bartel demonstrates like this:

section section h1, section article h1, section aside h1, section nav h1, article section h1, article article h1, article aside h1, article nav h1, aside section h1, aside article h1, aside aside h1, aside nav h1, nav section h1, nav article h1, nav aside h1, nav nav h1 {   font-size: 20px; }


:is(section, article, aside, nav) :is(section, article, aside, nav) h1 {   font-size: 20px; }

Adam Argyle demonstrated like this:

MDN has an extra dramatic one:

ol ol ul,     ol ul ul,     ol menu ul,     ol dir ul, ol ol menu,   ol ul menu,   ol menu menu,   ol dir menu, ol ol dir,    ol ul dir,    ol menu dir,    ol dir dir, ul ol ul,     ul ul ul,     ul menu ul,     ul dir ul, ul ol menu,   ul ul menu,   ul menu menu,   ul dir menu, ul ol dir,    ul ul dir,    ul menu dir,    ul dir dir, menu ol ul,   menu ul ul,   menu menu ul,   menu dir ul, menu ol menu, menu ul menu, menu menu menu, menu dir menu, menu ol dir,  menu ul dir,  menu menu dir,  menu dir dir, dir ol ul,    dir ul ul,    dir menu ul,    dir dir ul, dir ol menu,  dir ul menu,  dir menu menu,  dir dir menu, dir ol dir,   dir ul dir,   dir menu dir,   dir dir dir {   list-style-type: square; }
:is(ol, ul, menu, dir) :is(ol, ul, menu, dir) ul, :is(ol, ul, menu, dir) :is(ol, ul, menu, dir) menu, :is(ol, ul, menu, dir) :is(ol, ul, menu, dir) dir {   list-style-type: square; }

It’s less code and easier to reason.

Kezz Bracey notes that pairing it with :not() can be nice as well:

:not(article, section, aside) :is(h1, h2, h3, h4, h5, h6) {   font-weight: 400; }

Browser support is just starting to get there and polyfilling is hard, so we aren’t at day-to-day no-brainer use levels quite yet. I’d bet it’s not too far away.

The post Is “is” Useful? appeared first on CSS-Tricks.



The Amazingly Useful Tools from Yoksel

I find myself web searching for some tool by Yoksel at least every month. I figured I’d list out some of my favorites here in case you aren’t aware of them.

The post The Amazingly Useful Tools from Yoksel appeared first on CSS-Tricks.


, , , ,