Set Site Icon programmatically (eg. using `wp cli`)

Wordpress has a "Site Icon" feature that serves correctly-sized favicons and so on to browsers. Is there a way to drive this feature programmatically, eg. by uploading media and setting an option with wp cli?

Topic favicon icon wp-cli Wordpress

Category Web


Use wp-cli commands wp media import and wp option update.

wp media import <file> : Creates attachments from local files or URLs.

wp option update <key> : Updates an option value.

Image from theme folder :

$ wp media import "$(wp theme path)/theme/assets/images/logo.png" --porcelain | wp option update site_icon

Image from url :

$ wp media import "https://source.unsplash.com/random/512x512" --porcelain | wp option update site_icon

The flag [--porcelain] output just the new attachment ID.

References :

https://developer.wordpress.org/cli/commands/media/import/

https://developer.wordpress.org/cli/commands/option/update/


I managed to set the favicon of my wordpress using Wordpress CLI:

FAVICON_TITLE="mysite-favicon"
FAVICON_PATH="~/dev/favicon.png"
wp media import ${FAVICON_PATH} --title=${FAVICON_TITLE}
FAVICON_ID=$(wp post list --post_type=attachment --post_title=${FAVICON_TITLE} --format=ids)
wp option update site_icon ${FAVICON_ID}

The 'official rules' about site icons are here:https://www.w3.org/TR/html5/links.html#link-type-icon .

They provide this example of site icons for several sizes:

<link rel=icon href=favicon.png sizes="16x16" type="image/png">
  <link rel=icon href=windows.ico sizes="32x32 48x48" type="image/vnd.microsoft.icon">
  <link rel=icon href=mac.icns sizes="128x128 512x512 8192x8192 32768x32768">
  <link rel=icon href=iphone.png sizes="57x57" type="image/png">
  <link rel=icon href=gnome.svg sizes="any" type="image/svg+xml">

The above link also specifies if the 'link rel=icon ...' is not specified, then the /favicon.ico file (in the site root) will be used.

It further states:

"If multiple icons are provided, the user agent must select the most appropriate icon according to the type, media, and sizes attributes."

("User agent" is the browser rendering the site.)

Also, see one of the answers here https://stackoverflow.com/questions/9943771/adding-a-favicon-to-a-static-html-page that references an application to create all of the different icon sizes and the code needed to use them:

Actually, to make your favicon work in all browsers, you must have more than 10 images in the correct sizes and formats.

I created an App (faviconit.com) so people don´t have to create all these images and the correct tags by hand.

I have not tried the application referenced. YMMV.

And, this question/answer might also be helpful: https://stackoverflow.com/questions/53464667/best-practice-for-ordering-icon-link-tags-in-html-head .

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.