wordpress json rest API to get custom field data - json

I am currently using the JSON REST API (WP API) plug-in to get my post and page data.
I have noticed that none of my custom field data is returned in the json, and looking at the routes, i don't think i can obtain these.
Any ideas via the current plug-in, or how I can accomplish this otherwise?

If you are using 'advanced custom fields' - until something more official is decided, you can use this plugin: https://github.com/times/acf-to-wp-api (and now on the shelf in standard wp plugin area too.)
It will include the custom fields under acf: [], in your json structure.

To grab a custom field value using native WP functions only, add the following to your functions.php
function my_rest_prepare_post( $data, $post, $request ) {
$_data = $data->data;
$_data[$field] = get_post_meta( $post->ID, 'my_custom_field_key', true );
$data->data = $_data;
return $data;
}
add_filter( 'rest_prepare_post', 'my_rest_prepare_post', 10, 3 );
Replace 'my_custom_field_key' with your custom field key name.
For multiple fields:
function my_rest_prepare_post( $data, $post, $request ) {
$_data = $data->data;
// My custom fields that I want to include in the WP API v2 responce
$fields = ['writer', 'publisher', 'year', 'youtube_link'];
foreach ( $fields as $field ) {
$_data[$field] = get_post_meta( $post->ID, $field, true );
}
$data->data = $_data;
return $data;
}
add_filter( 'rest_prepare_post', 'my_rest_prepare_post', 10, 3 );

You need to create this file contain following code in
wp-content\themes\name\inc\functions
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
/*
* init function
*/
if ( ! function_exists( 'mnu_rest_init' ) ) {
function mnu_rest_init() {
register_rest_route( 'guider/v1', '/booking', array(
'methods' => 'GET',
'callback' => 'handle_get_all',
'permission_callback' => function () {
return current_user_can( 'edit_others_posts' );
}
) );
register_rest_route( 'guider/v1', '/booking', array(
'methods' => 'POST',
'callback' => 'handle_post_booking',
'permission_callback' => function () {
return current_user_can( 'edit_others_posts' );
}
) );
}
}
//GET QUERY PARMS
function handle_get_all( $request_data) {
$parameters = $request_data->get_params();
$userId = $parameters["Id"];
global $wpdb;
$query = "SELECT * FROM `wp_trav_tour_bookings` WHERE `user_id` = $userId";
$list = $wpdb->get_results($query);
return $list;
}
// GET BODY PARMS
function handle_post_booking( $request_data) {
$parameters = $request_data->get_body();
$params = json_decode( $parameters , true );
// $userId = $parameters["Id"];
// global $wpdb;
// $query = "SELECT * FROM `wp_trav_tour_bookings` WHERE `user_id` = $userId";
// $list = $wpdb->get_results($query);
return $params ;
}
then you need to add
//actions
add_action( 'rest_api_init', 'mnu_rest_init');
to your main.php in
wp-content\themes\name\inc\functions
to do that you need to require this file to main.php
require_once dirname( __FILE__ ) . '/filename.php';

You can manipulate the response and add custom fields to the JSON. I'm using Advanced Custom Fields in my example but you can just add any key/value-pairs to the data object before returning it.
// In functions.php
function modify_rest_post( $data, $post, $request ) {
if (is_admin()) {
return $data;
}
$data->my_favorite_data = get_field('my_custom_field', $post->ID);
return $data;
}
add_filter( 'rest_prepare_post', 'modify_rest_post', 10, 3 );

Related

Using AJAX returned JSON encoded data in Codeigniter

I am relatively new to codeigniter. While I was trying to perform a searching operation on my data base using AJAX, The code is returned as successful and the data is retrieved but, This data is JSON encoded and is in the javascript portion of my view so I am unable to use the json_decode function of codeigniter
public function lookup(){
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->MAutocomplete->lookup($keyword); //Search DB
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id'=>$row->id,
'value' => $row->firstname,
); //Add a row to array
}
}
echo json_encode($data); //echo json string
}
the data is accessed in the javascript as data.message.
Please tell me is there anyway i can use this data in the php part of my program
<?php
class MAutocomplete extends CI_Model{
function lookup($keyword){
$this->load->database();
$this->db->select('*');
$this->db->from('Students');
$this->db->like('firstName',$keyword,'after');
$query = $this->db->get();
// echo '<pre>'; print_r($query->result()); exit;
return $query->result();
}
}
I think you need to parse json response in Ajax's success function using JSON.parse().Like this..
$.ajax({
url:'',//your url
dataType:'JSON',
data:'',//your data
success:function(response){
data = JSON.parse(response);
alert(data.message.value);//alerts value
}
});
In controller use count rather than empty.To check the array
if( count($query) >0 )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id'=>$row->id,
'value' => $row->firstname,
); //Add a row to array
}
}
You should use to response:
return $this->output
->set_content_type('application/json')
->set_output(json_encode($data));

