Home > CMS Tutorial > WordPress > Explore WordPress features for web application development: Unlock URL rewriting capabilities

Explore WordPress features for web application development: Unlock URL rewriting capabilities

PHPz
Release: 2023-09-04 20:09:14
Original
1240 people have browsed it

The best thing about modern web application development frameworks is that they provide a way to generate truly clean routes (or URL schemes) that map to a conceptual model of the application structure.

For example, given some type of data (such as individuals), you can do the following:

  • Add to
  • renew
  • delete

etc.

Depending on the nature of your application, you may be able to perform more operations (such as adding a spouse), but for the purposes of this article, basic CRUD operations will suffice.

For those of you who have been paying attention, we have been looking at the various features that WordPress offers as a foundation for application development. As we continue our discussion, it’s worth taking a look at the APIs available for customizing WordPress rewrite rules.

Regular users may be familiar with how to change the URL scheme in the WordPress dashboard (we will discuss this briefly to make sure we are all on the same page), however, for those who need to change the URL scheme, there is more Multi-purpose available. Learn about URL rewriting in WordPress.

In fact, we have the ability to build URL rewrite rules to match and enforce, just like modern MVC-based frameworks.


Understand rewriting rules

To make sure we are all on the same page, think of rewrite rules as a way of matching specific patterns to the web server to retrieve data from the database.

For example, in a standard WordPress installation, the default permalink structure is as follows:

http://domain.com/?p=123
Copy after login

This URL contains a query string parameter, a key-value pair of p=123, which in the context of WordPress means "Retrieve post with ID 123".

If you drill down into the options on the Permalink Settings screen, you'll also see various options:

探索用于 Web 应用程序开发的 WordPress 功能:解锁 URL 重写功能

Another example of a rewrite rule you might see is what’s called a “pretty permalink,” or as it’s named in the WordPress dashboard, a “post name.”

In this format, the URL looks like this:

http://domain.com/post-title/
Copy after login

From here, the requested URL goes to the web server, which then determines the ID of the post with that title based on a set of rules and returns it to the requesting client (i.e., the browser).

Between these two examples, there is a basic principle at work that demonstrates exactly what rewriting rules are.

In short, rewrite rules define a set of rules in which incoming URLs are transformed into a format in which the client retrieves information from the database.

Of course, this raises two questions:

  1. How are rewriting rules generated?
  2. Perhaps more importantly, why are they so complicated?

Business of rewriting rules

Rewriting rules can be a challenge for developers because they are based on regular expressions. Jamie Zawinski has an old saying about regular expressions:

Some people think "I know, I'll use regular expressions" when they encounter a problem. Now they have two problems.

Funny, but true. This is why dealing with custom rewrite rules in WordPress can be a challenge for many developers.

Unfortunately, we can't demonstrate every variation or type of URL scheme that rewrite rules can create or support, but we can look at a few practical examples that show how to get started and provide a basis or guide us in What needs to be done in future application work.

Refresh rewrite rules

One thing to note is that when you define rewrite rules, they don't take effect immediately - they are already flushed. This means you need to delete the old rule set and replace it with the new rule set.

There are two ways to achieve this:

  1. You can click Save changes in the Permalink Settings dashboard. Despite the fact that an option will be selected, anything you define in your application's functions.php file will be used.
  2. You can call $wp_rewrite->flush_rules(); and solve the problem programmatically.

No matter which route you choose, it is important to remember this step because every time you define a new rewrite rule, you will need to refresh the old rule.

How does the rewrite API work?

When actually writing our own rewrite rules, it's important to understand how the rewrite API works.

It can be summarized into four steps:

  1. 从网络服务器请求 URL。
  2. 如果请求的网址存在内容,则将返回该内容(可以是图像、字体或其他内容)。
  3. 如果内容不存在,则请求将被定向到 index.php,它将与网址的模式匹配。
  4. 内容随后将从 WordPress 返回到请求客户端。

如果您有兴趣根据固定链接仪表板中的配置查看重写规则的定义,请查看重写规则检查器插件。

此插件将呈现当前用于匹配指定 URL 模式的所有规则的列表,包括正则表达式和针对 index.php 的匹配变量。

探索用于 Web 应用程序开发的 WordPress 功能:解锁 URL 重写功能

有道理吗?如果没有,让我们看几个简单实用的示例。

重写规则的示例

鉴于我们知道模式将被匹配并传递到 index.php,我们可以利用 add_rewrite_rule 函数来定义自定义 URL 的工作方式。

帖子 ID 的简短标题

假设我们正在查看系统中的第一篇帖子,即 ID 为 1 的帖子。

在大多数普通 WordPress 安装中,这是Hello World,URL 通常为 http://domain.com/hello-worldhttp://domain.com/? p=1 取决于您的永久链接设置(即您当前的重写规则集)。

但是让我们定义一个规则,以便 http://domain.com/first 也将加载数据库中的第一篇文章:

function example_add_rewrite_rules() {

	add_rewrite_rule( 'first', 'index.php?p=1', 'top' );
	flush_rewrite_rules();

}
add_action( 'init', 'example_add_rewrite_rules' );
Copy after login

让我们再添加一条规则,该规则将允许我们在数据库中加载第二篇文章。即 http://domain.com/?p=2

function example_add_rewrite_rules() {

	add_rewrite_rule( 'first', 'index.php?p=1', 'top' );
	add_rewrite_rule( 'second', 'index.php?p=2', 'top' );

	flush_rewrite_rules();

}
add_action( 'init', 'example_add_rewrite_rules' );
Copy after login

假设您已经阅读了 add_rewrite 规则 的文档,这很容易理解,对吧?

