Access WP custom REST Fields in custom route - php

I have created custom fields to display in WordPress rest api. I want the same data to be fetched into a custom route api. How it is possible?
That is, I have some custom rest fields in the path example.com/wp-json/wp/v2/posts/
have the following rest fields I need to show in the another route. ie at example.com/wp-json/mycustom/route/v2
How can I do it?
function list_subpages() {
$data = array();
$request = array();
$my_column = array();
global $wpdb;
$save_table = $wpdb->prefix.'saved_post';
$regid = $_REQUEST['save_key'] ;
$sql1 = "select postid FROM ".$save_table." WHERE regid='".$regid."';";
$result1 = $wpdb->get_results($sql1);
foreach ($result1 as $p)
{
$id[]=$p->postid;
}
$args = array(
'post__in' => $id,
'per_page' => $per_page,
);
$subpages = get_posts( $args );
if ( empty( $subpages ) ) {
return null;
}
foreach ($subpages as $p) {
$request[] = $data;
}
return new WP_REST_Response($request, 200);
}
add_action('rest_api_init', function () {
$namespace = 'savedpost/v2';
$base = 'user';
register_rest_route($namespace, '/' . $base, array(
'methods' => 'GET',
'callback' => 'list_subpages',
));
});

Related

WordPress wp-insert-post function creating arbitrary no-title pages

I am using the wp-insert post function to dynamically generate pages from a website I am working on. However, I have been getting these no title posts that increase every time I refresh the page along with the actual pages that are generated from my code.
I have tried solving this by adding a hook into my page creation process, however this does not seem to do anything. I was wondering how I can only create the pages I need without these no title posts appearing.
My code:
if( !class_exists("PageCreator")) {
class PageCreator
{
public function __construct()
{
add_action('init', array($this, 'AddThisPage'));
}
public function AddThisPage()
{
$dirName = "/zotpull/resources/temp/";
$filename = dirname(__DIR__, 2) . $dirName . "useData.txt";
$theFile = fopen($filename, "r");
$msg = fread($theFile, filesize($filename));
fclose($theFile);
$links = explode("\n", $msg);
foreach( array_slice($links, 0, count($links) -1) as $item ) {
$item = str_replace("/","-",$item);
$str2 = substr($item, 5);
$page = array(
'page_template' => 'datePage.php', //Sets the template for the page.
'post_title' => $str2, //The title of your post.
'post_status' => 'publish',
'post_type' => 'page'
);
if ( ! function_exists( 'post_exists' ) ) {
require_once( ABSPATH . 'wp-admin/includes/post.php' );
}
$page_exists = post_exists($page['post_title']);
if ($page_exists == 0) {
$insert = wp_insert_post($page);
}
}
}
}
}
Try to use wp_update_post after wp_insert_post. check the below code.
if( !class_exists("PageCreator")) {
class PageCreator{
public function __construct()
{
add_action('init', array($this, 'AddThisPage'));
}
public function AddThisPage()
{
$dirName = "/zotpull/resources/temp/";
$filename = dirname(__DIR__, 2) . $dirName . "useData.txt";
$theFile = fopen($filename, "r");
$msg = fread($theFile, filesize($filename));
fclose($theFile);
$links = explode("\n", $msg);
foreach( array_slice($links, 0, count($links) -1) as $item ) {
$item = str_replace("/","-",$item);
$str2 = substr($item, 5);
$page = array(
'page_template' => 'datePage.php', //Sets the template for the page.
'post_title' => $str2, //The title of your post.
'post_status' => 'publish',
'post_type' => 'page'
);
if ( ! function_exists( 'post_exists' ) ) {
require_once( ABSPATH . 'wp-admin/includes/post.php' );
}
$page_exists = post_exists($page['post_title']);
if ($page_exists == 0) {
$insert = wp_insert_post($page);
$my_post = array(
'ID' => $insert,
'post_title' => $str2
);
wp_update_post( $my_post );
}
}
}
}
}

Add Custom Endpoint in WordPress Rest Api