Wordpress: How do I resolve Notice: Undefined offset: 0 in /wp-includes/capabilities.php on line 1145

I've looked at previous examples of this problem but I can't find a solution for what is causing this notice based on what I've seen from other people. This appears when I am adding a new post only.
1145 is:
$post = get_post( $args[0] );
I'm not getting any other kind of error so I'm not sure where in my code this is causing the problem.
Any help on this?
This is the code:
//show metabox in post editing page
add_action('add_meta_boxes', 'kk_add_metabox' );
//save metabox data
add_action('save_post', 'kk_save_metabox' );
//register widgets
add_action('widgets_init', 'kk_widget_init');
function kk_add_metabox() {
add_meta_box('kk_youtube', 'YouTube Video Link','kk_youtube_handler', 'post');
}
/**
* metabox handler
*/
function kk_youtube_handler($post)
{
$youtube_link = esc_attr( get_post_meta( $post->ID, 'kk_youtube', true ) );
echo '<label for="kk_youtube">YouTube Video Link</label><input type="text" id="kk_youtube" name="kk_youtube" value="' . $youtube_link . '" />';
}
/**
* save metadata
*/
function kk_save_metabox($post_id) {
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
//check if user can edit post
if( !current_user_can( 'edit_post' ) ) {
return;
}
if( isset($_POST['kk_youtube'] )) {
update_post_meta($post_id, 'kk_youtube', esc_url($_POST['kk_youtube']));
}
}
/**
* register widget
*/
function kk_widget_init() {
register_widget('KK_Widget');
}
/**
* Class KK_Widget widget class
*/
class KK_Widget extends WP_Widget
{
function __construct()
{
$widget_options = array(
'classname' => 'kk_class', // For CSS class name
'description' => 'Show a YouTube video from post metadata'
);
$this->WP_Widget('kk_id', 'YouTube Video', $widget_options);
}
/**
* Show widget form in Appearance/Widgets
*/
function form($instance)
{
$defaults = array(
'title' => 'YouTube Video'
);
$instance = wp_parse_args((array)$instance, $defaults);
var_dump($instance);
$title = esc_attr($instance['title']);
echo '<p>Title <input type="text" class="widefat" name="' . $this->get_field_name('title') . '" value="' . $title . '" /></p>';
}
function update($new_instance, $old_instance)
{
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
return $instance;
}
/**
* Show widget in post/page
*/
function widget($args, $instance)
{
global $before_widget;
global $after_widget;
global $before_title;
global $after_title;
extract( $args );
$title = apply_filters('widget_title', $instance['title']);
//show only if single post
if(is_single()) {
echo $before_widget;
echo $before_title.$title.$after_title;
//get post metadata
$kk_youtube = esc_url(get_post_meta(get_the_ID(), 'kk_youtube', true));
//print widget content
echo '<iframe width="200" height="200" frameborder="0" allowfullscreen src="http://www.youtube.com/embed/' . $this->get_yt_videoid($kk_youtube) . '"></iframe>';
echo $after_widget;
}
}
function get_yt_videoid($url)
{
parse_str(parse_url($url, PHP_URL_QUERY), $my_array_of_vars);
return $my_array_of_vars['v'];
}
}
I found the solution here https://wordpress.org/support/topic/patch-notice-undefined-offset-0-in-capabilitiesphp-on-line-1102
May seem different issue but I could fix the issue changing:
if ( ! current_user_can( 'edit_post' ) ) return;
to
if ( ! current_user_can( 'edit_posts' ) ) return;
In other scenary
if you have a custom taxonomy, you must be sure that 'assign_term' capability on 'capabilities' args is related to 'edit_posts'
'assign_terms' => 'edit_posts',
or
'assign_terms' => 'edit_mycustomposttypes',
(note the 's' at end)
example:
$capabilities = array(
'manage_terms' => 'manage_mytaxs',
'edit_terms' => 'manage_mytaxs',
'delete_terms' => 'manage_mytaxs',
**'assign_terms' => 'edit_mycustomposttypes',**
);
$args = array(
'show_ui' => true,
'show_admin_column' => true,
**'capabilities' => $capabilities,**
);
register_taxonomy( 'mytax', 'mycustomposttype', $args );
This line:
if( !current_user_can( 'edit_post' ) ) {
Should be:
if( !current_user_can( 'edit_post', $post_id ) ) {

WordPress add meta box allow HTML

I have set up a Meta box which all works fine, however I want to accept HTML, or the just the class really. I have tried to code in this to work however it doesn't and I'm not sure why this is.
My code is:
/**
* Adds a box to the main column on the Page edit screens.
*/
function myplugin_add_meta_box() {
$screens = array( 'page' );
foreach ( $screens as $screen ) {
add_meta_box(
'myplugin_sectionid',
__( 'Page Intro Text in Header', 'myplugin_textdomain' ),
'myplugin_meta_box_callback',
$screen
);
}
}
add_action( 'add_meta_boxes', 'myplugin_add_meta_box' );
/**
* Prints the box content.
*
* #param WP_Post $post The object for the current post/page.
*/
function myplugin_meta_box_callback( $post ) {
// Add an nonce field so we can check for it later.
wp_nonce_field( 'myplugin_meta_box', 'myplugin_meta_box_nonce' );
/*
* Use get_post_meta() to retrieve an existing value
* from the database and use the value for the form.
*/
$value = get_post_meta( $post->ID, 'pageintro', true );
echo '<input type="text" id="myplugin_new_field" name="myplugin_new_field" value="' . esc_html( $value ) . '" style="width: 100%;" />';
}
/**
* When the post is saved, saves our custom data.
*
* #param int $post_id The ID of the post being saved.
*/
function myplugin_save_meta_box_data( $post_id ) {
/*
* We need to verify this came from our screen and with proper authorization,
* because the save_post action can be triggered at other times.
*/
// Check if our nonce is set.
if ( ! isset( $_POST['myplugin_meta_box_nonce'] ) ) {
return;
}
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $_POST['myplugin_meta_box_nonce'], 'myplugin_meta_box' ) ) {
return;
}
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// Check the user's permissions.
if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) ) {
return;
}
} else {
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
}
/* OK, it's safe for us to save the data now. */
// Make sure that it is set.
if ( ! isset( $_POST['myplugin_new_field'] ) ) {
return;
}
// WP's default allowed tags
global $allowedtags;
// allow iframe only in this instance
$span = array( '<span>' => array(
'<span>' => array ()
) );
$allowed_html = array_merge( $allowedtags, $span );
// Sanitize user input.
$my_data = sanitize_text_field( $_POST['myplugin_new_field'], $allowed_html );
// Update the meta field in the database.
update_post_meta( $post_id, 'pageintro', $my_data );
}
// save the text input
if ( isset( $_POST['myplugin_new_field'] ) ) {
// Sanitize user input.
$my_data = sanitize_text_field( $_POST['myplugin_new_field'] );
// Update the meta field in the database.
update_post_meta( $post_id, 'pageintro', $my_data );
}
add_action( 'save_post', 'myplugin_save_meta_box_data' );
What do I need to change to get this work?
Thank you.
use reach text area for html it is very helpfull and also avilable in by default in wordpress folow this code
$value = get_post_meta( $post->ID, 'pageintro', true );
wp_editor( $meta, $field['id'], $settings);
$this->show_field_end( $field, $meta );

