1

Goal: Create a page template that queries that database based on page title. This allows for "dynamic" pages based off of the title.

I've got the page template set up and working when I hard code the id, when I try and use the_title_attribute() it's not working. This is what I'm attempting.

$id = the_title_attribute();
$sql = "SELECT * FROM <databasename>.<tablename> WHERE name = '". $id."'";
$results = $wpdb->get_results($sql, OBJECT);

The issue with this is that the_title_attribtue() doesn't populate in time for my query because it's populating later for the page to be rendered. So I'm trying to figure out how to pull page title so I can use it in SQL select statements to generate content for my page.

Any help is appreciated.

  • 2
    Why not use get_the_title() with $wpdb->prepare()? – Howdy_McGee Nov 27 '17 at 5:11
  • @Howdy_McGee I attempted to use prepare based on examples I saw but the same result happens, at the time of execution it returns blank. $sql = $wpdb->prepare("SELECT * FROM <databasename>.<tablename> WHERE name = '%d'", get_the_title()); – Matt Nov 27 '17 at 6:07
  • 1
    Have you turned on debugging? And %d looks for a decimal or number value, you need to use %s. – Howdy_McGee Nov 27 '17 at 15:24
  • @Howdy_McGee Thanks, updating the code to use '%s' along with the prepare statement provided the correct solution. If you would like to answer the question I will mark your answer as correct. – Matt Nov 28 '17 at 2:20
1

Answer provided by @Howdy_McGee who commented on the question. Using the prepare statement allowed the results to be pulled at the correct time and using %s is for strings and %d would be for a decimal or number value.

$sql = $wpdb->prepare("SELECT * FROM <databaseName>.<tableName> WHERE name = '%s'", get_the_title());
$results = $wpdb->get_results($sql, OBJECT);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.