Enhance WordPress: Build improved APIs and libraries
Sep 02, 2023 am 11:33 AMIt feels like everything we come into contact with is carefully designed: website, phone number, subway map, etc. Even things we used to take for granted: thermostats, smoke detectors, and car dashboards now receive careful user experience treatment.
Design is more than just look and feel: it also needs to consider the various ways users need to interact with our devices/tools/screens/objects.
This also applies to programming.
(Un)Designed Programming
Programming languages ??are a large and complex world. Even PHP, which many programming snobs consider too "simple", is actually a fairly complex combination of functions and classes that behave in very inconsistent ways.
Over the years, the syntax, methods, and naming have evolved across millions of different users and applications. Most tend to reflect the underlying construction inside - not necessarily how you want to use it.
Great moments in API design: jQuery
??>When I started writing JavaScript around 2006, things were a mess. Here's how I find a tag with a specific class and move it around the DOM:
var uls = getElementsByTagName("ul"); var classToSearch = "foods"; for (var i = 0; i < uls.length; i++) { var classes = uls[i].getClasses(); for (var j = 0; j < classes.length; j++){ if (classes[j] == classToSearch){ myUL = uls[i]; } } } var $li = document.createElement('li'); $li.innerHTML = 'Steak'; myUL.innerHTML += $li;
Finish!
jQuery makes JavaScript fun again. In the late 2000s, the impact was so huge that I remember my dad asking me about “something weird” he’d read about in the Wall Street Journal. But despite its huge effect, jQuery doesn't add any "new functionality" to JavaScript. It just breaks down what developers have to do into very clear patterns.
Instead of reinventing how to find content on a page, they leveraged something people already knew: CSS selectors. Then it's just a matter of gathering a bunch of common operations and organizing them into dozens of functions. Let's try the previous example again, now using jQuery:
var $li = $('<li>Steak</li>'); $("ul.foods").append($li);
In 2006, I bought a 680 page Ajax book. With jQuery's excellent API, it's almost superseded by this:
$.post();
WordPress API
While API has come to stand for "third-party services," it simply means a programming interface that talks to a system. Just like the Twitter API or the Facebook API, the WordPress API also exists. You wouldn't do a raw database query to create a post, right? You use wp_insert_post
.
But many design holes plague the WordPress API. You might use get_the_title
but get_the_permalink
will generate an error if you use get_permalink
. Hey, when you have a decades-long open source project involving thousands of people's code and millions of users: you're going to encounter some quirks.
You can save a lot of time by masking these quirks and writing according to the habits and behaviors of the programmer you're writing for (which is probably you). This is where you can design the right interface for programming the plugins and themes you use every day.
solution
To speed up my work and reduce repetitive tasks, I created libraries to handle the commands and customizations I always needed.
1. Shortcuts for common tasks
Take the source of getting the post thumbnail as an example. It turns out WordPress has no built-in functionality to get thumbnails based on post IDs (only attachment IDs).
This means I often find myself doing this:
$thumb_id = get_post_thumbnail_id( get_the_ID() ); $src = wp_get_attachment_thumb_url( $thumb_id ); echo '<img alt="" src="' . $src . '" />';
But there must be a better way!
function get_thumbnail_src( $post ){ $thumb_id = get_post_thumbnail_id( $post ); $src = wp_get_attachment_thumb_url( $thumb_id ); return $src; } echo '<img alt="" src="' . get_thumbnail_src( get_the_ID() ) . '" />';
2: Unpredictable input, predictable output
much better! In fact, you find yourself using it all the time and then sharing it with other developers in the company.
Your friend is in trouble, so he calls you to debug, and you see:
echo '<img src="' . get_thumbnail_src( get_post() ) . '">';
It seems he accidentally used get_post
instead of get_the_ID
. You yelled at him. But wait, why notmake it more acceptable?
Maybe we can adjust our function so that it can take a WP_Post
object and still give the user what they expect. Let's get back to the function:
function get_thumbnail_src( $post ){ if ( is_object( $post ) && isset( $post->ID ) ){ $post = $post->ID; } else if ( is_array( $post ) && isset( $post['ID'] ) ) { $post = $post['ID']; } $thumb_id = get_post_thumbnail_id( $post ); $src = wp_get_attachment_thumb_url( $thumb_id ); return $src; }
So if they send WP_Post
objects or an array, your function can still help them get what they need. This is an important part of a successful API: hiding messy internals. You can make separate functions for
get_thumbnail_src_by_post_id and
get_thumbnail_src_by_wp_post_object.
In fact, it may be preferable for more complex conversions, but you can simplify the interface by routing individual functions to the correct subroutines. No matter what the user sends, this function will always return the string of the image source.
Let's move on: What if they send nothing?
3。合理的默認值
function get_thumbnail_src( $post = false ) { if ( false === $post ) { $post = get_the_ID(); } else if ( is_object( $post ) && isset( $post->ID ) ) { $post = $post->ID; } else if ( is_array( $post ) && isset( $post['ID'] ) ) { $post = $post['ID']; } $thumb_id = get_post_thumbnail_id( $post ); $src = wp_get_attachment_thumb_url( $thumb_id ); return $src; }
我們再次進行了簡化,因此用戶無需發(fā)送帖子,甚至無需發(fā)送帖子 ID。在循環(huán)中時,所需要做的就是:
echo '<img src="'.get_thumbnail_src().'" />';
我們的函數(shù)將默認為當前帖子的 ID。這正在變成一個非常有價值的功能。為了確保它能很好地發(fā)揮作用,讓我們將它包裝在一個類中,這樣它就不會污染全局命名空間。
/* Plugin Name: JaredTools Description: My toolbox for WordPress themes. Author: Jared Novack Version: 0.1 Author URI: http://upstatement.com/ */ class JaredsTools { public static function get_thumbnail_src( $post = false ) { if (false === $post ) { $post = get_the_ID(); } else if ( is_object( $post ) && isset( $post->ID ) ) { $post = $post->ID; } else if ( is_array( $post ) && isset( $post['ID'] ) ) { $post = $post['ID']; } $thumb_id = get_post_thumbnail_id( $post ); $src = wp_get_attachment_thumb_url( $thumb_id ); return $src; } }
并且請不要在您的類前面添加 WP
。我將其設為公共靜態(tài)函數(shù),因為我希望它可以在任何地方訪問,并且它不會改變:輸入或執(zhí)行不會更改函數(shù)或?qū)ο蟆?
該函數(shù)的最終調(diào)用是:
echo '<img src="'.JaredsTools::get_thumbnail_src().'">';
先設計,后構(gòu)建
讓我們繼續(xù)處理更復雜的需求。當我編寫插件時,我發(fā)現(xiàn)我總是需要生成不同類型的錯誤和/或更新消息。
但是基于事件的語法一直困擾著我:
add_action( 'admin_notices', 'show_my_notice'); functon show_my_notice(){ echo '<div class="updated"><p>Your thing has been updated</p></div>'; }
WordPress 遵循這種基于事件的架構(gòu)有很多充分的理由。但這并不直觀,除非您想坐下來記住不同的過濾器和操作。
讓我們將此匹配作為最簡單的用例:我需要顯示管理員通知。我喜歡首先設計這個 API:我找出在代碼中引用該函數(shù)的最佳方式。我希望它讀起來像這樣:
function thing_that_happens_in_my_plugin($post_id, $value){ $updated = update_post_meta($post_id, $value); if ($updated){ JaredsTools::show_admin_notice("Your thing has been updated") } else { JaredsTools::show_admin_notice("Error updating your thing", "error"); } }
一旦我設計了端點,我就可以滿足設計要求:
class JaredsTools { public static function show_admin_notice($message, $class = 'updated'){ add_action('admin_notices', function() use ($message, $class){ echo '<div class="'.$class.'"><p>'.$message.'</p></div>'; }); } }
好多了!現(xiàn)在我不需要創(chuàng)建所有這些額外的函數(shù)或記住瘋狂的鉤子名稱。在這里,我使用 PHP 匿名函數(shù)(也稱為“閉包”),它讓我們可以將函數(shù)直接綁定到操作或過濾器。
這可以讓您避免在文件中出現(xiàn)大量額外的函數(shù)。 use
命令讓我們將參數(shù)從父函數(shù)傳遞到子閉包中。
保持直覺
現(xiàn)在另一位同事打電話給您。她不知道為什么她的管理通知沒有變成紅色:
JaredsTools::show_admin_notice("Error updating your thing", "red");
這是因為她正在發(fā)送“紅色”(她希望將盒子變成紅色),而實際上她應該發(fā)送觸發(fā)紅色的類名稱。但為什么不讓它變得更容易呢?
public static function show_notice( $message, $class = 'updated' ) { $class = trim( strtolower( $class ) ); if ( 'yellow' == $class ) { $class = 'updated'; } if ('red' == $class ) { $class = 'error'; } add_action( 'admin_notices', function() use ( $text, $class ) { echo '<div class="'.$class.'"><p>' . $text . '</p></div>'; }); }
我們現(xiàn)在已經(jīng)接受了更多的用戶容忍度,這將使我們在幾個月后回來使用它時更容易分享。
結(jié)論
在構(gòu)建了其中一些之后,以下是我學到的一些原則,這些原則使這些原則對我和我的團隊真正有用。
1.首先進行設計,讓函數(shù)的構(gòu)建符合人們想要使用它的方式。
2. 拯救你的鍵盤!為常見任務創(chuàng)建快捷方式。
3. 提供合理的默認值。
4. 保持最小化。讓您的庫來處理處理。
5. 對輸入要寬容,對輸出要精確。
6. 也就是說,使用盡可能少的函數(shù)參數(shù),最多四個是一個很好的參數(shù)。之后,您應該將其設為選項數(shù)組。
7. 將您的庫組織成單獨的類,以涵蓋不同的領域(管理、圖像、自定義帖子等)。
8. 包含示例代碼的文檔。
在 Upstatement,我們的 Timber 庫使構(gòu)建主題變得更加容易,而 Jigsaw 提供了節(jié)省時間的快捷方式來自定義每個安裝。
這些工具節(jié)省的時間讓我們可以花更多時間構(gòu)建每個網(wǎng)站或應用程序的新的和創(chuàng)新的部分。通過執(zhí)行深奧的命令(例如向管理帖子表添加一列)并制作簡單的界面:我們公司的任何設計師或開發(fā)人員都可以使用與專業(yè) WordPress 開發(fā)人員相同的能力完全自定義每個網(wǎng)站。
The above is the detailed content of Enhance WordPress: Build improved APIs and libraries. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.

robots.txt is crucial to the SEO of WordPress websites, and can guide search engines to crawl behavior, avoid duplicate content and improve efficiency. 1. Block system paths such as /wp-admin/ and /wp-includes/, but avoid accidentally blocking the /uploads/ directory; 2. Add Sitemap paths such as Sitemap: https://yourdomain.com/sitemap.xml to help search engines quickly discover site maps; 3. Limit /page/ and URLs with parameters to reduce crawler waste, but be careful not to block important archive pages; 4. Avoid common mistakes such as accidentally blocking the entire site, cache plug-in affecting updates, and ignoring the matching of mobile terminals and subdomains.
