I have a custom table 'wp-products' in WordPress with the following fields

id (primary key)  e.g 1
make              e.g. ford
model             e.g. mustang
price             e.g. 17500.00

id (primary key)  e.g 2
make              e.g. dodge
model             e.g. pheonix
price             e.g. 77500.00

what I want to do is create a shortcode e.g. [product_price id=2] that returns the price value associated with id number 2 in this table e.g. 77500.00. I have tried several ways and ended up with this (below)
I put this code in functions.php

function product_price_func( $atts ) {
    global $wpdb;
    $output="";
    $product_id = '';

    $atts = shortcode_atts(
    array(
      'id' => 'no id found',
    ), $atts, 'product_price' );

    $product_id = $atts['id'];


    $product_price = $wpdb->get_results("SELECT price FROM wp-products WHERE id={$product_id}", ARRAY_A);

    foreach ( $product_price as $the_price ) 
    {   
      $output = $the_price->price;
    }
    return "Product Price: $" . $output;
}
add_shortcode( 'product_price', 'product_price_func' );

However, this returns an empty result. I have checked that it passes id correctly but cannot get the query to return the value associated with id=2.

1 Answer
1

I have worked it out and here are the steps to what I did to get it working

  1. created a custom table in the wordpress database (called it wp-products)
  2. this table had the following fields: id, make, model, price
  3. Created a shortcode to retrieve the price. Shortcode looks like this [product_price id=2] where id=2 is the price value for item 2 in the table.
  4. wrote the shortcode function for this and put it in functions.php in my themes directory.
  5. Modified my original code by
  • adding $table_name = $wpdb->prefix . ‘products’;
  • Changed the query to: $product_price = $wpdb->get_results(“SELECT price FROM ” . $table_name .” WHERE id={$product_id}”, ARRAY_A);
  • changed the foreach statement to $output = $the_price[‘price’];
  1. added the shortcode into the page location where I wanted to display the code.

Here is the code that works, I hope it helps

function product_price_func( $atts ) {
    global $wpdb;

$table_name = $wpdb->prefix . 'products';

$atts = shortcode_atts(
array(
  'id' => 'no id found',
), $atts, 'product_price' );

$product_id = $atts['id'];

$product_price = $wpdb->get_results("SELECT price FROM " . $table_name ." WHERE id={$product_id}", ARRAY_A);

foreach ( $product_price as $the_price ) 
  { 
    $output = $the_price['price'];
  }

return "Product Price: $" . $output;

}
add_shortcode( 'product_price', 'product_price_func' );

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *