search
HomeBackend DevelopmentPHP TutorialDetailed explanation of the basic method of writing shortcode format tags in WordPress, _PHP tutorial

Detailed explanation of the basic method of writing shortcode format tags in WordPress,

WordPress shortcode is something similar to a forum tag, and the format is similar to replacing angle brackets with square brackets Html tag. Many people call short codes short codes, but the official translation should be short codes. Please correct them here.

The logic of shortcode development is relatively simple, mainly adding, deleting and judging, which will be fully introduced in this article.

Shortcode format

The format of shortcode is very flexible, it can be with attributes, without attributes, closed, unclosed, etc.:

[example]

[example]Content[/example]

[example attr="attribute" attr-hide="1"]Content[/example]

[example "property"]

Add shortcode

To add a shortcode, you need to use the add_shortcode() function, with two attributes, the first is the shortcode name, and the second is the callback function of the shortcode.

add_shortcode( $tag, $func );

For example, add a shortcode named test and call back the Bing_shortcode_test() function:

function Bing_shortcode_test( $attr, $content ){
  return 'Hello World!';
}
add_shortcode( 'test', 'Bing_shortcode_test' );

Add [test] to the article and "Hello World!" will be output.

As you can see from the above example, the callback function of the shortcode needs to receive two parameters. The first is all the attributes of the shortcode, stored in an array; the second is the content of the shortcode (the content in the closed shortcode).

Remove shortcode

The remove_shortcode() function can remove a shortcode. You only need to specify the name of the shortcode to remove it.

remove_shortcode( 'test' );

The remove_all_shortcodes() function is used to remove all shortcodes currently added.

remove_all_shortcodes();

Judge shortcode

Regarding judging shortcodes, there are two functions. The shortcode_exists() function judges whether shortcodes exist.

remove_all_shortcodes();
if( shortcode_exists( 'test' ) ) echo '简码 test 存在';//False
add_shortcode( 'test', 'Bing_shortcode_test' );
if( shortcode_exists( 'test' ) ) echo '简码 test 存在';//True

There is also a has_shortcode() function to determine whether a certain shortcode appears in the string.

$content = '测试测试测试测试测试测试测试测试';
if( has_shortcode( $content, 'test' ) ) echo '字符串中有 test 简码';//False
$content = '测试测试测试测[test]测试[/test]试测试测试测试测试';
if( has_shortcode( $content, 'test' ) ) echo '字符串中有 test 简码';//True

Execute shortcode

The do_shortcode() function is used to find the shortcode in the string and call the previously added callback function at the shortcode to execute the shortcode into the required content.

Hooks added by WordPress:

add_filter( 'the_content', 'do_shortcode', 11 );

Example:

function Bing_shortcode_test( $attr, $content ){
  return 'Hello World!';
}
add_shortcode( 'test', 'Bing_shortcode_test' );
$content = '测试测试测试测[test]试测试测试测试测试';
echo do_shortcode( $content );//测试测试测试测Hello World!试测试测试测试测试

Shortcode attribute

Shortcode supports attributes in various formats and accepts the first parameter of the shortcode callback function. If you want to set default values ​​for parameters, you can use the shortcode_atts() function:

function Bing_shortcode_test( $attr, $content ){
  extract( shortcode_atts( array(
    'url' => 'http://www.bgbk.org',
    'hide' => false,
    'text' => '点击隐藏 / 显示'
  ), $attr ) );
  $hide = $hide ? ' style="display:none;"' : '';
  return '<a href="' . $url . '"' . $hide . '>' . $text . '</a>';
}
add_shortcode( 'test', 'Bing_shortcode_test' );


The script is only loaded when shortcodes are used in the page
During the development process, we sometimes encounter this problem: the shortcode module needs to load JS or CSS scripts, and when the page does not use shortcodes, it will cause a waste of resources.

For example, the Google Maps plug-in below:


//添加简码
function Bing_add_google_map( $atts, $content ){
  //content...
}
add_shortcode( 'google_map', 'Bing_add_google_map');
 
//挂载脚本
function Bing_add_javascript(){
  wp_enqueue_script( 'map_scripts' );
}
add_action( 'wp_enqueue_scripts', 'Bing_add_javascript' );

The script needs to be loaded only when the [google_map] shortcode is used in the page. How to do this?

In fact, it is very simple. You only need to mount the script in the footer when the shortcode function is triggered.

//添加简码
function Bing_add_google_map( $atts, $content ){
  $GLOBALS['google_map_shortcode'] = true;
  return '地图的代码';
}
add_shortcode( 'google_map', 'Bing_add_google_map');
 
//挂载脚本
function Bing_add_javascript(){
  global $google_map_shortcode;
  if( isset( $google_map_shortcode ) && $google_map_shortcode ) wp_enqueue_script( 'map_scripts' );
}
add_action( 'wp_footer', 'Bing_add_javascript' );

Summary

Shortcode is a very powerful function. It is a good extension to the content of the article. If it is used well, it can make adding something quick and convenient.

The functions related to short codes are all in the wp-includes/shortcode.php file. Friends who are capable can read it to understand the principle.

Articles you may be interested in:

  • PHP code example for adding page number navigation to article list page in WordPress theme
  • Analysis of the role and basic usage of function hooks in WordPress
  • Enable the theme to support widgets and add plug-in enabling functions in WordPress

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1084559.htmlTechArticleDetails the basic method of writing shortcode format tags in WordPress. WordPress shortcode is something similar to forum tags , the format is similar to the Html tag with angle brackets replaced by square brackets. Jane...
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
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool