WordPress add meta box allow HTML - 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 );

Related

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 wp_editor removes html tags - how to stop it?

Why does wp_editor remove all my html tags?
This is my code:
/**
* Outputs the content of the meta box.
*/
function prfx_meta_callback( $post ) {
// echo 'This is a meta box';
wp_nonce_field( basename( __FILE__ ), 'prfx_nonce' );
$prfx_stored_meta = get_post_meta( $post->ID );
$field_value = get_post_meta( $post->ID, 'meta-textarea', false );
// Settings that we'll pass to wp_editor
$args = array (
'textarea_rows' => 4,
'teeny' => true,
// 'media_buttons' => false,
);
?>
<p>
<label for="meta-text" class="prfx-row-title"><?php _e( 'Example Text Input', 'prfx-textdomain' )?></label>
<input type="text" name="meta-text" id="meta-text" value="<?php if ( isset ( $prfx_stored_meta['meta-text'] ) ) echo $prfx_stored_meta['meta-text'][0]; ?>" />
</p>
<label for="meta-textarea" class="prfx-row-title"><?php _e( 'Example Textarea Input', 'prfx-textdomain' )?></label>
<?php wp_editor( $field_value[0], 'meta-textarea', $args);?>
<?php
}
/**
* Saves the custom meta input.
*/
function prfx_meta_save( $post_id ) {
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'prfx_nonce' ] ) && wp_verify_nonce( $_POST[ 'prfx_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
// Checks for input and sanitizes/saves if needed
if( isset( $_POST[ 'meta-text' ] ) ) {
update_post_meta( $post_id, 'meta-text', sanitize_text_field( $_POST[ 'meta-text' ] ) );
}
// Checks for input and sanitizes/saves if needed
if( isset( $_POST[ 'meta-textarea' ] ) ) {
update_post_meta( $post_id, 'meta-textarea', sanitize_text_field( $_POST[ 'meta-textarea' ] ) );
}
}
add_action( 'save_post', 'prfx_meta_save' );
How can I stop it from removing html tags?
For instance I type in this:
<img src="http://xxxx.jpg" alt="10168088_719806568132380_3368979362641476670_n" width="300" height="214" class="alignnone size-medium wp-image-96" />
It removes it.
But if I type in plain text without html tags,
abcde.
It saves it.
Any ideas?
sanitize_text_field() cleans your input.
so replace
update_post_meta( $post_id, 'meta-textarea', sanitize_text_field( $_POST[ 'meta-textarea' ] ) );
with
update_post_meta( $post_id, 'meta-textarea', stripslashes( $_POST[ 'meta-textarea' ] ) );
may solve your problem.
Sanitize a string from user input or from the db.
Checks for invalid UTF-8, Convert single < characters to entity, strip all tags, remove line breaks, tabs and extra white space, strip octets.
try removing the sanitize function from update_post_meta( $post_id, 'meta-textarea', sanitize_text_field( $_POST[ 'meta-textarea' ] ) );

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

$wpdb insert not working

I've created a new meta box for my 'cases' post type. And when I publish a new 'cases' post I want to insert the meta id into a new table created by me called 'sort'. I used this code:
function save_postdata( $post_id ) {
global $post, $new_meta_boxes, $wpdb;
foreach ($new_meta_boxes as $meta_box) {
if ( !wp_verify_nonce( $_POST[$meta_box['name'].'_noncename'], plugin_basename(__FILE__) )) {
return $post_id;
}
if ( 'cases' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ))
return $post_id;
} else {
if ( !current_user_can( 'edit_post', $post_id ))
return $post_id;
}
$data = $_POST[$meta_box['name'].'_value'];
if(get_post_meta($post_id, $meta_box['name'].'_value') == "") {
add_post_meta($post_id, $meta_box['name'].'_value', $data, true);
$meta_id = get_post_meta($post_id, 'meta_id', true);
$wpdb->insert( 'sort', array('meta_id'=>$meta_id, 'column_order' => 1));
}
elseif($data != get_post_meta($post_id, $meta_box['name'].'_value', true))
update_post_meta($post_id, $meta_box['name'].'_value', $data);
elseif($data == "")
delete_post_meta($post_id, $meta_box['name'].'_value', get_post_meta($post_id, $meta_box['name'].'_value', true));
}
}
The sort table has three fields: id, meta_id and column_order. Can someone sees what I'm doing wrong?
Make sure that on your insert statement you add 'NULL'
$wpdb->insert( 'sort', array('NULL', 'meta_id'=>$meta_id, 'column_order' => 1));
This could be causing the issue, and also make sure that it's the correct order of your columns.