How do I connect to the database via [Wordpress] to query?

Asked

Viewed 3,169 times

1

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

How can I do that? What I’ve developed so far regarding the archive PHP is below but it didn’t work. I guess 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();  
}

?>

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

  • Answered ... If you are interested in doing a search in Wordpress and still use an Ajax request for this follows this path there that you get there: http://pastebin.com/P65c3khd

1 answer

2


To make queries in wordpress first you have to give a 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 the queries, example:

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

For more information visit: https://codex.wordpress.org/Class_Reference/wpdb

  • You can evaluate and answer this question in the American stackoverflow: http://wordpress.stackexchange.com/questions/196143/how-to-solve-this-script-problem-in-theme-directory

Browser other questions tagged

You are not signed in. Login or sign up in order to post.