WordPress: creare uno shortcode per le tabelle di dati

WordPress: creare uno shortcode per le tabelle di dati

In WordPress è semplice creare uno shortcode per le tabelle di dati.

La soluzione è la seguente:


function my_datatable_shortcode( $atts, $content = null ) {
    $a = shortcode_atts( array(
        'thead' => '',
        'tbody' => '',
    ), $atts );

    $head = explode( ',', $atts['thead'] );
    $body = explode( '|', $atts['tbody'] );

    $output = '<table>';
    $output .= '<thead>';
    $output .= '<tr>';
    
    foreach( $head as $th ) {
        $output .= '<th>' . $th . '</th>';
    }

    $output .= '</tr>';
    $output .= '</thead>';

    $output .= '<tbody>';

    foreach( $body as $tr ) {
        $output .= '<tr>';

        $tds = explode( ',', $tr );

        foreach( $tds as $td ) {
            $output .= '<td>' . $td . '</td>';
        }

        $output .= '</tr>';
    }

    $output .= '</tbody>';

    $output = '</table>';

    return $output;
}

add_shortcode( 'mydatatable', 'my_datatable_shortcode' );

Esempio d'uso:


[mydatatable thead="A,B,C" tbody="1,2,3|4,5,6|7,8,9"]

Torna su