Autonomía digital y tecnológica

Código e ideas para una internet distribuida

Linkoteca. wordpress


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.

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')

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.

The free White Label CMS plugin is a good all-in-one CMS solution that will let you quickly customize most aspects of the WordPress dashboard.

In total, it can help you:

  • Replace the generic WordPress branding with your own
  • Customize the WordPress login page
  • Add your own custom dashboard widget welcome panel
  • Include your own RSS feed as a dashboard widget
  • Hide menu items from the sidebar or top toolbar
  • Disable the WordPress toolbar
//////
// 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 );
            }
        }
    }
}

//
//////

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.

Recently I needed to download some files from a WordPress installation where the client only gave me access to the admin dashboard. Fortunately the All-in-One WP Migration plugin was already installed, so I could take a quick backup of the whole site by downloading the installed plugins, theme and database.

To my surprise downloading the backup from the All-in-One WP Migration plugin only gave me a single compressed migration.wpress file that any unpack tool refused to extract. A little web search brought me to a five year old tool called Wpress-Extractor but the provided binaries for MacOS refused to work because the package was already too old.

So I decided to rewrite this little helpful tool in Node.js to make it cross-platform compatible for Windows, MacOS and Linux.

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.

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' );

There are a few steps to create the custom quick edit box and custom column

  1. create a custom meta key (assumed that you have 1 already)
  2. 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)
  3. add custom quick edit box
  4. add save logic
  5. load script to modify original inline-edit-post function in order to support custom meta value
  6. prepare the script file

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.

The filter for modifying, removing or adding columns to post list in WordPress admin panel is manage_{$post_type}_posts_columns.

Which hook you need to use for controlling the output of the column content depends on whether or not your post type is set to be hierarchical or not.

Any non-hierarchical post types, including WordPress’ built-in post type ‘post‘, use the hook name manage_{$post_type}_custom_column. Any hierarchical post types, including WordPress’ built-in post type ‘page‘, use the hook name manage_pages_custom_column (note: no injection of post type name in the hook name).

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.”

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 );

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.

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).