Add Custom Endpoint in WordPress Rest Api - php

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 );

Related

Taxonomy ID by Post ID in custom endpoint

I making custom endpoint for my custom post type. The one thing is the taxonomy ID. I need to get taxonomy ID by post ID. get_terms( 'gallery_tax', $post->ID ) gives me array with all taxonomy object
function wl_posts() {
$args = [
'numberposts' => 9999,
'post_type' => 'gallery',
];
$posts = get_posts($args);
$data = [];
$i = 0;
foreach ($posts as $post) {
$data[$i]['id'] = $post->ID;
$data[$i]['fimg_url'] = get_the_post_thumbnail_url($post->ID, 'large');
$data[$i]['proizvoditel'] = get_field('proizvoditel', $post->ID);
$data[$i]['tip'] = get_field('tip', $post->ID);
$data[$i]['razmer'] = get_field('razmer', $post->ID);
$data[$i]['forma'] = get_field('forma', $post->ID);
$data[$i]['rost'] = get_field('rost', $post->ID);
$data[$i]['ves'] = get_field('ves', $post->ID);
$data[$i]['ohvat'] = get_field('ohvat', $post->ID);
$data[$i]['vozrast'] = get_field('vozrast', $post->ID);
$data[$i]['galereya'] = get_field('galereya', $post->ID);
$data[$i]['taxonomy'] = get_terms( 'gallery_tax', $post->ID );
$i++;
}
return $data;
}
add_action('rest_api_init', function() {
register_rest_route('wl/v1', 'gallery', [
'methods' => 'GET',
'callback' => 'wl_posts',
]);
});
Using get_terms('gallery_tax') will give you all the terms in a taxonomy.
https://developer.wordpress.org/reference/functions/get_terms
You get all the existing terms in your taxonomy. So this is why you get the result.
Using get_the_terms($post->ID, 'gallery_tax') will give you all taxonomy terms attached to the post.
https://developer.wordpress.org/reference/functions/get_the_terms/
You get all the terms that have been assigned to your post.
If you want to display the name of the taxonomy itself and not display the terms associated with the post, you can first get all the names of the taxonomies outside of your post loop and then get the taxonomy name inside of your foreach:
...
$data = [];
$i = 0;
$taxnames = get_taxonomies('','names');
foreach ($posts as $post) {
...
$data[$i]['taxonomy'] = wp_get_post_terms($post->ID, $taxnames, array("fields" => "names"));
$i++;
}
...
https://developer.wordpress.org/reference/functions/get_taxonomies/

Wordpress find category of custom post connected to custom post

Below is my working code to change a custom text field in every post of type lp_lesson to some text. Each one of these lp_lessons are assigned a specific post (lp_course).
My question is how do I figure out which lesson is connected to which course? I have a space in my phpAdmin title wp_learnpress_section_items that have a section_id and an item_id but I don't know how to access these as I have tried: $field_value = get_post_meta( $post->ID, 'section_id', 1);
The section_id references an array in my phpAdmin of wp_learnpress_sections and I would love to do this:
get the item_id which is equivalent to the post's ID. Then get the section_id associated with that item_id. Then get the section_course_id associated with that section_id. I have the logic down - I just don't know how to access these variables or items. I am guessing my $field_value is not the correct way to access these items.
add_action( 'wp_enqueue_scripts', 'win_9388244_format_lp_lesson' );
function win_9388244_format_lp_lesson() {
//Get post type of lp_lesson
$args = array(
'post_type' => 'lp_lesson',
'numberposts' => 99999
);
$posts = get_posts($args);
foreach($posts as $post) {
//if category == Test
update_post_meta( $post->ID, 'wpk_icon_text', 'Test' );
}
}
Edit: I have found that $post->ID gives me the post's ID, but not the rest of the variables.
For anyone who wants to do something similar I got it to work.
function win_9388244_format_lp_lesson() {
//Get post type of lp_lesson
$args = array(
'post_type' => 'lp_lesson',
'numberposts' => 99999
);
$posts = get_posts($args);
global $wpdb;
$sections = $wpdb->get_results( "SELECT section_item_id, section_id, item_id FROM wp_learnpress_section_items", ARRAY_A );
$items = $wpdb->get_results( "SELECT section_course_id, section_id FROM wp_learnpress_sections", ARRAY_A );
foreach($posts as $post) {
$lesson_id = $post->ID;
foreach($sections as $section) {
if($section['item_id'] == $lesson_id) {
$currentSection = $section['section_id'];
foreach($items as $item) {
if ($item['section_id'] == $currentSection) {
$course_code = $item['section_course_id'];
if ($course_code == 6177){
update_post_meta( $post->ID, 'wpk_icon_text', 'Time & Labor' );
}
else{
update_post_meta( $post->ID, 'wpk_icon_text', 'Lesson' );
}
}
}
}
}
}
}

Access WP custom REST Fields in custom route

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',
));
});

How to get post author name in WordPress?

