search
HomeBackend DevelopmentPHP TutorialDetailed explanation of the shortcode function in WordPress, wordpressshortcode_PHP tutorial

Detailed explanation of the use of shortcode shortcode function in WordPress, wordpressshortcode

WordPress has added a shortcode (short code) API starting from version 2.5, similar to BBCode on BBS. Shortcode can also easily add functions to articles or pages, and shortcode is more flexible and powerful than BBCode. Next, Kayo will introduce shortcode to you.

1. Shortcode Introduction
Shortcode allows developers to generate content by creating macro content in the form of functions. Perhaps this concept seems a bit vague, but in fact it is a very simple and practical function, as long as you can write basic PHP functions, that is Shortcode can be used. The following will use practical examples to illustrate the use of shortcode.

2.shortcode form
Shortcode supports closed tags and self-closing (automatically closed) tags, and supports the use of parameters within tags. As for the specific form of shortcode, it depends on how the developer writes the shortcode.

[myshortcode]Some Content[/myshortcode] // 封闭标签
[myshortcode] // 自闭标签
[myshortcode title="example"] // 带有一个参数的自闭标签
[myshortcode]<p><a href="#"><span>内容</span></a></p>[/myshortcode] // 标签内可以填写文本或 HTML
[myshortcode]Content [myshortcodesecond] more content[/myshortcodesecond] // 也可以嵌套使用标签

Three.shortcode examples
Before using shortcode, you must first define shortcode in the theme’s functions.php file, for example:

function myshortcode_function($atts, $content = null){ // $atts 代表了 shortcode 的各个参数,$content 为标签内的内容
 
 extract(shortcode_atts(array( // 使用 extract 函数解析标签内的参数
 "title" => '标题' // 给参数赋默认值,下面直接调用 $ 加上参数名输出参数值
 ), $atts));
 // 返回内容
 return '<div class="myshortcode">
    <h3 id="title">'. $title .'</h3>
    <p>
     '. $content .'
    </p>
   </div>';
}
 
add_shortcode("msc", "myshortcode_function"); // 注册该 shortcode,以后使用 [msc] 标签调用该 shortcode

Add the above code to functions.php, and a simple shortcode will be created. We can call the shortcode through the [msc][/msc] tag, such as:

[msc title="欢迎"]这是独立博客 Kayo's Melody ,欢迎来到本博客[/msc]

Enter the above call in the article or page content, and you can output a welcome statement at the corresponding location. Define the corresponding CSS in style.css to give the short code a style.

Kayo briefly introduced the shortcode function of WordPress, mainly introducing the main concepts and usage of shortcode. In this article, Kayo will introduce the more important APIs in shortcode in more detail, hoping to help you develop more complex shortcodes.

4. Function add_shortcode

This function is used to register a shortcode. It has two parameters: the shortcode name and the shortcode processing function name. Quoting the above example:

function myshortcode_function($atts, $content = null){ // $atts 代表了 shortcode 的各个参数,$content 为标签内的内容
 
 extract(shortcode_atts(array( // 使用 extract 函数解析标签内的参数
 "title" => '标题' // 给参数赋默认值,下面直接调用 $ 加上参数名输出参数值
 ), $atts));
 // 返回内容
 return '<div class="myshortcode">
    <h3 id="title">'. $title .'</h3>
    <p>
     '. $content .'
    </p>
   </div>';
}
 
add_shortcode("msc", "myshortcode_function"); // 注册该 shortcode,以后使用 [msc] 标签调用该 shortcode

msc is the shortcode name. You can directly use the [msc][/msc] tag to call the shortcode when writing articles or pages in the future, and "myshortcode_function" is the name of the shortcode processing function in the example. The following focuses on analyzing the short code processing function.

5. Short code processing function

The shortcode processing function is the core of a shortcode. The shortcode processing function is similar to Flickr (WordPress filter). They all accept specific parameters and return certain results. The shortcode processor accepts two parameters, $attr and $content. $attr represents the various attribute parameters of shortcode, which is essentially an associative array, and $content represents the content in the shortcode tag.

As in the above example, if a call is made within the article, a welcome statement will be output:

[msc title="Welcome"]This is an independent blog Kayo's Melody, welcome to this blog[/msc]
When the article is displayed, WordPress will register all shortcodes, such as [msc] above. If there are attribute parameters and content in the shortcode, WordPress will separate and parse them, and then pass them to the shortcode processing function of the shortcode. After processing The result output by the processing function is displayed in the article instead of the original content of the shortcode.

At this time, the attribute parameters will be parsed and the associative array will be passed to $attr. For example, in the above example, the value of $attr is an associative array as follows:

array( 'title' => '欢迎')

When outputting results, you can directly use the form of $parameter name to output. In the case of the example, the attribute value is output as $title.

6.shortcode_atts

shortcode_atts is a very practical function that can set default values ​​for the attribute parameters you need and delete some unnecessary parameters.

shortcode_atts() contains two parameters $defaults_array and $atts. $attr is the attribute parameter collection. $defaults_array represents the default value of the attribute that needs to be set. For example:

$result = shortcode_atts( array(
 'title' => '新标题',
 'description' => '描述内容'
), $atts );
$attr 依然为

array( 'title' => '欢迎')

The result of $result is

array( 'title' => '新标题', 'description' => '描述标题')

'title' Since there are different values ​​in $defaults_array, 'title' is updated based on this new value, and the value of 'description' is also added. It is worth noting that shortcode_atts() will filter attributes that are not in $defaults_array. If there is an 'ohter' attribute in $attr, then the result of $result will still be the above result, because there is no 'other' in $defaults_array this property. Of course, the value mentioned here is only the default value of the attribute, and the actual output value is still the value filled in when shortcode is called.

7. Further parse attributes and set attribute default values

The

extract() function is used to further parse attributes and set attribute default values. One of its functions is to assign each attribute parameter value to a variable in the form of "$parameter name" and save it (such as $title in the example). It is easy to call. Use this function together with shortcode_atts() to output the results safely. For the specific use of this point, please refer to the example of the first point of this article "1. Function add_shortcode".

In addition, uppercase letters in attribute names will be converted to lowercase letters before being passed to the processing function, so it is recommended to use lowercase letters directly when writing attribute names.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1127865.htmlTechArticleDetailed explanation of the shortcode shortcode function in WordPress. WordPressshortcode WordPress has added a shortcode (short code) starting from version 2.5. Code) API, similar to BBCode on BBS,...
Statement
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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software