I want to add custom endpoint in WordPress Rest API.I am able to fetch the post id,title,content,slug,categories and featured_image through this code by creating simple plugin. I am obtained category id in the Code.I want the category name i tried to do this by get_cat_name But did not understand it. How can i get category name,author name and author profile image through custom endpoint. I am also a beginner in wordpress. I refer to the documentation but did not understand how to do it. Write it as in w_posts function for category name
$data[$i]['catname']= get_cat_name($data[$i]['categories']);
<?php
/** Plugin Name : Custom API
* Plugin URI : https://google.com
* Decription : Crushing It
* Version : 1.0
* Author: Shahryar
* Author URI: https://google.com
*/
/** Plugin Name: Custom API... */
function w_posts(){
$args = [
'numberposts'=> 99999,
'post_type' => 'post'
];
$posts = get_posts($args);
$data = [];
$i = 0;
foreach($posts as $post) {
$data[$i]['id'] = $post->ID;
$data[$i]['title'] = $post->post_title;
$data[$i]['content'] = $post->post_content;
$data[$i]['slug'] = $post->post_name;
$data[$i]['categories'] = $post->post_category;
$data[$i]['featured_image']['thumbnail'] = get_the_post_thumbnail_url($post->ID, 'thumbnail');
$data[$i]['featured_image']['medium'] = get_the_post_thumbnail_url($post->ID, 'medium');
$data[$i]['featured_image']['large'] = get_the_post_thumbnail_url($post->ID, 'large');
$i++;
}
return $data;
}
function my_awesome_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if ( empty( $posts ) ) {
return null;
}
return $posts[0]->post_title;
}
function my_awesome_function( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if ( empty( $posts ) ) {
return null;
}
return $posts[0]->post_title;
}
function w_post( $slug ) {
$args = [
'name' => $slug['slug'],
'post_type' => 'post'
];
$post = get_posts($args);
$data['id'] = $post[0]->ID;
$data['title'] = $post[0]->post_title;
$data['content'] = $post[0]->post_content;
$data['slug'] = $post[0]->post_name;
$data['categories'] = $post[0]->post_category;
$data['featured_image']['thumbnail'] = get_the_post_thumbnail_url($post[0]->ID, 'thumbnail');
$data['featured_image']['medium'] = get_the_post_thumbnail_url($post[0]->ID, 'medium');
$data['featured_image']['large'] = get_the_post_thumbnail_url($post[0]->ID, 'large');
return $data;
}
add_action('rest_api_init',function(){
register_rest_route('w/v1','posts',[
'methods'=> 'GET',
'callback'=>'w_posts',
]);
register_rest_route( 'w/v1', 'posts/(?P<slug>[a-zA-Z0-9-]+)', array(
'methods' => 'GET',
'callback' => 'w_post',
) );
});
You are getting category id then you can get category name using it' id like:
get_the_category_by_ID( $cat_ID )
To get the author name and image you can do as following:
$author_id=$post->post_author; //get author id
//get author image URL by author id
$author_img_url = the_author_meta( 'avatar' , $author_id );
//get author name by author id
the_author_meta( 'user_nicename' , $author_id );

WordPress, retrieving the ID of the user profile page currently being edited

I'm in the process of developing a WordPress plugin. When editing a user's profile page, I need to be able to retrieve the ID of that user (not the currently logged in user).
I'm using the Advanced Custom fields plugin, and using a load filter for the function in question.
add_filter( 'acf/load_field/name=funbotic_parents', 'funbotic_load_parents' );
function funbotic_load_parents( $field ) {
$args = array(
'role' => 'customer',
'orderby' => 'display_name',
'order' => 'ASC',
);
$parent_data_array = get_users( $args );
// Clear choices array in case it was previously set.
$field['choices'] = array();
foreach ( $parent_data_array as $parent ) {
$parent_ID = $parent->ID;
$parent_display_name = $parent->display_name;
$field['choices'][$parent_ID] = $parent_display_name;
}
$current_user = (int) $_GET['user_id'];
$previously_associated_parents = get_user_meta( $current_user_id, 'funbotic_parents' );
if ( empty( $previously_associated_parents ) || is_null( $previously_associated_parents ) ) {
update_user_meta( $current_user_id, 'funbotic_previously_associated_parents', $previously_associated_parents );
} else {
$new_meta = funbotic_clean_array( $previously_associated_parents );
update_user_meta( $current_user_id, 'funbotic_previously_associated_parents', $new_meta );
}
return $field;
}
The line $current_user = (int) $_GET['user_id']; is returning null. Is there a way to pull 'user_id' from the URL? It's not an ideal solution but at this point I'm starting to get desperate. The URL looks like this:
http://dev-funbotic.local/wp-admin/user-edit.php?user_id=115&wp_http_referer=%2Fwp-admin%2Fusers.php%3Fs%3Dtest%26action%3D-1%26new_role%26course_id%26group_id%26paged%3D1%26action2%3D-1%26new_role2
You can try getting the current url and breaking it down to query params like this:
$query = explode('&', $_SERVER['QUERY_STRING']);
$params = array();
if(!empty($query[0])){
foreach( $query as $param ){
list($name, $value) = explode('=', $param, 2);
$params[urldecode($name)][] = urldecode($value);
}
}
then you can access the user_id by $params['user_id'][0]

