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.
WordPress REST API post orderby custom value
Ordering posts by menu_order doesn’t work out of the box with the WP REST API. To enable this you need to add a filter to rest_{post_type}_collection_params
for each post type you want to order by menu_order.
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')
Gatherpress. Event Scheduling community driven plugin
This project is for the collaborative effort to build a compelling event management application using open source tools such as WordPress and BuddyPress and the grit sweat and love of the community, for the community.
We’re creating the very network features we need to host events and gather well.
Post Type Switcher
This plugin adds a simple post-type drop-down to the post editor interface, allowing you to reassign any post to a new post type. It allows you to switch post’s type while editing your post.
Increase per_page limit in REST API
The rest_{$this->post_type}_collection_params
does indeed describe the available params.
You should be able to set the per_page
max at $params['per_page']['maximum']
.
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.
How to Create a WordPress Custom Dashboard for Yourself or Clients
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
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 ); } } } } // //////
Quick Tip: Block OpenAI from Using Content From Your WordPress Site
Whatever your thoughts on AI bots, you may want to take action on your own website to block ChatGPT from crawling, indexing, and using your website content and data.
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.
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.
How to unpack .wpress archive files created by the All-in-one-Wp-Migration WordPress plugin
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
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.
Custom Post Type Templates from Plugin Folder?
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' );
How to add a custom field to quick edit
There are a few steps to create the custom quick edit box and custom column
- create a custom meta key (assumed that you have 1 already)
- 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)
- add custom quick edit box
- add save logic
- load script to modify original inline-edit-post function in order to support custom meta value
- prepare the script file
Modernizing JavaScript Code in WordPress
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.
How to Modify or Add Custom Columns to Post List in WordPress Admin
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).
How to Use Sequential Order Numbers for Member Invoices in Paid Memberships Pro
Generate custom order codes / order numbers that increment for Paid Memberships Pro Orders [Custom order sequence]
WordPress.org Strongly Urges Theme Authors to Switch to Locally Hosted Webfonts
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.”
Making Autocomplete Search in WordPress With Code
The autocomplete is generated with help from jQuery UI Autocomplete, a script that is included in WordPress as default.
Run a WP-CLI command as a given WordPress user
Use the –user=
Privacy Policy Generator, Terms & Conditions Generator WordPress Plugin : WPLegalPages
Generate a professional WordPress Privacy Policy, terms of use, terms & conditions, eCommerce returns & refunds policy, affiliate disclaimers & more. Covers 25+ expert vetted legal pages for WordPress websites.
Setting Cookies in WordPress
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 );
How to Create a Custom WordPress Gutenberg Block: Tutorial Series
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.
Intercept WordPress API Requests
Say you want to intercept a response from any WordPress API call before it gets returned to the user? For example, you want to block /users/ route or append additional content to a /posts/ response. Simply call the rest_pre_echo_response filter and you can modify all responses!
wp-rest-polylang
Adds value `lang` and `translations` to WP REST api response for each Post and Page request for site running the Polylang Pro plugin.
Adds polylang_translations and keeps lang to WP REST api response for each Post and Page request for site running the Polylang Pro plugin.
Extending Gutenberg With SlotFill and Filters
SlotFill is a modernized take on classic interface “hooks and filters”—a convention for empowering developers to extend the publishing interface outside of the block editor itself—that found its way into WordPress.
Gutenberg : override core blocks rendering
The easiest way to achieve this, is to consider the gallery as a Dynamic block and re-declare its render through PHP:
One thousand and one way to extend Gutenberg today
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).
What does apply_filters(…) actually do in WordPress?
apply_filters($tag, $value) passes the ‘value’ argument to each of the functions ‘hooked’ (using add_filter) into the specified filter ‘tag’. Each function performs some processing on the value and returns a modified value to be passed to the next function in the sequence.
Adding custom fields in the WordPress REST API
Adding a new field with the register_api_field function
The described below requires more code, but it’s more elegant and opens up many more possibilities for expanding our functionality.
Why We Should Set the $content_width Variable in WordPress Themes
It is a theme feature which helps us to control our content width for images, videos and embeds. If you used _s starter theme or browsed through any official WordPress theme, you saw it in the functions.php. In today’s responsive design, it is not the most necessary tool for the images but still useful because of the other media formats.
Customizer Export/Import
The Customizer Export/Import plugin allows you to export or import your WordPress customizer settings from directly within the customizer interface! If your theme makes use of the WordPress customizer for its settings, this plugin is for you!