Reputation: 11
I have custom function where I retrieve guid's attached to each post. Now I want to add this on WordPress API.
global $wpdb;
$post_id= $object['id'];
$sql = "SELECT post_content FROM wp_posts WHERE id = $post_id";
$results = $wpdb->get_results($sql);
foreach ($results as $result) {
$content = $result->post_content;
$needle = 'gallery_ids="';
$offset = strpos($content,$needle);
if($offset>=0){
$offset += strlen($needle);
$l = strpos($content,'"',$offset);
$l -= $offset;
$content = substr($content,$offset,$l);
$content = explode(",",$content);
function filterGuid($var) {return is_numeric($var);}
$content = array_filter($content,"filterGuid");
for ($x = 0; $x <= count($content) -1; $x++) {
$guids = "SELECT guid FROM wp_posts WHERE id IN ('$content[$x]')";
$gui_results = $wpdb->get_results($guids);
foreach ($gui_results as $result) {
echo $result->guid;
}
}
}
}
What changes should I make to add it? Thanks for the help!
Upvotes: 1
Views: 430
Reputation: 830
A few steps to help you out:
add_action( 'rest_api_init', 'register_function_name' );
function register_function_name() {
register_rest_route( 'endpoint_group', '/endpoint', array(
'methods' => 'POST', //Whatever Method you want
'callback' => 'callback_function' //Function to call
));
}
function callback_function(){
global $wpdb;
$post_id= $object['id']; //Change this to get the data from the api call ex: $post_id = $_POST['id']
$sql = "SELECT post_content FROM wp_posts WHERE id = $post_id";
$results = $wpdb->get_results($sql);
foreach ($results as $result) {
$content = $result->post_content;
$needle = 'gallery_ids="';
$offset = strpos($content,$needle);
if($offset>=0){
$offset += strlen($needle);
$l = strpos($content,'"',$offset);
$l -= $offset;
$content = substr($content,$offset,$l);
$content = explode(",",$content);
function filterGuid($var) {return is_numeric($var);}
$content = array_filter($content,"filterGuid");
for ($x = 0; $x <= count($content) -1; $x++) {
$guids = "SELECT guid FROM wp_posts WHERE id IN ('$content[$x]')";
$gui_results = $wpdb->get_results($guids);
foreach ($gui_results as $result) {
$results[] = $result->guid;
}
}
}
}
wp_send_json_success($results, 200);
}
Upvotes: 1