Custom API Wordpress Endpoint fails - wordpress

{"code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status":404}}
Im trying to determine whats wrong with my code. Ive written a custom api endpoint for wordpress but I get the above error while trying to access the url. My code is as follows:
$this->loader->add_action('rest_api_init', $plugin_public, 'create_api_webhook');
public function create_api_webhook() {
register_rest_route('learn2/v1', '/api/', array(
'methods' => 'GET',
'callback' => array($this, 'learn2_api_webhook')
));
}
public function learn2_api_webhook() {
global $wpdb;
$args = array('post_type' => 'sfwd-courses',
'post_status' => 'publish',
'order' => 'DESC',
'orderby' => 'ID',
);
$loop = new WP_Query($args);
$courses = array();
$lessons = array();
while ($loop->have_posts()) : $loop->the_post();
$mylessons = learndash_get_lesson_list($post->ID);
$lessons = array();
foreach ($mylessons as $lesson) {
$topics = array();
$mytopics = learndash_get_topic_list($lesson->ID, $post->ID);
foreach ($mytopics as $topic) {
$topics[] = array('id' => $topic->ID, 'title' => $topic->post_title);
}
$lessons[] = array('id' => $lesson->ID, 'title' => $lesson->post_title, 'topics' => $topics);
}
$courses[] = array('id' => $post->ID, 'title' => $post->post_title, 'lessons' => $lessons);
endwhile;
return json_encode($courses);
}
Im trying to access the url with:
http://localhost/community_staging/wp-json/learn2/v1/api/ but I get the above error.
Im running the latest wordpress

$this->loader->add_action('rest_api_init', $plugin_public, 'create_api_webhook');
$plugin_public wasn't pointing to the right class.

Related

Sending variable to search page