简而言之,它接受三个参数:

  • 第一个参数是与请求的 URL 匹配的正则表达式。在我们的例子中,我们使用简单的单词。
  • 第二个参数是实际获取的 URL。同样,在我们的例子中,我们分别检索第一篇和第二篇帖子。
  • 最后,最后一个参数是优先级,可以是“top”或“bottom”。如果设置为“top”,则该规则将优先于所有其他规则进行评估;但是,如果为“bottom”,则将最后评估。

现在,这些示例都是基本的。这还不足以真正向我们展示如何设置自定义路由,例如我们在本文前面概述的路由。为此,我们需要看一些更复杂的表达式。

导入有关刷新重写规则的注释

但在我们开始这样做之前,需要注意的是,像我们上面所做的那样调用 flush_rewrite_rules() 实际上是一种不好的做法。它在上面的示例中有效,但实际上会减慢网站的加载时间。

事实上,它实际上只需要在重写规则发生变化时调用。每当激活插件时都可能会发生这种情况,或者当激活主题时它可能会发生变化。

无论如何,请确保正确挂钩函数,以便重写规则不会在每次加载页面时刷新 - 只要重写规则本身发生更改。


重写规则的更复杂方法

为了引入一组更复杂的重写规则,例如我们在本文前面通过 CRUD 操作详细介绍的重写规则,了解以下两个函数非常重要:

  • add_rewrite_tag 会让 WordPress 了解自定义查询字符串变量。这也与下一个函数结合使用。
  • add_rewrite_rule, 如前所述,将允许我们向 WordPress 添加额外的重写规则(以及设置它们的优先级)。

现在假设我们有一个名为个人的自定义帖子类型,它代表应用程序中的某个人。然后,假设个人还具有以下方法和相应的可用网址:

  • all: http://domain.com/individuals/
  • update: http://domain.com/individual/update/1 用于更新第一人称
  • delete: http://domain.com/individual/delete/1 用于删除第一个人

所以这个模式很简单,但是我们如何实现它呢?

首先,我们需要定义重写规则:

function example_add_rewrite_rules() {

	// Define the tag for the individual ID
	add_rewrite_tag( '%individual_id%', '([0-9]*)' );

	// Define the rules for each of the individuals
	add_rewrite_rule( '^individual/update/([0-9]*)', 'index.php?individual=update&individual_id=$matches[1]', 'top' );
	add_rewrite_rule( '^individual/delete/([0-9]*)', 'index.php?individual=delete&individual_id=$matches[1]', 'top' );

}
add_action( 'init', 'example_add_rewrite_rules' );
Copy after login

接下来,我们需要为每个人定义这些自定义函数,以便它们在调用时更新数据库中的正确记录。

在本例中,我们将定义两个函数 - 一个用于更新个人,另一个用于删除个人。以下代码还假设从浏览器提交的表单中将包含一些信息。

具体来说,它假设将发送个人 ID、名字、姓氏和其他信息,以便更新个人。

function example_process_individual( $input ) {

	if ( example_updating_user() ) {
		example_update_individual( $input );
	} else if ( 'true' == $input['delete_individual'] ) {
		example_delete_individual( $input['individual_id'] );
	}

}
if( ! is_admin() ) add_action( 'init', 'example_process_individual' );

function example_update_individual( $input ) {

	/* The incoming $input collection from an assumed form
	 * that will be used to update the user.
	 *
	 * It may include information such as the ID, the first name,
	 * last name, and so on.
	 *
	 * Upon success, use <code>wp_redirect</code> to go back to the homepage,  or reload
	 * the page to show an error.
	 */

}

function example_delete_individual( $individual_id ) {

	/* Use the incoming ID to locate the individual record and remove it
	 * from the database.
	 *
	 * Upon success, use <code>wp_redirect</code> to go back to the homepage,  or reload
	 * the page to show an error.
	 */

}

function example_updating_user() {
	return 0 == strpos( $_SERVER['REQUEST_URI'], '/individual/update' );
}

function example_deleting_user() {
	return 0 == strpos( $_SERVER['REQUEST_URI'], '/individual/delete' );
}
Copy after login

请注意,上面的第一个函数已挂接到 init 操作中,并且在用户未以管理员身份登录时触发。此外,还可以通过有条件地将其设置为仅在来自某个页面时加载来进一步增强此功能;然而,对于这个例子来说,它达到了它的目的。

接下来,阅读 UpdateDelete 函数的代码注释,了解它们应如何运行。

最后,请注意,最后两个函数是简单的帮助程序,旨在允许我们在初始挂钩函数中编写更清晰的代码。

有点不完整

我知道,这是一个不完整的示例,但对于一篇冗长的文章和一个复杂的主题,我的目标是尽我所能来展示 WordPress Rewrite API,讨论使用它的优点,并讨论如何使用它来创建更清晰的 URL 路由。

事实是,这仍然是一个具有挑战性的主题,并且最好通过实施来掌握。尽管如此,这是 WordPress 应用程序的另一个组件,使其可以作为 Web 应用程序开发的基础。


下一个

说了这么多,现在是时候讨论缓存的概念了。

当然,有很多可用于 WordPress 的缓存插件,但如果您是开发人员,您希望构建一定程度的本机缓存,并且您希望利用 WordPress API 来实现所以。如果是这种情况,熟悉可用的内容以及如何操作就很重要。

话虽如此,我们接下来将注意力转向 Transients API,以便我们可以自己处理一些本机缓存,并回顾这如何帮助第三方缓存机制使我们的应用程序更快。

The above is the detailed content of Explore WordPress features for web application development: Unlock URL rewriting capabilities. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template