In WordPress I need to fetch name of author who created post using author_id.
How can I find author_name ?
You can use get_the_author_meta(), to get author data.
echo get_the_author_meta('display_name', $author_id);
Hope this helps!
This should work like charm
<?php echo get_the_author(); ?>
For more detailed information.
https://codex.wordpress.org/Function_Reference/get_the_author
Use below code in single.php or the relevant page you want author name
<?php get_the_author_meta( 'display_name', $author_id ); ?>
When used in the WordPress Custom REST API endpoint you can do it like this:
function customrestapiplugin_getpost( $slug ) {
$args = [
'name' => $slug['slug'],
'post_type' => 'post'
];
$post = get_posts($args);
$data[$i]['id'] = $post[0]->ID;
$data['title'] = $post[0]->post_title;
$data['content'] = $post[0]->post_content;
$data['excerpt'] = $post[0]->post_excerpt;
$data['slug'] = $post[0]->post_name;
$data['date'] = $post[0]->post_date;
$data['link'] = get_permalink($post[0]->ID);
$data['author'] = get_the_author_meta('display_name', $post[0]->post_author);
$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 This code in single-post.php
<?php echo get_the_author(); ?>
I hope this will work !!
For those who are looking for a seamless solution on how to get an author of a post in WordPress, this is another lightweight method.
global $wpdb;
$post_id = 12; // your post id
$post_author_id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT post_author FROM {$wpdb->posts} WHERE ID = %d ", $post_id ) );
$author = new WP_User( $post_author_id );
$display_name = $author->display_name;
$avartar = get_avatar( $post_author_id, 30 ); // get_avatar( userid, size )
$author_url = get_author_posts_url( $post_author_id );

Wordpress: Contact form 7 select form getting array from custom post type

I'm setting up a site where a friend of mine can create new color pattern for her shop, but I would like to link it to a contact order form.
Currently, she has to create them both in the custom fields I set up AND in the contact form.
example: She create the color red for people to choose, but then she has to type 'red' in the select tag of contact form 7. "farve" = "color" (in danish) ;)
<div class="form-group">
<label>Color</label>
[select* menu-farve class:form-control "red" "blue"]
Now I have the custom post type slug called. "color", but how do I create an array that I can impliment into the form? and how to I get it into the form?
I have an array to display the color name from my custom post type if that helps:
<?php
$args = array( 'post_type' => 'color' );
$posts = get_posts( $args );
foreach ( $posts as $post ) :
$image = get_field('color_image', $post->ID);
setup_postdata( $post );
if ( get_field( 'sold' ) ): ; else: ?>
<div class="col-md-3">
<img class="img-responsive" src=" <?php echo $image['url'] ?> ">
<h2 class="">
<?php the_title(); ?>
</h2>
</div>
<?php endif ?>
<?php endforeach;
wp_reset_postdata(); ?>
There are several ways to accomplish dynamically generating Contact Form 7 selects.
Option 1: PHP
A great solution found both on the WordPress StackExchange and a blog by Lee Willis with the following being from the StackExchange as follows:
/** Dynamic List for Contact Form 7 **/
/** Usage: [select name term:taxonomy_name] **/
function dynamic_select_list($tag, $unused){
$options = (array)$tag['options'];
foreach ($options as $option)
if (preg_match('%^term:([-0-9a-zA-Z_]+)$%', $option, $matches))
$term = $matches[1];
//check if post_type is set
if(!isset($term))
return $tag;
$taxonomy = get_terms($term, array('hide_empty' => 0));
if (!$taxonomy)
return $tag;
foreach ($taxonomy as $cat) {
$tag['raw_values'][] = $cat->name;
$tag['values'][] = $cat->name;
$tag['labels'][] = $cat->name;
}
$tag['raw_values'][] = 'Other';
$tag['values'][] = 'Other';
$tag['labels'][] = 'Other - Please Specify Below';
return $tag;
}
add_filter( 'wpcf7_form_tag', 'dynamic_select_list', 10, 2);
This is for taxonomies but can be edited to use the the array you provided as follows
$options = (array) $tag[‘options’];
foreach ( $options as $option ) {
if ( preg_match( ‘%^posttype:([-0-9a-zA-Z_]+)$%’, $option, $matches ) )
{
$post_type = $matches[1];
}
}
//check if post_type is set
if(!isset($post_type))
return $tag;
$args= array(
'post_type' => $post_type
);
$colors = get_posts($args);
if ( ! $colors )
return $tag;
foreach ( $colors as $color ) {
$tag['raw_values'][] = $color->post_title;
$tag['values'][] = $color->post_title;
$tag['labels'][] = $color->post_title;
}
return $tag;
}
Option 2: Plugin
The Contact Form 7 Dynamic Text Extension may have the functionality you're seeking.
I found my solution somewhere else, but the code is almost the same
function dynamic_field_values ( $tag, $unused ) {
if ( $tag['name'] != 'colorfield' )
return $tag;
$args = array (
'numberposts' => -1,
'post_type' => 'color',
'orderby' => 'title',
'order' => 'ASC',
);
$custom_posts = get_posts($args);
if ( ! $custom_posts )
return $tag;
foreach ( $custom_posts as $custom_post ) {
$tag['raw_values'][] = $custom_post->post_title;
$tag['values'][] = $custom_post->post_title;
$tag['labels'][] = $custom_post->post_title;
}
return $tag;
}
add_filter( 'wpcf7_form_tag', 'dynamic_field_values', 10, 2);

Categories