1

Good day,

I was wondering if can do a shortcode that gets all the fields in a row stored in a database, with the difference that I do not want to do many shortcodes for the speed of the site.

The row of the database with separate fields, as you will see in the image below.

Database fields

Or if there is another way to do it and it is better, you're welcome.

  • Could you explain what do you mean by “like an array or something like that”? – Krzysiek Dróżdż Mar 3 '19 at 6:03
  • Sorry, I'm wrong, I've been thinking many things with this problem – Sebastián Mar 3 '19 at 6:05
1

I’m not entirely sure if that’s what you wanted, but... Here’s the code that will register a shortcode, which will get given row and output all the fields of it:

function shortcode_db_row_cb( $atts ) {
    $atts = shortcode_atts( array(
        'id' => false,
    ), $atts, 'db_row' );

    global $wpdb;
    $row = $wpdb->get_row( $wpdb->prepare( "select * from {$wpdb->prefix}TABLE_NAME where id = %d", $atts['id'] ), ARRAY_A );
    $res = '';

    if ( $row ) {
        $res = '<table>';
        $res .= '<tr>';
        foreach ( $row as $k => $v ) $res .= '<th>' . esc_html($k) . '</th>';
        $res .= '</tr>';
        $res .= '<tr>';
        foreach ( $row as $k => $v ) $res .= '<to>' . esc_html($v) . '</td>';
        $res .= '</tr>';
        $res .= '</table>';
        return $res;
    }

    return 'no such row';
}
add_shortcode( 'db_row', 'shortcode_db_row_cb' );
|improve this answer|||||
  • Thanks! Can I request data from the row separately? Or is it necessary to create a new shortcode? – Sebastián Mar 3 '19 at 6:43
  • Sorry, but I can’t get what do you mean by that? Do you want to get only some of fields from that row? Do you want to get different rows? – Krzysiek Dróżdż Mar 3 '19 at 6:55
  • The first one, only some of fields from that row. Use one shortcode to get the id, another for name.. and so on. Hopefully only with just 1 shortcode to not slow down the site – Sebastián Mar 3 '19 at 7:00
  • Yes, you can pass parameters to shortcodes. I don't think a few shortcodes will make any difference to the speed of your site though. – Rup Mar 3 '19 at 8:02
  • Registering more shortcodes won’t affect the speed of site significantly... And yes, you can pass more params in there - here we pass only the ID, but you can pass field name also. – Krzysiek Dróżdż Mar 3 '19 at 8:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.