moving specific field value to another table before deleting the whole row

I have a table with 7 fields, when I delete a row from the table by id i want two fields of that row to be inserted into another table with just two columns.
This is my controller function
public function refund() {
$id = $this->uri->segment(4);
$accounts = $this->accounts_model->get_accounts_data_by_id($id);
foreach ($accounts as $row) {
$data = array(
'barcode' => $row->barcode,
'refunded_amount' => $row->refunded_amount,
);
}
$this->accounts_model->insert_refund($data);
$this->accounts_model->delete_accounts_data($id);
}
these are model functions
public function delete_accounts_data($id) {
$this->db->where('id', $id);
$this->db->delete('accounts');
}
public function insert_refund($data){
$this->db->insert('refund', $data);
}
Suppose this the row i will delete
id|name|barcode|refunded_amount|commission
01|asd |2342342| 53.01 | 5.32
on the other hand i will insert as
id|barcode|refunded_amount
01|2342342| 53.01
You should try and debug your code for general errors, e.g,
1) Try to set the environment to development in index.php.
2) Add some debugging code in your function to check for errors.
function refund(){
$id = $this->uri->segment(4);
$accounts = $this->accounts_model->get_accounts_data_by_id($id);
echo $this->db->last_query(); //will produce the query for fetching the details by id
if( isset( $accounts ) && count( $accounts ) > 0 ){
foreach ($accounts as $row) {
$data = array(
'barcode' => $row->barcode,
'refunded_amount' => $row->refunded_amount,
);
}
print_r( $data );
$this->accounts_model->insert_refund($data);
$this->accounts_model->delete_accounts_data($id);
}else{
echo "NO DATA FOUND";
}
}

