sitespecificplugin

Create a Simple Plugin in WordPress – 5 – How to fetch data using wp_Query class

We can run a simple static query and run that query as we did in first part while we activation hook but to fetch the data from the table we use standard wp_Query class.

Check my github repo to download the plugin files.

We create a new short-code to display posts here.

First we create an object of wp_Query class. We pass arguments as array here. WordPress will run that query and give the result back. We need to check if we have posts in output by method have_posts()

global $wpdb, $table_prefix;

$args = array(
        's' => 'example',
        'post_type' => 'post',
        'order' => 'ASC',
        'tag' => 'new',
        'tax_query' => array(
            'relation' => 'OR',
            array(
                'taxonomy' => 'category',
                'field' => 'slug',
                'terms' => 'flat',
            ),
            array(
                'taxonomy' => 'category',
                'field' => 'slug',
                'terms' => 'plot',
            )
        )
    );

$the_query = new WP_Query($args);

if ($the_query->have_posts()){
// do a while loop to get each post data
}

Default WordPress handbook has all methods & arguments data described in detail here.

use below code into your plugin file and create a short-code into your page, it will create a list of post data.

function filter_posts_fun()
{
    global $wpdb, $table_prefix;

    $args = array(
        's' => 'example',
        'post_type' => 'post',
        'order' => 'ASC',
        'tag' => 'new',
        'tax_query' => array(
            'relation' => 'OR',
            array(
                'taxonomy' => 'category',
                'field' => 'slug',
                'terms' => 'flat',
            ),
            array(
                'taxonomy' => 'category',
                'field' => 'slug',
                'terms' => 'plot',
            )
        )
    );
    $the_query = new WP_Query($args);
    ob_start();
    if ($the_query->have_posts()) :
        echo "<ul>";
        while ($the_query->have_posts()) {
            $the_query->the_post();
            echo "<li>" . get_the_title(), get_the_content() . "</li>";
        }
        echo '</ul>';
    endif;
    $html = ob_get_clean();
    return $html;
}
add_shortcode('filter-posts', 'filter_posts_fun');

These are the helpful videos to understand this idea.