Data validation / Sanitization callback function - wordpress

I added a section to the customizer of my WP theme that allows a user to change which categories display on the first page of the theme. However, when checking with the Theme Check plugin, it returned the following error:
REQUIRED: Found a Customizer setting that did not have a sanitization callback function. Every call to the add_setting() method needs to have a sanitization callback function passed.
I have no idea how to add this function to my code. If you can help, here’s the code:
http://pastebin.com/xksf3vWd
Thanks in advance!

By default, the Customizer does not handle validation and sanitization of the user input values. It is therefore essential to sanitize these values before saving them to the database.
The add_setting() method of the WP_Customizer object accepts an 'sanitize_callback' argument, that can be used to specify a sanitization callback. So, in every add_setting() call, add the sanitization callback function.
$wp_customize->add_setting( 'first_category', array(
'default' => 'Uncategorized', // The default category name.
'sanitize_callback' => 'ys_sanitize_category', // Sanitize callback function name
) );
The Sanitize callback function:
function ys_sanitize_category( $category ) {
if ( ! in_array( $category, array( 'Uncategorized', 'Blogposts', 'News' ) ) ) { // Add the names of your categories here. Use get_categories() to fetch them dynamically.
$category = 'Uncategorized';
}
return $category;
}

Related

WordPress: Customize Ajax request response via filter

There is a function in parent theme and I want to customize success message, I don't want to make change in parent theme file. And the function is not pluggable so I can't override it. After digging, I found that I can use add_filter hook to filter response.
I wrote this code:
add_filter( 'wp_ajax_sync-data', 'custom_sync_data' );
function custom_sync_data(){
$response = array(
'success' => true,
'message' => 'Date is updated'
);
wp_send_json($response);
}
It does the job but it always returns success message, without any validation. I don't know, how to pass parameter for validation or decision making.
Can you try this
function custom_sync_data($params){
//$params can be data or parameters you will have to pass
//or you will have to check
//based on that your setup validation or logic
$response = array(
'success' => true,
'message' => 'Date is updated'
);
}
wp_send_json($response);
You may also use var_dump($params) to check if anything is passed to function.
Hope this helps.

How to check if a shortcode (including its params) exist?

Is there a way to check if a shortcode exist, including its 'id' attribute ?
For example, checking if the following shortcode is active on the website: [shortcode id="3268"]
Thanks in advance !
Try var_dump on the attributes within the Shortcode.
// var dump to show shortcode attributes are working
function bartag_func( $atts ) {
$att = shortcode_atts( array(
'foo' => 'something',
'bar' => 'something else',
), $atts );
var_dump($att);
}
add_shortcode( 'bartag', 'bartag_func' );
When you call the Shortcode ( [bartag] ) in this example - you will see the attributes default values (or the values you add to the Shortcode).
There is actually a shortcode API shortcode API in wordpress, allowing you to call functions and perform actions when the shortcode is present while displaying the page. If you want to check an entire website, you will have to code a plugin that goes thru all the content.

Custom-Field option not found in custom post type WP 4.6.1

I have created a custom post type call 'Movie'.Now,I want to add custom meta field in this call Movie Reviews.I have following code for custom post type.
function Create_Movies_Posttype()
{
register_post_type('Movies',
array(
'labels'=>array('name'=>__('Movies'),'singular_name'=>__('Movie')),
'public'=>true,
'has_archive'=>true,
'rewrite'=>array('slug'=>'movies'),
'support'=>array('title','custom-fields','edit'),
)
);
}
add_action('init','Create_Movies_Posttype');
Added Meta Box
function adding_custom_meta_boxes( $post ) {
add_meta_box(
'my-meta-box',
__( 'My Meta Box' ),
'render_my_meta_box',
'post',
'normal',
'default'
);
}
add_action( 'add_meta_boxes_post', 'adding_custom_meta_boxes' );
Any one please help me with this custom field.
You need to use add_meta_boxes() action to register metaboxes for a post type.
add_meta_box() function to define the box, and save_post action to save it.
You'll find everything you need by reading example on Codex add_meta_boxes
You need also to add supports parameter to the register post type arguments and add custom-field in the array defining the supports for it, all the native supports can be found here