insert if not exists Codeigniter

my controller:
function getFeed()
{
$feed_url = $this->input->get("url");
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
foreach($x->channel->item as $entry) {
$feeds[] = array(
'title' => (string)$entry->title,
'url'=> (string)$entry->link,
'username' => $this->session->userdata('username')
);
$this->load->model('membership_model');
$this->membership_model->feeds($feeds);
}
Model:
function feeds($feeds_data)
{
$this->db->insert_batch('feeds', $feeds_data);
}
Is there a function to insert if only the row doesn't exists in the table? I have a table with 4 column : id,title,url,username. I have an anchor when i click him it calls geFeed function and insert the info into table. But i want to insert only if not exists.
I had the same challenge, so i eventually come up with a function which might be helpful to you.
function safe_update_batch($table_name,$records,$filter_field)
{
$filters=array();
foreach($records as $record)$filters[]=$record[$filter_field];
$this->db->query("SET SESSION group_concat_max_len=10000000");
$query=$this->db->select("GROUP_CONCAT($filter_field) AS existing_keys",FALSE)->where_in($filter_field, $filters)->get($table_name);
$row=$query->row();
$found_fields=explode(',',$row->existing_keys);
$insert_batch=array();
$update_batch=array();
foreach($records as $record)
{
if(in_array($record[$filter_field],$found_fields))$update_batch[]=$record;
else $insert_batch[]=$record;
}
if(!empty($insert_batch))$this->db->insert_batch($table_name,$insert_batch);
if(!empty($update_batch))$this->db->update_batch($table_name,$update_batch,$filter_field);
}
//sample usage
$this->safe_update_batch('feeds', $feeds_data,'title');
You can try this in your model!!
function insertClient($array)
{
$this->db->from('MyTable');
$this->db->where('Id', $array['Id']);
$query = $this->db->get();
if($query->num_rows() != 0){
$data = array(
'name'=>$array['name'],
'phone'=>$array['phone'],
'email'=>$array['email']
);
$this->db->where('Id', $array['Id']);
$this->db->update('CLIENTS', $data);
}else{
$data = array(
'name'=>$array['name'],
'phone'=>$array['phone'],
'email'=>$array['email']
);
$this->db->insert('CLIENTS',$data);
}
}
In controller:
$this->site_model->insertClient($_POST);
Sadly if you are using the active record class an INSERT IF NOT EXISTS function doesn't exist. You could try
Extending the active record class (easier said than done)
You could set indexes on certain columns as UNIQUE so that MySQL will check to see if it already exists
You could do some kind of SELECT before your INSERT to determine if the record is already there
For the queries where you need to do INSERT IF NOT EXISTS do $this->db->query('INSERT IF NOT EXISTS...')
function getFeed()
{
// Load the model up here - otherwise you are loading it multiple times
$this->load->model('membership_model');
$feed_url = $this->input->get("url");
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
foreach($x->channel->item as $entry) {
// check if the feed is unique, if true then add to array
if( $this->membership_model->singleFeedIsUnique($entry) == TRUE ){
$feeds[] = array(
'title' => (string)$entry->title,
'url'=> (string)$entry->link,
'username' => $this->session->userdata('username')); }
} //foreach
// check to make sure we got any feeds with isset()
// if yes, then add them
if (isset($feeds)){ $this->membership_model->feeds($feeds); }
}
You can try this in your model and leave you controller without changes
function feeds($feeds_data)
{
$data = array(
title => $feeds_data[0],
url => $feeds_data[1],
username => $feeds_data[2]
);
$this->db->select('*');
$this->db->from('mytable');
$this->db->where('title',$feeds_data[0]);//you can use another field
if ($this->db->count_all_results() == 0) {
$query = $this->db->insert('mytable', $data);//insert data
} else {
$query = $this->db->update('mytable', $data, array('title'=>$feeds_data[0]));//update with the condition where title exist
}
}
you can check the id if you have it, adding in the data array and use it to check if exist