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

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

Related

On button click save a flag to database in mediawiki 1.3

I am a fresher in mediawiki. I was trying to implement Manual:Tag extensions/Example (https://www.mediawiki.org/wiki/Manual:Tag_extensions/Example). But the example is based on mediawiki version < 1.3. I have a submit button. I want to save the current user name and a flag (say 1) to a database table if the submit button is clicked. but I am getting
Uncaught SyntaxError: Unexpected identifier (at load.php?lang=en&modules=ext.Example.welcome%7Cjquery&skin=vector&version=h3cy2:1:383).
Can I anyone suggest how to resolve the issue
My hook
class PollHooks implements
\MediaWiki\Hook\ParserFirstCallInitHook
{
Public function onParserFirstCallInit( $parser ) {
$parser->setHook( 'btn', [ self::class, 'pollRender' ] );
//$parser->setHook( 'poll', [self::class, 'pollRender' ] );
}
public static function pollRender( $data, $attribs, $parser, $frame ) {
$ret = '<table class="wtable">';
$ret .= '<tr>';
$ret .= '<td align="center" colspan=2><input id="btn002" type="button" value="Submit"></td>';
$ret .= '</tr>';
$ret .= '</table>';
return $ret;
}
My index.js
( function () {
$("#btn001").click
(
function() {
alert("Button clicked " + mw.user.getName() + ".");
console.log("Button clicked.");
$var user = mw.user.getName();
$flag = 1;
$.get(
mw.util.wikiScript(),
{
action: 'ajax',
rsargs: [user, flag],
rs: 'MediaWiki\\Extension\\Example\\SubmitApi'
}
);
}
);
}() );
SubmitApi.php
use ApiBase;
use Wikimedia\ParamValidator\ParamValidator;
class SubmitApi extends ApiBase {
public function execute() {
/* … */
global $wgUser;
$dbw = wfGetDB( DB_REPLICA );
// Insert vote
$insertQuery = $dbw->insert(
'polldb',
array(
'poll_user' => $user,
'poll_flag' => $flag
)
);
$dbw->commit();
}
public function getAllowedParams() {
return [
'level' => [
ParamValidator::PARAM_TYPE => 'integer',
ParamValidator::PARAM_REQUIRED => true,
]
];
}
}
?>
index.js:
$var user = mw.user.getName();
Remove the $ from $var.

Wordpress: Adding multiple category-names & tag-names from page to <body>

Please refer to code below.
I have already a code who gives category-names and tag-names to the <body>. But it only puts in one category and one tag, not all. What do i have to update in my code to tell wordpress that it should get all tags and categories and put that as 'class' into the <body>?
// category-name to body
function add_category_name($classes = '') {
if( is_page() )
{
$category = get_the_category();
$classes[] = 'category-'.$category[0]->slug;
}
return $classes;
}
add_filter('body_class','add_category_name');
// tag-name in body
function add_tag_name($classes = '') {
if( is_page() )
{
$tag = get_the_tags( $post->ID );
$classes[] = 'tag-'.$tag[0]->slug;
}
return $classes;
}
add_filter('body_class','add_tag_name');
Thank you!
SOLUTION
You can add this code to your custom functions.php file:
// add tags and categories to pages
function add_taxonomies_to_pages() {
register_taxonomy_for_object_type( 'post_tag', 'page' );
register_taxonomy_for_object_type( 'category', 'page' );
}
add_action( 'init', 'add_taxonomies_to_pages' );
if ( ! is_admin() ) {
add_action( 'pre_get_posts', 'category_and_tag_archives' );
}
function category_and_tag_archives( $wp_query ) {
$my_post_array = array('post','page');
if ( $wp_query->get( 'category_name' ) || $wp_query->get( 'cat' ) )
$wp_query->set( 'post_type', $my_post_array );
if ( $wp_query->get( 'tag' ) )
$wp_query->set( 'post_type', $my_post_array );
}
// add tags and categorys as class to <body>
function add_categories_and_tags( $classes = '' ) {
if( is_page() ) {
$categories = get_the_category();
foreach( $categories as $category ) {
$classes[] = 'category-'.$category->slug;
}
$tags = get_the_tags();
foreach( $tags as $tag ) {
$classes[] = 'tag-'.$tag->slug;
}
}
return $classes;
}
add_filter( 'body_class', 'add_categories_and_tags' );
Works perfect, tested in WordPress 4.8

wordpress json rest API to get custom field data

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

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

query function in cake php

I am writing code in php to basically 'map' data from a mySQL database to another database. I am using the code as follows:
$results = $this->query("select PT_FS_DATA_ID from PATIENT_FLOWSHEET_DATA where
DT_LAST_UPDATED_TIME = (select top 1 DT_LAST_UPDATED_TIME from PATIENT_FLOWSHEET_DATA
order by DT_LAST_UPDATED TIME desc) group by PT_FS_DATA_ID;");
however, I am getting an error:
syntax error, unexpected T_VARIABLE, expecting T_FUNCTION
Everywhere I look this seems to be the correct syntax. Is there something I'm missing here?
I tried putting the controller in there as well $this->controllerName->query, but that didn't work either.
Full Code:
class CaExtraFlowsheetFields extends CaBase {
public $name = 'CaExtraFlowsheetFields';
/*
NOTE: This is to take all the fields in flowsheet and
maps their id's.
*/
//public $useTable = 'ANSWER_ENTRY';
public $useTable = 'PATIENT_FLOWSHEET_DATA';
public $primaryKey = 'PT_FS_DATA_ID';
protected function getPrimaryKeyValue(
$hospital_id,
$patient_id,
$admission_id = null
) {
return $patient_id;
}
//*CHANGE BEGIN*
$results = $this->query("select PT_FS_DATA_ID from PATIENT_FLOWSHEET_DATA where
DT_LAST_UPDATED_TIME = (select top 1 DT_LAST_UPDATED_TIME from PATIENT_FLOWSHEET_DATA
order by DT_LAST_UPDATED TIME desc) group by PT_FS_DATA_ID;");
protected $filedMethodMappings = array(
'Method_GO' => array(
CaBase::KEY_MAPPING_LOGIC_COMPLEXITY => CaBase::LEVEL2_COMPLEXITY,
CaBase::KEY_FIELD_LOGIC_NAME => 'wsMethod_GO',
);
//########################################################################//
//Note[]>Block[] //
//>Method that calls LookUpField for every field in flowsheet // //
//########################################################################//
public function wsMethod_GO ($params) {
foreach($results as $value){
$questionName = ''.$value;
$msg_prefix = $this->name . "::" . __FUNCTION__ . ": ". "arrivez-vouz" ;
$ret = $this->wsLookUpField($params,$questionName,$msg_prefix);
return $ret;
}
unset($value);
}
//########################################################################//
public function wsLookUpField($params,$questionName,$msg_prefix){
$arrayValues=array();
try{
$hospital_id = $params[Constants::KEY_HOSPITAL_ID];
$patient_id = $params[Constants::KEY_PATIENT_ID];
$admission_id = $params[Constants::KEY_ADMISSION_ID];
$msg_prefix = $this->name . "::" . __FUNCTION__ . ": ". "attendez-vouz: l'hopital= ".$hospital_id.
" patient= ".$patient_id." admission= ".$admission_id;
//shows info about given question name
$msg_prefix = "*!*!*!*Show me ---> ".$questionName." : ".$answer_entry_id.
" = aic: " .$answer_id_check;
$ret = array();
//now with needed fields, grab the A_NAME:
$params = array(
'conditions' => array(
$this->name . '.PID' => $patient_id,
$this->name . '.PT_FS_DATA_ID' => $questionName,
),
'order' => array(
$this->name . '.' . $this->primaryKey . ' DESC'
),
'fields' => array(
$this->name . '.FS_VALUE_TEXT',
)
);
$rs = $this->find('first', $params);
/* check to make sure $rs has received an answer from the query
and check to make sure this answer is a part of the most recent
database entries for this note */
if (false != $rs) {
try {
$msg = $msg_prefix . "Data obtained successfully."."<br>".$result;
$result = $rs;
$ret = WsResponse::getResponse_Success($msg, $result);
} catch (Exception $e) {
$msg = $msg_prefix . "Exception occurred.";
$ret = WsResponse::getResponse_Error($msg);
}
/*answer was not part of most recent database entries, meaning no
answer was given for this particular question the last time this
particular note was filled out. Message is given accordingly.*/
} else {
$msg = $msg_prefix . "/No answer given.";
$ret = WsResponse::getResponse_Error($msg);
}
} catch (Exception $e) {
$msg = $msg_prefix . "Exception occurred.";
$ret = WsResponse::getResponse_Error($msg);
}
return $ret;
}
Here is what you are doing:
class ABC {
$result = 'whatever';
}
You can't declare a variable there!
Code needs to be inside a method/function...
class ABC
{
public function wsMethod_GO ($params)
{
$result = 'whatever';
}
}