I`ve made this action:
add_action( 'init', 'advanced_search_query' );
function advanced_search_query( $query ) {
if ( isset($_GET['make']) && isset($_GET['model']) && isset($_GET['fuel']) ) {
$all_products = [];
$inner_cats = get_terms(['taxonomy' => 'product_cat','hide_empty' => false, 'parent' => $_GET['model']]);
foreach ($inner_cats as $cat) {
if ($_GET['fuel'] == 0)
$fuel_cat = get_terms(['taxonomy' => 'product_cat','hide_empty' => false, 'parent' => $cat->term_id, 'name' => 'Diesel']);
elseif ($_GET['fuel'] == 1)
$fuel_cat = get_terms(['taxonomy' => 'product_cat','hide_empty' => false, 'parent' => $cat->term_id, 'name' => 'Benzin']);
$args = array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'terms' => $fuel_cat[0]->term_id,
'operator' => 'IN',
)
)
);
$products = get_posts( $args );
if ($products) {
foreach ($products as $prd) {
$all_products[] = $prd;
}
}
}
}
}
Now what I am strugling with is sending the $all_products to my search page and loop them. Tried to redirect to the search page like wp_safe_recirect('domain.com?s=""') with empty s parameter and use the all_results there. Also tried to set the variable as global but again couldnt reach it.
Did you try the following?
if ($products) {
foreach ($products as $prd) {
$all_products[] = $prd;
?>
<script>window.location.href="domain.com?s=''"</script>
<?php
}
}

get_posts() does not return featured_image field on Wordpress custom endpoint

Trying to get only the needed data on a custom endpoint in Wordpress. To do so, I am using get_posts() function.
add_action('rest_api_init', function() {
register_rest_route('wl/v1', 'pages', [
'methods' => 'GET',
'callback' => 'wl_page',
]);
});
function wl_page() {
$args = [
'numberposts' => 99999,
'post_type' => 'page',
'post_parent' => 0,
];
$posts = get_posts($args);
$data = [];
$data['ID'] = $posts[0]->ID;
$data['title'] = $posts[0]->post_title;
$data['content'] = $posts[0]->post_content;
$data['featured_image'] = $posts[0]->featured_media;
return $data;
}
It should return the ID of the featured image, but get_posts() doesn't even return that field.
get_posts returns array of Post Objects which don't have featured_media property available. Use get_post_thumbnail_id() instead.
See updated code below:
add_action('rest_api_init', function() {
register_rest_route('wl/v1', 'pages', [
'methods' => 'GET',
'callback' => 'wl_page',
]);
});
function wl_page() {
$args = [
'numberposts' => 99999,
'post_type' => 'page',
'post_parent' => 0,
];
$posts = get_posts($args);
$data = [];
$data['ID'] = $posts[0]->ID;
$data['title'] = $posts[0]->post_title;
$data['content'] = $posts[0]->post_content;
$data['featured_image'] = get_post_thumbnail_id( $posts[0]->ID );
return $data;
}

Wordpress plugin only works on localhost (not working on remote host)

I have a plugin that is using OOP and it works perfectly on my localhost but not on my Bluehost server. It does not require any dependencies other than Composer autoload (i have uploaded composer generated vendor folder and json to remote plugin folder). I know the plugin is activating because it is generating empty database entries to my wp_options. However my add_menu_page function is not generating an options page in my Admin Dashboard.
I made sure that localhost and remote host are running same version of PHP (7.2+) and Wordpress (5.0.3)
I have already disabled all other plugins and tried uding in twentynineteen theme so I'm pretty confident it is not due to a conflict.
I have enabled debugging in wp_config and receive no errors.
I have no errors in my Bluehost error log
Below is a sample of my Dashboard.php....I'm only posting it because the lack of menu option is a symptom of my unknown error but i don't think its the cause
<?php
/**
* #package ICUPlugin
*/
namespace Inc\Pages;
use Inc\Api\SettingsApi;
use Inc\Base\BaseController;
use Inc\Api\Callbacks\AdminCallbacks;
use Inc\Api\Callbacks\ManagerCallbacks;
/**
*
*/
class Dashboard extends BaseController
{
public $settings;
public $callbacks;
public $callbacks_mgr;
public $pages = array();
//public $subpages = array();
public function register()
{
$this->settings = new SettingsApi();
$this->callbacks = new AdminCallbacks();
$this->callbacks_mgr = new ManagerCallbacks();
$this->setPages();
//$this->setSubpages();
$this->setSettings();
$this->setSections();
$this->setFields();
$this->settings->addPages( $this->pages )->withSubPage( 'Dashboard'
)->register();
}
public function setPages() {
$this->pages = array(
array(
'page_title' => 'ICU Plugin',
'menu_title' => 'ICU',
'capability' => 'manage_options',
'menu_slug' => 'icu_plugin',
'callback' => array( $this->callbacks, 'adminDashboard' ),
'icon_url' => 'dashicons-store',
'position' => 110
)
);
}
public function setSettings() {
$args = array(
array(
'option_group' => 'icu_plugin_settings',
'option_name' => 'icu_plugin',
'callback' => array( $this->callbacks_mgr, 'checkboxSanitize'
)
)
);
$this->settings->setSettings( $args );
}
public function setSections() {
$args = array(
array(
'id' => 'icu_admin_index',
'title' => 'Settings Manager',
'callback' => array( $this->callbacks_mgr,
'adminSectionManager' ),
'page' => 'icu_plugin'
)
);
$this->settings->setSections( $args );
}
public function setFields() {
$args = array();
foreach( $this->settingsManagers as $key => $value ) {
$args[] = array(
'id' => $key,
'title' => $value,
'callback' => array( $this->callbacks_mgr, 'checkboxField' ),
'page' => 'icu_plugin',
'section' => 'icu_admin_index',
'args' => array(
'option_name' => 'icu_plugin',
'label_for' => $key,
'class' => 'ui-toggle'
)
);
}
$this->settings->setFields( $args );
}
}

get custom fieds in rest API (meta_key)

I have this function to for my custom fields to save in WP data base (this is working and saving):
function notifyem_save_post() {
if(empty($_POST)) return; //why is prefix_teammembers_save_post triggered by add new?
global $post;
update_post_meta($post->ID, "country", $_POST["country"]);
update_post_meta($post->ID, "region", $_POST["region"]);
update_post_meta($post->ID, "time", $_POST["time"]);
update_post_meta($post->ID, "activity", $_POST["activity"]);
}
I want to display them from REST API but only TITLE is showing:
[{"title":"john"},{"title":"xxx"},{"title":"11"}]
This is my code for my REST API GET
function notifyem_rest_get() {
$subscriptions = new WP_Query(array(
'post_type' => 'notifyem'
));
$subscriptionResults = array();
register_rest_route('notifyemAPI/v1', '/subscription', array(
'methods' => WP_REST_SERVER::READABLE,
'callback' => array($this, 'getSubscription')
));
}
function getSubscription() {
$subscriptions = new WP_Query(array(
'post_type' => 'notifyem',
'meta_key' => 'country'
));
$subscriptionResults = array();
while($subscriptions->have_posts()) {
$subscriptions->the_post();
array_push($subscriptionResults, array(
'region' => get_field('regi'),
'country' => get_field('country'),
'activity' => get_field('activity'),
'time' => get_field('time')
));
}
return $subscriptionResults;
}
The screenshow below are the fields inserted to my custom post type.
Any ideas how to get the custom fields I created in my REST API?
Try this code
function getSubscription() {
$subscriptions = new WP_Query(array(
'post_type' => 'notifyem',
'meta_key' => 'country'
));
$subscriptionResults = array();
while($subscriptions->have_posts()) {
$subscriptions->the_post();
array_push($subscriptionResults, array(
'region' => get_post_meta(the_ID(), "region", true),
'country' =>get_post_meta(the_ID(), "country", true),
'activity' => get_post_meta(the_ID(), "activity", true),
'time' => get_post_meta(the_ID(), "time", true)
));
}
return $subscriptionResults;
}

How to hit the url in WordPress rest_api_init

I have set up the API end points in WordPress in theme functions.php.
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
'args' => array(
'id' => array(
'validate_callback' => function($param, $request, $key) {
return is_numeric( $param );
}
),
),
));
});
And the callback function is like:
function my_awesome_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if ( empty( $posts ) ) {
return new WP_Error( 'awesome_no_author', 'Invalid author', array( 'status' => 404 ) );
}
return $posts[0]->post_title;
}
I want to know what will be the url for this API and how can I hit that url?
Please help me out. I know this is simple thing but couldn't figure it out.

Resources