Auto-remove custom field with no value on publish - wordpress

I got some plugins that auto-generates custom fields. Does anyone know how to automatically remove empty custom fields from post when I press "publish"?
A check I can put in my functions.php that does a check and removes the custom field if there is no value?

Here is the solution:
add_action('save_post','my_cf_check');
function my_cf_check($post_id) {
// verify this is not an auto save routine.
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return;
//authentication checks
if (!current_user_can('edit_post', $post_id)) return;
//obtain custom field meta for this post
$custom_fields = get_post_custom($post_id);
if(!$custom_fields) return;
foreach($custom_fields as $key=>$custom_field):
//$custom_field is an array of values associated with $key - even if there is only one value.
//Filter to remove empty values.
//Be warned this will remove anything that casts as false, e.g. 0 or false
//- if you don't want this, specify a callback.
//See php documentation on array_filter
$values = array_filter($custom_field);
//After removing 'empty' fields, is array empty?
if(empty($values)):
delete_post_meta($post_id,$key); //Remove post's custom field
endif;
endforeach;
return;
}

wp_insert_post_data is a hook that happens before a database write in the admin panel. You can probably use that to call a function that checks for data, then strips out any empty custom field entries.
Or, you could use the_content hooks on the front end to strip out empty custom fields before they get displayed to the user.
Or, if you have control of the theme files, you can just test for data in your custom fields before displaying them.

Related

auto generate post title in wordpress like ABC-123456

I want to auto-generate post title like that
Ex : ABC-123456
also i need to let (( ABC- )) fixed and random change the 06 numbers
and to dont change the post title through updating the post
First, to modify WordPress behavior the correct way, you find an appropriate hook. In this case, that would be a filter that allows changing the Post data before it is saved to the db.
The filter 'wp_insert_post_data' is exactly what you need, so you add your filter, and connect it to a function like so:
function zozson_filter_post_title(){
}
add_filter( 'wp_insert_post_data', 'zozson_filter_post_title',50,4);
'wp_insert_post_data' is the name of the filter
'zozson_filter_post_title' is the name you give to your function, to hook to it.
50 is the priority. I chose 50 to run it after most other things. Default is 10
4 is the number of variables that the filter passes to your function.
So now we will add those variables and the logic inside it, to assign these CPT sho7nat those titles on admin saving them.
function zozson_filter_post_title( $data, $postarr, $unsanitized_postarr, $update){
//Then if it is the post type sho7nat
if( $data['post_type'] !== 'sho7nat' ){
return $data;
}
//If there is already a titled saved ($update returns true always)
if( $data['post_title'] !== '' ){
return $data;
}
//Let's build our title
$post_title = ' ABC-';
//What better random number that a unique timestamp?
$random_number = strtotime('now');
//Add the random number to the post title to save. You can do these in 1 line instead of 3
$post_title.= $random_number;
//We now have a post title with ABC- fixed and a random number, tell WordPress to use it as the post title
$data['post_title'] = $post_title;
return $data;
}
add_filter( 'wp_insert_post_data', 'zozson_filter_post_title',50,4);
The title automatically assigned should be like in this example:

WordPress/WooCommerce - remove wp_count_posts call in wp-admin

There's a call to wp_count_posts() on every page in wp-admin. I would think it should only happen on the product pages. Is there a way to disable the call on all pages but products? Our site has over 100,000 products, and this call slows down wp-admin pages.
The following is the caller log from Query Monitor
wp_count_posts()
wp-includes/post.php:2859
WC_Install::is_new_install()
wp-content/plugins/woocommerce/includes/class-wc-install.php:399
WC_Admin_Notices::init()
wp-content/plugins/woocommerce/includes/admin/class-wc-admin-notices.php:58
WC_Admin->includes()
wp-content/plugins/woocommerce/includes/admin/class-wc-admin.php:62
do_action('init')
wp-includes/plugin.php:470
Could you try the following. Add following function in your theme functions.php . All credits goes to - wordpress remove post status count from cms
I have edited $post_type where we want all post types and $exclude_post_types changed to product over page post type.
add_filter('bulk_post_updated_messages', 'suppress_counts', 10, 2);
// We need to let the function "pass through" the intended filter content, so accept the variable $bulk_messages
function suppress_counts($bulk_messages) {
// If the GET "post_type" is not set, then it's the "posts" type
$post_type = (isset($_GET['post_type'])) ? $_GET['post_type'] : '';
// List any post types you would like to KEEP counts for in this array
$exclude_post_types = array('product');
// Global in the variable so we can modify it
global $locked_post_status;
// If the post type is not in the "Exclude" list, then set the $locked variable
if ( ! in_array($post_type, $exclude_post_types)) {
$locked_post_status = TRUE;
}
// Don't forget to return this so the filtered content still displays!
return $bulk_messages;
}

Woocommerce Readonly Billing Fields

