How do I connect to the database via [WordPress] to consult?

1

Well, I have a call jQuery Ajax on header.php of my theme that is entering a PHP file in the root of my Wordpress and returning me echo test. I need this file to query the banco de dados and return me some ID's .

How can I do this? What I have developed so far in relation to the PHP file is below but did not work. I think I'm not using the right way to connect to the database via WordPress .

<?php

// ... eu imagino que este include serve para 
// instaciar uma conexão com o banco de dados
require('./wp-blog-header.php');

if( isset($_POST['letra']) ){

    function retorna(){

        global $wpdb;

        // Recuperando o termo a ser filtrado no banco de dados
        $parametro = isset($_POST['letra']) ? $_POST['letra'] : null;

        // Recuperando os ID de todos os registros que respondem a pesquisa
        $pesquisas = $wpdb->get_results("SELECT ID FROM $wpdb->posts WHERE post_type = 'professores'"); 

        // Por enquanto imprimindo estes valores
        foreach ( $pesquisas as $pesquisa ){ 

            print_r($pesquisa->ID);

        }   
    }

    retorna();  
}

?>
  

Errors 404 and 500 appear randomly but the paths exist and the permissions are correct. When I remove everything from within the function and leave a echo it works.

    
asked by anonymous 29.07.2015 / 22:48

1 answer

2

To do wordpress queries first you have to give an include in the configuration files and db so:

define( 'BLOCK_LOAD', true );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-config.php' );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-includes/wp-db.php' );
$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);

Then you will use the variable $wpdb to make queries, for example:

$results = $wpdb->get_results( 'SELECT * FROM wp_options WHERE option_id = 1', OBJECT );

For more information, visit: link

    
30.07.2015 / 16:59