Search code examples
phpsqlwordpressshortcode

Wordpress Database query and Output as HTML list


I'm trying to get a PHP Code to work in order to make a Database query within a Wordpress database table. The results (all distinct values of one specific column) should be put out within an HTML list. I want to be able to place the output everywhere in my content, so it should be accessable via shortcode.

Here's what I got so far. This code does not produce any errors in wordpress or the console, but it also doesn't do the trick... Nothing appears at the desired place.

class my_Shortcode {

    var $echo;

    function __construct() {
        add_shortcode( 'my_plugin', array( $this, 'shortcode' ) );
    }    

    function shortcode( $atts ) {
        global $wpdb;

        $table = isset( $atts['table'] ) ? $atts['table'] : false;
        $column = isset( $atts['column'] ) ? $atts['column'] : false;
        $listDisplay = isset( $atts['listDisplay'] ) ? $atts['listDisplay'] : false;

        if ( $listDisplay == true ) {
            if ( false != $table && false != $column ) {
                $this->echo = "";
                $results = $wpdb->get_results(
                    prepare('SELECT DISTINCT ' . $column . ' FROM ' . $table)
                );
                $this->echo .= "<div class=\"list\"><ul>";

                foreach ($results as $result) {
                    $this->echo .= "<li>$result</li>\n"; 
                }
                $this->echo .= "</ul></div>";
                return $this->echo;
            }
        }
    }
}

I'm glad about any suggestions!


Solution

  • Do you want likve this?

    <?php
        echo do_shortcode("[my_plugin table='wp_posts' column=id]");
    ?>
    
    
    
    
    
    class my_Shortcode {
    
        var $echo;
    
        function __construct() {
        add_shortcode( 'my_plugin', array( $this, 'shortcode' ) );
        }    
    
        function shortcode( $atts ) {
        global $wpdb;
    
        $table = isset( $atts['table'] ) ? $atts['table'] : false;
        $column = isset( $atts['column'] ) ? $atts['column'] : false;
        $listDisplay = isset( $atts['listDisplay'] ) ? $atts['listDisplay'] : true;
    
        if ( $listDisplay == true ) {
            if ( false != $table && false != $column ) {
            $this->echo = "";
    
            $results = $wpdb->get_results("SELECT DISTINCT  $column  FROM  $table ",ARRAY_A);
    
    
            $this->echo .= "<div class=\"list\"><ul>";
    
            foreach ($results as  $key => $result) {
                $keys = array_keys( $result);                   
                $this->echo .= '<li>'.$result[ $keys[0] ].'</li>\n'; 
            }
            $this->echo .= "</ul></div>";
            return $this->echo;
            }
        }
        }
    }
    
    $test = new my_Shortcode();