user1048676 user1048676 - 1 month ago 5
PHP Question

How to use do_shortcode outside of a template

All,
I'm trying to use the do_shortcode function. I have the following jQuery to call a post function:

category = $("#past_vendor_category").val();
search_term = $("#past_vendor_name").val();

$.post("http://localhost/wordpress/wp-content/search_past_vendors.php", { category: category, search_term: search_term }, function(results){
$("#past_vendor_search_results").html(results);
});


Which then calls this PHP file:

<?php
global $shortcode_values, $theLayout;
include "config.php";
$category = mysql_real_escape_string($_POST['category']);
$search_term = mysql_real_escape_string($_POST['search_term']);

$qry = "Select wp_posts.ID, wp_posts.post_name, wp_posts.post_title, custom_vendor_info.city, custom_vendor_info.city
from wp_posts
join custom_vendor_info on wp_posts.ID=custom_vendor_info.post_id
join wp_term_relationships on wp_posts.ID=wp_term_relationships.object_id
where wp_posts.post_title like '%$search_term%' and wp_term_relationships.term_taxonomy_id='$category'";
$result = mysql_query($qry);
$resultrows = mysql_num_rows($result);
$x=0;
if($resultrows>0){
$show_results = '<br>';
while($resultset = mysql_fetch_array($result)){
if($x==0){
$show_results .= '<div class="vendor_search_result"><span class="vendor_search_result_name"><a href="'.$resultset['post_name'].'">'.$resultset['post_title'].'</a></span><span class"vendor_search_result_button">'.do_shortcode("[button]Text[/button]").'</span>';
}else{
$show_results .= '<div class="vendor_search_result"><span class="vendor_search_result_name"><a href="'.$resultset['post_name'].'">'.$resultset['post_title'].'</a></span><span class"vendor_search_result_button">'.do_shortcode("[button]Text[/button]").'</span>';
$x=0;
}
}
echo $show_results;
}else{
echo '<br>Sorry, there were no search results for "<b>'.$search_term.'</b>". Please try again!';
}
?>


This file is not inside a Wordpress page so I'm getting the error message:
Fatal error: Call to undefined function do_shortcode() in D:\My Documents\xampp\htdocs\wordpress\wp-content\search_past_vendors.php on line 19

Any idea how I can use the do_shortcode outside of a Wordpress page?

Thanks

Answer

The do_shortcode function depends on the global state of wordpress. As in your example code you don't load wordpress, it's not available.

I suggest you create yourself some plugin that offers an Ajax interface and that is then processed by the default wordpress Ajax backend.

See 5 tips for using AJAX in WordPress (original article archived) for a step-by-step description how you can bind your PHP functions to Ajax requests properly.