下面的解决方案将解析传递给短代码的逗号分隔值type
参数我们还将去掉值周围的空白,这是一种可用性改进(请参见下面代码后面的示例2)。
add_shortcode( \'related\', \'wpse_related\' );
function wpse_related( $atts, $content = \'\' ) {
// User provided values are stored in $atts.
// Default values are passed to shortcode_atts() below.
// Merged values are stored in the $a array.
$a = shortcode_atts( [
\'type\' => false,
], $atts );
$output = \'\';
if ( $a[\'type\'] ) {
// Parse type into an array. Whitespace will be stripped.
$a[\'type\'] = array_map( \'trim\', str_getcsv( $a[\'type\'], \',\' ) );
}
// Debugging: Display the type parameter as a formatted array.
$output .= \'<pre>\' . print_r( $a[\'type\'], true ) . \'</pre>\';
return $output;
}
Example 1:
[related type="2,3,4,5,6"]
Output:
Array
(
[0] => 2
[1] => 3
[2] => 4
[3] => 5
[4] => 6
)
Example 2:
[related type="8, 6, 7,5,30, 9"]
Output:
Array
(
[0] => 8
[1] => 6
[2] => 7
[3] => 5
[4] => 30
[5] => 9
)