I have some e-commerce website where the customer billing address is predefined on the back-end.
I need to set the "Billing Address" fields as 'readonly' to avoid the customer to replace the information placed there... but i donĀ“t know how/where to do it...
Is it possible?
Put following code in your theme's "function.php" file.
add_action('woocommerce_checkout_fields','customization_readonly_billing_fields',10,1);
function customization_readonly_billing_fields($checkout_fields){
$current_user = wp_get_current_user();;
$user_id = $current_user->ID;
foreach ( $checkout_fields['billing'] as $key => $field ){
if($key == 'billing_address_1' || $key == 'billing_address_2'){
$key_value = get_user_meta($user_id, $key, true);
if( strlen($key_value)>0){
$checkout_fields['billing'][$key]['custom_attributes'] = array('readonly'=>'readonly');
}
}
}
return $checkout_fields;
}
This function checks if the address fields have value (i.e. if the address is specified), and if it has value, makes the field/s readonly. Else keeps the fields open to add data for user.
Hope this helps.
You have not specified which form you want to customize making the billing address fields read-only. Normally the billing address fields appear on two types of forms on a WooCommerce site:
On a checkout form
On a my-account/edit-address/billing/ page
If your case is the first one, then zipkundan's answer is the best one. But if your case is the second one, then copy and paste the following code to your active theme's (or child theme if any) functions.php file:
add_filter('woocommerce_address_to_edit', 'cb_woocommerce_address_to_edit');
function cb_woocommerce_address_to_edit($address){
array_key_exists('billing_first_name', $address)?$address['billing_first_name']['custom_attributes'] = array('readonly'=>'readonly'):'';
array_key_exists('billing_last_name', $address)?$address['billing_last_name']['custom_attributes'] = array('readonly'=>'readonly'):'';
array_key_exists('billing_email', $address)?$address['billing_email']['custom_attributes'] = array('readonly'=>'readonly'):'';
array_key_exists('billing_email-2', $address)?$address['billing_email-2']['custom_attributes'] = array('readonly'=>'readonly'):'';
return $address;
}
The above code will make the following fields read-only:
Billing first name
Billing last name
Billing email address
Billing confirm email address
Array keys for other form fields on the same page are as follows:
billing_company
billing_country
billing_address_1
billing_address_2
billing_city
billing_state
billing_postcode
billing_phone
Additionally, you can make the read-only fields appear slightly faded out. So, add the following CSS to your theme's style.css
.woocommerce-address-fields input[readonly="readonly"]{
opacity: 0.5;
}
$checkout_fields['billing'][$key]['custom_attributes'] = array('readonly'=>'readonly');
this solves the problem
This one worked for me.
https://www.sitekickr.com/snippets/woocommerce/make-checkout-field-read
add_filter('woocommerce_billing_fields', 'my_woocommerce_billing_fields');
function my_woocommerce_billing_fields($fields)
{
$fields['billing_first_name']['custom_attributes'] = array('readonly'=>'readonly');
$fields['billing_last_name']['custom_attributes'] = array('readonly'=>'readonly');
return $fields;
}

wordpress plugin creation get_post_meta

I am building my first plugin, and I am using as a reference the following link.
http://www.sitepoint.com/create-a-voting-plugin-for-wordpress/
and I am trying to underestand the following part of the code:
function voteme_addvote()
{
$results = '';
global $wpdb;
$post_ID = $_POST['postid'];
$votemecount = get_post_meta($post_ID, '_votemecount', true) != '' ? get_post_meta($post_ID, '_votemecount', true) : '0';
$votemecountNew = $votemecount + 1;
update_post_meta($post_ID, '_votemecount', $votemecountNew);
$results.='<div class="votescore" >'.$votemecountNew.'</div>';
// Return the String
die($results);
}
I run the code and it works, but I just dont understand the following:
What is "get_post_meta" doing?
Does it create a custom meta field, the same as add_post_meta?, if it doesnt why there is not an add_post_meta?
I checked the DB, and it looks like it is creating a custom meta field... so in that order what is the difference between get_post_meta and add_post_meta?
Thanks very much for helping me understand this.
The first time your code runs, get_post_meta returns '' so $votemecount is set to 0. The following update_post_meta creates the new meta field as documented below. Values that start with _ are not displayed (are hidden meta fields).
The function, update_post_meta(), updates the value of an existing meta key (custom field) for the specified post.
This may be used in place of add_post_meta() function. The first thing this function will do is make sure that $meta_key already exists on $post_id. If it does not, add_post_meta($post_id, $meta_key, $meta_value) is called instead and its result is returned.

WordPress: get all meta data when user registers

I have a user registration form in the front end (in the Users admin section as well) with three extra fields (apart from default ones): birthday, country, language. their values are stored in usermeta table.
I have this action hook to retireve all meta data for the registered user:
add_action('user_register', 'new_user_func');
// user registration callback function
function new_user_func($userID) {
$newUser = get_user_meta( $userID );
$userMeta = array();
foreach ($newUser as $key => $value) {
$userMeta[$key] = $value[0];
}
//do something with $userMeta...
}
var_dump($userMeta) after submit doesn't give me the extra fields value though.. only defaults (first name, last name etc)
Anyone know what might be the case?
Did you try getting the values with:
$meta = get_the_author_meta($meta_key, $user_id);
Perhaps the meta values you add yourself isn't supported by get_user_meta() .
If this don't work either, perhaps you need to look on how you went about creating the new meta fields. Theres a pretty decent tutorial on how to do it here:
http://justintadlock.com/archives/2009/09/10/adding-and-using-custom-user-profile-fields
Read de Codex entry for user_register action, it says:
Not all user metadata has been stored in the database when this action is triggered.

Resources