Wordpress REST API create custom endpoint that uses custom table

Is it possible to create a Custom endpoint that is connected to the same database but with a custom table? if yes, how?
for example :
wp_TempTable (Custom Table)
I want to access this with a custom endpoint... I have searched multiple forums and sites but no luck..
Yes it is possible. This does not use the Controller pattern recommended by Wordpress but gets the job done, where the job is to convert incoming json into a row in your custom table (here called restaurants).
function handle_post( WP_REST_Request $request ) {
global $wpdb;
$item = $request->get_json_params();
$fields = array();
$values = array();
foreach($item as $key => $val) {
array_push($fields, preg_replace("/[^A-Za-z0-9]/", '', $key));
array_push($values, $wpdb->prepare('%s', $val));
}
$fields = implode(", ", $fields);
$values = implode(", ", $values);
$query = "INSERT INTO `restaurants` ($fields) VALUES ($values)";
$list = $wpdb->get_results($query);
return $list;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'restos/v1', '/post', array(
'methods' => 'POST',
'callback' => 'handle_post',
'permission_callback' => function () {
return current_user_can( 'edit_others_posts' );
}
) );
} );

Wordpress csv import duplicate

I've used an adapted version of a csv import plugin for wordpress. It imports the csv to create and update posts. To update existing posts I've added an edit that finds the post id by title, then if it exists it overwrites, otherwise it creates a new post.
Problem is that it seems to not be very reliable! If I import the same csv several times it over-writes most of them but I get a few duplicates. Is there any way I can make this more reliable, or is there another way I can deal with duplicate posts?
main function for creating posts here
function create_post($data, $options) {
extract($options);
//edit 1 added here
global $wpdb;
//end
$data = array_merge($this->defaults, $data);
$type = $data['csv_post_type'] ? $data['csv_post_type'] : 'post';
$valid_type = (function_exists('post_type_exists') &&
post_type_exists($type)) || in_array($type, array('post', 'page'));
if (!$valid_type) {
$this->log['error']["type-{$type}"] = sprintf(
'Unknown post type "%s".', $type);
}
$new_post = array(
'post_title' => convert_chars($data['csv_post_title']),
'post_content' => wpautop(convert_chars($data['csv_post_post'])),
'post_status' => $opt_draft,
'post_type' => $type,
'post_date' => $this->parse_date($data['csv_post_date']),
'post_excerpt' => convert_chars($data['csv_post_excerpt']),
'post_name' => $data['csv_post_slug'],
'post_author' => $this->get_auth_id($data['csv_post_author']),
'tax_input' => $this->get_taxonomies($data),
'post_parent' => $data['csv_post_parent'],
);
// edit 2 here
$new_post['ID'] = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" . $data['csv_post_title'] . "'" );
// ends
// pages don't have tags or categories
if ('page' !== $type) {
$new_post['tags_input'] = $data['csv_post_tags'];
// Setup categories before inserting
$cats = $this->create_or_get_categories($data, $opt_cat);
$new_post['post_category'] = $cats['post'];
}
// edit 3
if(!empty($new_post['ID'])) {
$id = wp_update_post($new_post);
} else {
$id = wp_insert_post($new_post);
}
// ends
if ('page' !== $type && !$id) {
// cleanup new categories on failure
foreach ($cats['cleanup'] as $c) {
wp_delete_term($c, 'category');
}
}
return $id;
}
thanks
Fixed! I used the built in wordpress function, get_page_by_title . Here is the code I used to target the correct post.
if (!get_page_by_title( $bpp_title, 'OBJECT', 'publications')) {
$id = wp_insert_post($new_post);
} else {
$bpp_page = get_page_by_title( $bpp_title, 'OBJECT', 'publications');
$new_post['ID'] = $bpp_page->ID;
$id = wp_update_post($new_post);
}

Categories