如何在wordpress中创建短代码?

时间:2017-04-15 15:59:35

标签: php wordpress shortcode

我有以下代码,我希望它使用

显示实现内容
[insert_dos]*Content for dos here*[/insert_dos]

[insert_donts]*Content for dos here*[/insert_donts]

待办事项

此处的dos内容

唐' TS

此处的内容

我正在尝试使用

的代码
// Shortcode for dos
       function insert_dos_func( $atts,$content ) {
    extract( shortcode_atts( array(
        'content' => 'Hello World',
        ), $atts ) );

      return '<h2>DOs</h2>';
      return '<div>' . $content . '</div>';
    }
    add_shortcode( 'insert_dos', 'insert_dos_func' );



// Shortcode for don'ts
        function insert_donts_func( $atts ) {
          extract( shortcode_atts( array(
            'content' => 'Hello World',
            ), $atts ) );

          return "<h2>DON'Ts</h2>";
          return "<div>" . $content . "</div>";
        }
        add_shortcode( 'insert_donts', 'insert_donts_func' );

1 个答案:

答案 0 :(得分:1)

您要面对的第一个问题是在单个函数中使用多个return语句。第一次回归后的任何事情都不会被执行。

第二个问题是您传递内容的方式。您的属性数组中有一个名为content的元素。如果你在该数组上运行extract,它将覆盖短代码回调的$content参数。

function insert_dos_func( $atts, $content ) {

    /**
     * This is going to get attributes and set defaults.
     *
     * Example of a shortcode attribute:
     * [insert_dos my_attribute="testing"]
     *
     * In the code below, if my_attribute isn't set on the shortcode
     * it's going to default to Hello World. Extract will make it 
     * available as $my_attribute instead of $atts['my_attribute'].
     *
     * It's here purely as an example based on the code you originally
     * posted. $my_attribute isn't actually used in the output.
     */
    extract( shortcode_atts( array(
        'my_attribute' => 'Hello World',
    ), $atts ) );

    // All content is going to be appended to a string.
    $output = '';

    $output .= '<h2>DOs</h2>';
    $output .= '<div>' . $content . '</div>';

    // Once we've built our output string, we're going to return it.
    return $output;
}
add_shortcode( 'insert_dos', 'insert_dos_func' );