I would like writing custom queries in WordPress in separate file php.
my class :
<?php
require('../../../wp-blog-header.php');
class DB_Functions {
private $db;
//put your code here
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
//$this->db = new DB_Connect();
// $this->db->connect();
}
// destructor
function __destruct() {
}
//------------------------------------------------
function test(){
global $wpdb;
$q = "SELECT
wp_posts.ID as ID
FROM
wp_posts
WHERE 1 = 1
AND wp_posts.post_title LIKE '%s%'
AND wp_posts.post_type = 'post'
AND ((wp_posts.post_status = 'publish'))
ORDER BY wp_posts.post_date DESC
LIMIT 0, 5 ";
$arr = $wpdb->get_results($q);
foreach($arr as $a ){
echo $a['ID'];
}
}
}
?>
But test
function does not return(echo) anything.
Where is my wrong ?
updated
returning of var_dump
of $arr
:
> array(5) { [0]=> object(stdClass)#5354 (1) { ["ID"]=> string(4) "6533"
> } [1]=> object(stdClass)#5353 (1) { ["ID"]=> string(4) "5838" } [2]=>
> object(stdClass)#5352 (1) { ["ID"]=> string(4) "5786" } [3]=>
> object(stdClass)#5351 (1) { ["ID"]=> string(4) "5282" } [4]=>
> object(stdClass)#5350 (1) { ["ID"]=> string(4) "5230" } }
solved:
foreach($arr as $a ){
echo $a->ID;
}
Try with following code :
what you need to get wordpress configuration and database object is
wp-load.php
. so include this file inside your class and then you can use$wpdb
object like this