城市简码
WordPress are super handy, especially when handing off a WordPress-based website to a client. The alternative to using shortcodes is creating complicated templates, and even then, you cannot adequately replace what shortcodes can do. I recently needed to implement a new shortcode for the Mozilla Hacks blog and was happy to learn how simple the WordPress API makes creating new shortcodes! Let me show you how to create your own WordPress shortcodes!
WordPress 非常方便,尤其是在将基于WordPress的网站移交给客户端时。 使用简码的替代方法是创建复杂的模板,即使那样,您也无法充分替换简码可以做什么。 我最近需要为Mozilla Hacks博客实现新的简码,并很高兴了解WordPress API如何使创建新的简码变得如此简单! 让我向您展示如何创建自己的WordPress短代码!
First you start by creating a function within your theme's functions.php
file. The function should return a string which replaces the shortcode within the rendered content. Your function can accept an $args
argument which is a key=>value
array of parameters passed in.
首先,您需要在主题的functions.php
文件中创建一个函数。 该函数应返回一个字符串,该字符串将替换呈现内容中的短代码。 您的函数可以接受$args
参数,该参数是传入的参数的key=>value
数组。
function my_shortcode_routine($args) { // $args = array('key1' => 'value1', 'key2' => 'value2') $return = ''; // a bunch of logic and string-building here // return the result return $return;}
Remember that your function shouldn't echo
; a string must be returned.
记住你的函数不应echo
; 必须返回一个字符串。
After your function has been created, you can use WordPress' add_shortcode
function to register the shortcode. The shortcode name function name doesn't need to match the shortcode:
创建函数后,您可以使用WordPress的add_shortcode
函数注册该短代码。 简码名称函数名称不需要与简码匹配:
// Add a shortcode called 'shortcode_name' that runs the 'my_shortcode_routine' functionadd_shortcode('shortcode_name', 'my_shortcode_routine');
With the function created and the shortcode registered, now you can use said shortcode within your posts and pages:
创建函数并注册简码后,现在您可以在帖子和页面中使用所述简码了:
[shortcode_name key1="value1" key2="value2"]
The shortcode system is positively beautiful; it's of large value to both seasoned devs and trained clients, and a prime example of why WordPress is deep and flexible platform.
简码系统非常漂亮; 对于经验丰富的开发人员和训练有素的客户而言,它都具有巨大的价值,并且是WordPress为什么是深度而又灵活的平台的典型示例。
翻译自:
城市简码