Woocommerce custom fields for shipping calculator

I'm building a custom shipping method for Woocommerce, and the one thing I'm totally hung up on is how to pass custom values to the calculate_shipping() function, either when it's being used on the Cart page or Checkout page.
I need to pass a handful of user-defined variables that will impact the quote -- ie "Is Residential Address", "Is Trade Show", etc etc.
calculate_shipping receives the $package array which contains a 'destination' array, but this only includes the standard add1, add2, city, state, zip, country info. I've added custom fields to the checkout page under both billing and shipping but I still can't figure out how to make these values accessible to the calculate_shipping function.
I've added a custom field like so:
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
$fields['shipping']['is_residential'] = array(
'label' => __('Residential Address?', 'woocommerce'),
'type' => 'checkbox',
'required' => false,
'class' => array('form-row-wide'),
'clear' => true
);
return $fields;
}
And I see this field show up on the Shipping section of the checkout form. However, I'm not seeing how I can access it anywhere. Even doing a print_r($_POST) on the checkout page doesn't show this field as being part of the post data, even after I know the form has been updated and re-posted.
But most importantly, I need to add the contents of the submitted field into the $package object which Woocommerce passes to a shipping method's calculate_shipping() function.
I'm just really not sure where to even start with this.
You can't expect to add checkout fields and have them available at the cart page.
The correct way is to use cart packages.
Check function get_shipping_packages() from class-wc-cart.php
public function get_shipping_packages() {
// Packages array for storing 'carts'
$packages = array();
$packages[0]['contents'] = $this->get_cart(); // Items in the package
$packages[0]['contents_cost'] = 0; // Cost of items in the package, set below
$packages[0]['applied_coupons'] = $this->applied_coupons;
$packages[0]['destination']['country'] = WC()->customer->get_shipping_country();
$packages[0]['destination']['state'] = WC()->customer->get_shipping_state();
$packages[0]['destination']['postcode'] = WC()->customer->get_shipping_postcode();
$packages[0]['destination']['city'] = WC()->customer->get_shipping_city();
$packages[0]['destination']['address'] = WC()->customer->get_shipping_address();
$packages[0]['destination']['address_2'] = WC()->customer->get_shipping_address_2();
foreach ( $this->get_cart() as $item )
if ( $item['data']->needs_shipping() )
if ( isset( $item['line_total'] ) )
$packages[0]['contents_cost'] += $item['line_total'];
return apply_filters( 'woocommerce_cart_shipping_packages', $packages );
}
You gotta hook into woocommerce_cart_shipping_packages filter and add your fields there.
Most likely you will need to add them (your fields) at the shipping calculator and checkout pages.
Hope this helps.

Wordpress set default title when creating a new custom post

I have a custom post type with just two (text)fields: an ISBN number and a youtube url by using 'supports' => array('title') when creating my custom post type.
The problem is, I don't need a title. So when I save my post, I made it so that the title becomes the ISBN number.
add_filter('wp_insert_post_data', array($this, 'change_title'), 99, 2);
function change_title($data, $postarr) {
if ($data['post_type'] == 'book_video') {
// If it is our form has not been submitted, so we dont want to do anything
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return $data;
// Verify this came from the our screen and with proper authorization because save_post can be triggered at other times
if (!isset($_POST['wp_meta_box_nonce']))
return $data;
// Combine address with term
$title = $_POST['_bv_isbn'];
$data['post_title'] = $title;
}
return $data;
}
This works, but the problem is, when I save the post WITHOUT prefilling a title (anything at all) the post is not saved, the title change function is not called, and all of my fields are reset.
Is it possible to set a default value to the title and hide it ?
When you register your custom post type, you can set what it supports, including the title.
When you call register_post_type(), add another entry to $args called supports and set it's value to an array. You can then pass a list of elements you want that post type to support. The default is 'title' and 'editor', but there are a host of options to choose from.
For example:
<?php
register_post_type(
"myCustomPostType",
array(
'supports' : array(
'editor',
'author',
'custom-fields'
)
)
)
?>
So long as you miss out title then you won't have to define one for each post.
For more information, visit this page: http://codex.wordpress.org/Function_Reference/register_post_type#Arguments

Resources