I'm trying to create a function.
My need is follow:
I have a cash on delivery payment method.
Sometime it happens that the shipping comes back because the address is wrong or not real.
Then I put this order in SPAM status.
I want that when I have a COD order, to check in all SPAM orders if address is present, if yes put the order in SPAM review status, so I can check it personally with client.
This is my code:
I put a check address button on "on hold" orders, that will check the addresses:
// 1. Create 2 new order statuses: SPAM and SPAM REVIEW
function create_new_order_statuses() {
register_post_status( 'wc-spam', array(
'label' => 'SPAM',
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true
) );
register_post_status( 'wc-spam-review', array(
'label' => 'SPAM REVIEW',
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true
) );
}
add_action( 'init', 'create_new_order_statuses' );
// 2. Register them in woocommerce
function add_spam_order_statuses_to_select( $order_statuses ) {
$order_statuses['wc-spam'] = 'SPAM';
$order_statuses['wc-spam-review'] = 'SPAM REVIEW';
return $order_statuses;
}
add_filter( 'wc_order_statuses', 'add_spam_order_statuses_to_select' );
add_action( 'woocommerce_admin_order_data_after_order_details', 'check_address_button_on_order_page' );
function check_address_button_on_order_page( $order ) {
if ( $order->get_status() === 'on-hold' ) {
$address = $order->get_address( 'shipping' );
echo '<button class="button check-address-button">Check Address</button>';
?>
<script>
jQuery('.check-address-button').click( function() {
var data = {
'action': 'check_address',
'address': <?php echo json_encode( $address ); ?>
};
jQuery.post(ajaxurl, data, function(response) {
if(response.found) {
alert('Match found, order status changed to "SPAM REVIEW"');
} else {
alert('No match found');
}
});
});
</script>
<?php
}
}
add_action( 'wp_ajax_check_address', 'check_address' );
function check_address() {
$address = json_decode( $_POST['address'] );
$spam_orders = wc_get_orders( array(
'status' => 'spam',
) );
foreach ( $spam_orders as $spam_order ) {
if ( $address == $spam_order->get_address( 'shipping' ) ) {
$order_id = $_POST['order_id'];
$order = wc_get_order( $order_id );
$order->update_status( 'spam-review' );
echo json_encode( array( 'found' => true ) );
wp_die();
}
}
echo json_encode( array( 'found' => false ) );
wp_die();
}
Of course doesn't work... any suggestion?
I am trying to update/refresh the shipping rates on city change, so far I have managed to do so only by refreshing the page manually.
add_action( 'woocommerce_package_rates', 'check_minimum_and_city', 10, 2 );
function check_minimum_and_city($rates, $package){
$selected_city = WC()->checkout->get_value('billing_city');
$price_thirty = array('bat-yam','hulon','azur','tel-aviv-yafo','givatayim','ramat-gan','bnei-brak','rishon-letzion','netaim','yavne','kfar-nagid','galiya','ben-zakai','beit-gamliel');
$price_fifty = array('einot','gan-shlomo','beit-oved','aseret','givat-brener','irus','misgav-dov','givton','kerem-yavne','beit-raban','rehovot','beit-elezri','beit-hanan','kvuzat-yavne','kfar-bilu','bnei-darom','nir-galim','kiryat-ekron','gedera','nes-tziona','kanot','gan-darom','netayim','mishmar-hashiva','gan-sorek','beit-dagan','ganot','beit-hanan-irus','hemed');
$price_sixty = array('savion','ganei-tikva','or-yehuda','kiryat-ono','yehud','petah-tikva','ramat-hasharon','herzliya','kfar-shmariyahu','rishpon','raanana','kfar-saba','tsafria','beer-yaakov','netser-sireni','nir-tzvi','ramla','matsliax','bnaya','kfar-aviv');
if(WC()->session->get( 'chosen_shipping_methods' )[0] == 'local_pickup:13'){
$minimum = 0;
}else{
$minimum_thirty = 100;
$minimum_fifty = 150;
$minimum_sixty = 200;
if(in_array($selected_city, $price_thirty)){
unset( $rates['flat_rate:18']);
unset( $rates['flat_rate:19']);
if(WC()->cart->subtotal < $minimum_thirty){
throw new Exception(
sprintf( 'סכום ההזמנה הנוכחית שלך עומד על %s, מינימום הזמנה לפני משלוח הינו %s.' ,
wc_price( WC()->cart->subtotal ),
wc_price( $minimum_thirty )
)
);
}
}elseif(in_array($selected_city, $price_fifty)){
unset( $rates['flat_rate:9']);
unset( $rates['flat_rate:19']);
if(WC()->cart->subtotal < $minimum_fifty){
throw new Exception(
sprintf( 'סכום ההזמנה הנוכחית שלך עומד על %s, מינימום הזמנה לפני משלוח הינו %s.' ,
wc_price( WC()->cart->subtotal ),
wc_price( $minimum_fifty )
)
);
}
}elseif(in_array($selected_city, $price_sixty)){
unset( $rates['flat_rate:9']);
unset( $rates['flat_rate:18']);
if(WC()->cart->subtotal < $minimum_sixty){
throw new Exception(
sprintf( 'סכום ההזמנה הנוכחית שלך עומד על %s, מינימום הזמנה לפני משלוח הינו %s.' ,
wc_price( WC()->cart->subtotal ),
wc_price( $minimum_sixty )
)
);
}
}
return $rates;
}
}
When I select a city field (dropdown custom list) I get the shipping cost I have made through the woocommerce settings but when I change it it does not update the rates.
add_filter( 'woocommerce_checkout_fields', 'city_dropdown_field' );
function city_dropdown_field( $fields ) {
$city_args = wp_parse_args( array(
'type' => 'select',
'options' => array(
'' => '',
'yavne' => 'יבנה',
'kfar-nagid' => 'כפר הנגיד',
'galiya' => 'גאליה',
'ben-zakai' => 'בן זכאי',
'beit-gamliel' => 'בית גמליאל',
'bnaya' => 'בניה',
'einot' => 'עינות',
'kfar-aviv' => 'כפר אביב',
'gan-shlomo' => 'גן שלמה',
'beit-oved' => 'בית עובד',
'aseret' => 'עשרת',
'givat-brener' => 'גבעת ברנר',
'irus' => 'אירוס',
'misgav-dov' => 'משגב דב',
'givton' => 'גיבתון',
'kerem-yavne' => 'כרם יבנה',
'beit-raban' => 'בית רבן',
'rehovot' => 'רחובות',
'beit-elezri' => 'בית אלעזרי',
'beit-hanan' => 'בית חנן',
'kvuzat-yavne' => 'קבוצת יבנה',
'kfar-bilu' => 'כפר בילו',
'bnei-darom' => 'בני דרום',
'nir-galim' => 'ניר גלים',
'kiryat-ekron' => 'קרית עקרון',
'gedera' => 'גדרה',
'nes-tziona' => 'נס ציונה',
'kanot' => 'כנות',
'netayim' => 'נטעים',
'gan-darom' => 'גן דרום',
'givatayim' => 'גבעתיים',
'ramat-gan' => 'רמת גן',
'tel-aviv-yafo' => 'תל אביב - יפו',
'bnei-brak' => 'בני ברק',
'ramat-hasharon' => 'רמת השרון',
'herzliya' => 'הרצליה',
'kfar-shmariyahu' => 'כפר שמריהו',
'rishpon' => 'רישפון',
'raanana' => 'רעננה',
'kfar-saba' => 'כפר סבא',
'bat-yam' => 'בת ים',
'hulon' => 'חולון',
'azur' => 'אזור',
'savion' => 'סביון',
'ganei-tikva' => 'גני תקווה',
'or-yehuda' => 'אור יהודה',
'kiryat-ono' => 'קרית אונו',
'yehud' => 'יהוד',
'petah-tikva' => 'פתח תקווה',
'rishon-letzion' => 'ראשון לציון',
'mishmar-hashiva' => 'משמר השבעה',
'gan-sorek' => 'גן שורק',
'beit-dagan' => 'בית דגן',
'ganot' => 'גנות',
'beit-hanan-irus' => 'בית חנן אירוס',
'hemed' => 'חמד',
'tsafria' => 'צפריה',
'beer-yaakov' => 'באר יעקב',
'netser-sireni' => 'נצר סירני',
'nir-tzvi' => 'ניר צבי',
'ramla' => 'רמלה',
'matsliax' => 'מצליח',
'clear' => true
),
), $fields['shipping']['shipping_city'] );
$fields['shipping']['shipping_city'] = $city_args;
$fields['billing']['billing_city'] = $city_args;
return $fields;
}
Tried using this jQuery but nothing does the work
add_action( 'wp_footer', 'checkout_shipping_city_refresh_display' );
function checkout_shipping_city_refresh_display() {
// On checkout
if ( is_checkout() && ! is_wc_endpoint_url() ) :
?><script type="text/javascript">
jQuery( function($){
// Shipping fias code change & input events
$(document.body).on( 'change', 'select[name=billing_city]', function() {
console.log($(this).val());
});
});
</script>
<?php
endif;
}
Help is appreciated. :-)
I have Managed to resolve the issue and here is my solution, the answer was in corrected AJAX call and changing from multiple shipping rates to one and changing the rate by code.
add_action('woocommerce_checkout_update_order_review', 'refresh_shipping_methods', 10, 1 );
function refresh_shipping_methods( $post_data ){
WC()->cart->calculate_shipping();
}
add_action( 'wp_footer', 'checkout_shipping_city_refresh_display' );
function checkout_shipping_city_refresh_display() {
// On checkout
if ( is_checkout() && ! is_wc_endpoint_url() ) :
?><script type="text/javascript">
jQuery(document).on('change', 'select[name=billing_city]', function(){
var requested_city = jQuery(this).val();
ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ) ?>'; // get ajaxurl
var data = {
'action': 'get_and_set_shipping_rate',
'city': requested_city
};
jQuery.ajax({
type: "POST",
url: ajaxurl, // this will point to admin-ajax.php
data: data,
async: false,
success: function (response) {
console.log(response);
setTimeout(function (){
jQuery('.shipping_method:checked').trigger('change');
});
}
});
});
</script>
<?php
endif;
}
function get_and_set_shipping_rate(){
$shipping_city = $_POST['city'];
$shipping_cost = get_shipping_cost_by_city($shipping_city);
setcookie('shipping_city_cost', $shipping_cost, time() + (86400 * 30), '/');
$_COOKIE['shipping_city_cost'] = $shipping_cost;
echo $shipping_cost;
wp_die();
}
add_action( 'wp_ajax_get_and_set_shipping_rate', 'get_and_set_shipping_rate' );
add_action( 'wp_ajax_nopriv_get_and_set_shipping_rate', 'get_and_set_shipping_rate' );
function get_shipping_cost_by_city( $city ) {
$cost = 30;
$price_thirty = array('bat-yam','hulon','azur','tel-aviv-yafo','givatayim','ramat-gan','bnei-brak','rishon-letzion','netaim','yavne','kfar-nagid','galiya','ben-zakai','beit-gamliel');
$price_fifty = array('einot','gan-shlomo','beit-oved','aseret','givat-brener','irus','misgav-dov','givton','kerem-yavne','beit-raban','rehovot','beit-elezri','beit-hanan','kvuzat-yavne','kfar-bilu','bnei-darom','nir-galim','kiryat-ekron','gedera','nes-tziona','kanot','gan-darom','netayim','mishmar-hashiva','gan-sorek','beit-dagan','ganot','beit-hanan-irus','hemed');
$price_sixty = array('savion','ganei-tikva','or-yehuda','kiryat-ono','yehud','petah-tikva','ramat-hasharon','herzliya','kfar-shmariyahu','rishpon','raanana','kfar-saba','tsafria','beer-yaakov','netser-sireni','nir-tzvi','ramla','matsliax','bnaya','kfar-aviv');
// SET HERE the default cost (when "calculated cost" is not yet defined)
if(in_array($city, $price_thirty)){
$cost = 30;
}elseif(in_array($city, $price_fifty)){
$cost = 50;
}elseif(in_array($city, $price_sixty)){
$cost = 60;
}
return $cost;
}
add_filter('woocommerce_package_rates', 'update_shipping_costs_based_on_cart_session_custom_data', 10, 2);
function update_shipping_costs_based_on_cart_session_custom_data( $rates, $package ){
$selected_city = WC()->checkout->get_value('billing_city');
$calculated_cost = get_shipping_cost_by_city($selected_city);
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return $rates;
// SET HERE the default cost (when "calculated cost" is not yet defined)
$cost = '30';
// Iterating though Shipping Methods
foreach ( $rates as $rate_key => $rate_values ) {
$method_id = $rate_values->method_id;
$rate_id = $rate_values->id;
// For "Flat rate" Shipping" Method only
if ( 'flat_rate' === $method_id ) {
if( ! empty( $calculated_cost ) ) {
$cost = $calculated_cost;
}
// Set the rate cost
$rates[$rate_id]->cost = number_format($rates[$rate_id]->cost * $cost, 2);
WC()->session->set( 'shipping_calculated_cost', $rates[$rate_id]->cost );
// Taxes rate cost (if enabled)
foreach ($rates[$rate_id]->taxes as $key => $tax){
if( $rates[$rate_id]->taxes[$key] > 0 ){ // set the new tax cost
$taxes[$key] = number_format( $rates[$rate_id]->taxes[$key] * $cost, 2 );
$has_taxes = true;
} else {
$has_taxes = false;
}
}
if( $has_taxes )
$rates[$rate_id]->taxes = $taxes;
}
}
return $rates;
}
In Woocommerce checkout section, I am trying to add a checkbox that adds an additional subscription product. It is working fine and I took help from here
One more requirement is that if there are other products in the cart then I want to change each product prices based on custom fields and new prices should display in the checkout.
Thanks in advance.
I used this code and working fine but product price is not changing in PayPal payment page.
// Display a custom checkout field
add_action( 'woocommerce_checkout_before_terms_and_conditions', 'custom_checkbox_checkout_field' );
function custom_checkbox_checkout_field() {
$value = WC()->session->get('add_a_product');
woocommerce_form_field( 'cb_add_product', array(
'type' => 'checkbox',
'label' => ' ' . __('Please check here to get VIP Membership'),
'class' => array('form-row-wide'),
), $value == 'yes' ? true : false );
}
// The jQuery Ajax request
add_action( 'wp_footer', 'checkout_custom_jquery_script' );
function checkout_custom_jquery_script() {
// Only checkout page
if( is_checkout() && ! is_wc_endpoint_url() ):
// Remove "ship_different" custom WC session on load
if( WC()->session->get('add_a_product') ){
WC()->session->__unset('add_a_product');
}
if( WC()->session->get('product_added_key') ){
WC()->session->__unset('product_added_key');
}
// jQuery Ajax code
?>
<script type="text/javascript">
jQuery( function($){
if (typeof wc_checkout_params === 'undefined')
return false;
$('form.checkout').on( 'change', '#cb_add_product', function(){
var value = $(this).prop('checked') === true ? 'yes' : 'no';
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
'action': 'add_a_product',
'add_a_product': value,
},
success: function (result) {
$('body').trigger('update_checkout');
//console.log(result);
}
});
});
});
</script>
<?php
endif;
}
// The Wordpress Ajax PHP receiver
add_action( 'wp_ajax_add_a_product', 'checkout_ajax_add_a_product' );
add_action( 'wp_ajax_nopriv_add_a_product', 'checkout_ajax_add_a_product' );
function checkout_ajax_add_a_product() {
if ( isset($_POST['add_a_product']) ){
WC()->session->set('add_a_product', esc_attr($_POST['add_a_product']));
echo $_POST['add_a_product'];
}
die();
}
// Add remove free product
add_action( 'woocommerce_before_calculate_totals', 'adding_removing_specific_product' );
function adding_removing_specific_product( $cart ) {
if (is_admin() && !defined('DOING_AJAX'))
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// HERE the specific Product ID
$product_id = 179;
if( WC()->session->get('add_a_product') == 'yes' && ! WC()->session->get('product_added_key') )
{
foreach ( $cart->get_cart() as $cart_item ) {
$cart_item_key = $cart->add_to_cart( $product_id );
WC()->session->set('product_added_key', $cart_item_key);
// get the product id (or the variation id)
$product_id = $cart_item['data']->get_id();
// GET THE NEW PRICE (code to be replace by yours)
$new_price = get_post_meta( $product_id, 'pro_price_extra_info', true );
// Updated cart item price
$cart_item['data']->set_price( floatval( $new_price ) );
}
}
elseif( WC()->session->get('add_a_product') == 'no' && WC()->session->get('product_added_key') )
{
$cart_item_key = WC()->session->get('product_added_key');
$cart->remove_cart_item( $cart_item_key );
WC()->session->__unset('product_added_key');
}
}
I got solution for my above post. It might help others in future.
// Display a custom checkout field
add_action( 'woocommerce_checkout_before_terms_and_conditions', 'custom_checkbox_checkout_field' );
function custom_checkbox_checkout_field() {
$value = WC()->session->get('add_a_product');
woocommerce_form_field( 'cb_add_product', array(
'type' => 'checkbox',
'label' => ' ' . __('Please check here to get VIP Membership'),
'class' => array('form-row-wide'),
), $value == 'yes' ? true : false );
}
// The jQuery Ajax request
add_action( 'wp_footer', 'checkout_custom_jquery_script' );
function checkout_custom_jquery_script() {
// Only checkout page
if( is_checkout() && ! is_wc_endpoint_url() ):
// Remove "ship_different" custom WC session on load
if( WC()->session->get('add_a_product') ){
WC()->session->__unset('add_a_product');
}
if( WC()->session->get('product_added_key') ){
WC()->session->__unset('product_added_key');
}
// jQuery Ajax code
?>
<script type="text/javascript">
jQuery( function($){
if (typeof wc_checkout_params === 'undefined')
return false;
$('form.checkout').on( 'change', '#cb_add_product', function(){
var value = $(this).prop('checked') === true ? 'yes' : 'no';
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
'action': 'add_a_product',
'add_a_product': value,
},
success: function (result) {
$('body').trigger('update_checkout');
//console.log(result);
}
});
if(value == 'no'){
window.location.reload();
}
});
});
</script>
<?php
endif;
}
// The Wordpress Ajax PHP receiver
add_action( 'wp_ajax_add_a_product', 'checkout_ajax_add_a_product' );
add_action( 'wp_ajax_nopriv_add_a_product', 'checkout_ajax_add_a_product' );
function checkout_ajax_add_a_product() {
if ( isset($_POST['add_a_product']) ){
WC()->session->set('add_a_product', esc_attr($_POST['add_a_product']));
echo $_POST['add_a_product'];
}
die();
}
// Add remove free product
add_action( 'woocommerce_before_calculate_totals', 'adding_removing_specific_product' );
function adding_removing_specific_product( $cart ) {
if (is_admin() && !defined('DOING_AJAX'))
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$has_sub = wcs_user_has_subscription( '', '179', 'active' );
$product_id = 179;
if( WC()->session->get('add_a_product') == 'yes' && ! WC()->session->get('product_added_key') ){
// HERE the specific Product ID
foreach ( $cart->get_cart() as $cart_item ) {
// get the product id (or the variation id)
$product_idnew = $cart_item['data']->get_id();
// GET THE NEW PRICE (code to be replace by yours)
$new_price = get_post_meta( $product_idnew, 'pro_price_extra_info', true );
$old_price = $cart_item['data']->get_price();
if($new_price == NULL){
$cart_item['data']->set_price( floatval( $old_price ) );
} else {
$cart_item['data']->set_price( floatval( $new_price ) );
}
}
$cart_item_key = $cart->add_to_cart( $product_id );
WC()->session->set('product_added_key', $cart_item_key);
} elseif( WC()->session->get('add_a_product') == 'no' && WC()->session->get('product_added_key') ) {
$cart_item_key = WC()->session->get('product_added_key');
$cart->remove_cart_item( $cart_item_key );
WC()->session->__unset('product_added_key');
}elseif ( $has_sub ) {
foreach ( $cart->get_cart() as $cart_item ) {
// get the product id (or the variation id)
$product_idnew = $cart_item['data']->get_id();
// GET THE NEW PRICE (code to be replace by yours)
$new_price = get_post_meta( $product_idnew, 'pro_price_extra_info', true );
$cart_item['data']->set_price( floatval( $new_price ) );
}
}
}
function woo_in_cart($product_id) {
global $woocommerce;
foreach($woocommerce->cart->get_cart() as $key => $val ) {
$_product = $val['data'];
if($product_id == $_product->id ) {
return true;
}
}
return false;
}
add_action( 'woocommerce_cart_loaded_from_session', 'adding_vip_product' );
function adding_vip_product( $cart ) {
$product_id = 179;
if(woo_in_cart($product_id) ) {
foreach ( $cart->get_cart() as $cart_item ) {
// get the product id (or the variation id)
$product_idnew = $cart_item['data']->get_id();
// GET THE NEW PRICE (code to be replace by yours)
$new_price = get_post_meta( $product_idnew, 'pro_price_extra_info', true );
if($new_price != 0){
$cart_item['data']->set_price( floatval( $new_price ) );
}
}
}
}
I want to load my post category in the drop-down select box
how I do this
help me please I am new to programming:
this is my code that creates the custom meta boxes and now in the category boxenter image description here, I want that it loads all the category of post in the drop-down menu: the output of the code is shown in the image attached
<?php
//Start: Adding custom metaboxes
class leaderboarddetailMetabox {
private $screen = array(
'ld-leaderboard',
);
private $meta_fields = array(
array(
'label' => 'Number of Students',
'id' => 'numberofstudent_81418',
'type' => 'number',
),
array(
'label' => 'Select Point Type',
'id' => 'selectpointtype_39141',
'type' => 'select',
'options' => array(
'Select',
'Int',
'Float',
'String',
),
),
array(
'label' => 'Category',
'id' => 'category_59112',
'type' => 'select',
'options' => array(
'Select',
'Course',
'Lesson',
'Topic',
'Quiz',
'Category',
),
),
array(
'label' => 'Time',
'id' => 'time_93126',
'type' => 'date',
),
array(
'label' => 'Shortcode',
'id' => 'shortcode_85946',
'type' => 'text',
'readonly' => true,
),
);
public function __construct() {
add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
add_action( 'save_post', array( $this, 'save_fields' ) );
}
// show meta boxes on admin page
public function add_meta_boxes() {
foreach ( $this->screen as $single_screen ) {
add_meta_box(
'leaderboarddetail',
__( 'leader board detail', 'textdomain' ),
array( $this, 'meta_box_callback' ),
$single_screen,
'advanced',
'default'
);
}
}
public function meta_box_callback( $post ) {
wp_nonce_field( 'leaderboarddetail_data', 'leaderboarddetail_nonce' );
$this->field_generator( $post );
}
public function field_generator( $post ) {
$output = '';
foreach ( $this->meta_fields as $meta_field ) {
$label = '<label for="' . $meta_field['id'] . '">' . $meta_field['label'] . '</label>';
$meta_value = get_post_meta( $post->ID, $meta_field['id'], true );
if ( empty( $meta_value ) ) {
$meta_value = $meta_field['default']; }
switch ( $meta_field['type'] ) {
case 'select':
$input = sprintf(
'<select id="%s" name="%s">',
$meta_field['id'],
$meta_field['id']
);
foreach ( $meta_field['options'] as $key => $value ) {
$meta_field_value = !is_numeric( $key ) ? $key : $value;
$input .= sprintf(
'<option %s value="%s">%s</option>',
$meta_value === $meta_field_value ? 'selected' : '',
$meta_field_value,
$value
);
}
$input .= '</select>';
break;
default:
$input = sprintf(
'<input %s id="%s" name="%s" type="%s" value="%s" %s >',
$meta_field['type'] !== 'color' ? 'style="width: 100%"' : '',
$meta_field['id'],
$meta_field['id'],
$meta_field['type'],
$meta_value,
$meta_field['readonly'] ? "readonly" : ""
);
}
$output .= $this->format_rows( $label, $input );
}
echo '<table class="form-table"><tbody>' . $output . '</tbody></table>';
}
public function format_rows( $label, $input ) {
return '<tr><th>'.$label.'</th><td>'.$input.'</td></tr>';
}
// save custom field data to databse and in the field
public function save_fields( $post_id ) {
if ( ! isset( $_POST['leaderboarddetail_nonce'] ) )
return $post_id;
$nonce = $_POST['leaderboarddetail_nonce'];
if ( !wp_verify_nonce( $nonce, 'leaderboarddetail_data' ) )
return $post_id;
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
foreach ( $this->meta_fields as $meta_field ) {
if ( isset( $_POST[ $meta_field['id'] ] ) ) {
switch ( $meta_field['type'] ) {
case 'email':
$_POST[ $meta_field['id'] ] = sanitize_email( $_POST[ $meta_field['id'] ] );
break;
case 'text':
$_POST[ $meta_field['id'] ] = sanitize_text_field( $_POST[ $meta_field['id'] ] );
break;
}
update_post_meta( $post_id, $meta_field['id'], $_POST[ $meta_field['id'] ] );
} else if ( $meta_field['type'] === 'checkbox' ) {
update_post_meta( $post_id, $meta_field['id'], '0' );
}
// generate shortcode and save
if( $meta_field['id'] == 'shortcode_85946' ) {
// update meta
update_post_meta( $post_id, $meta_field['id'], "[custom-shortcode id=" . $post_id . "]");
}
}
}
}
if (class_exists('leaderboarddetailMetabox')) {
new leaderboarddetailMetabox;
};
?>
I create new post type and set 'rewrite' => false then for set new permalink I use:
// add to our plugin init function
global $wp_rewrite;
$dariche_structure = '/d/%post_id%/%dariche%';
$wp_rewrite->add_rewrite_tag("%dariche%", '([^/]+)', "dariche=");
$wp_rewrite->add_permastruct('dariche', $dariche_structure, false);
// Add filter to plugin init function
add_filter('post_type_link', 'dariche_permalink', 10, 3);
// Adapted from get_permalink function in wp-includes/link-template.php
function dariche_permalink($permalink, $post_id, $leavename) {
$post = get_post($post_id);
$rewritecode = array(
'%year%',
'%monthnum%',
'%day%',
'%hour%',
'%minute%',
'%second%',
$leavename? '' : '%postname%',
'%post_id%',
'%category%',
'%author%',
$leavename? '' : '%pagename%',
);
if ( '' != $permalink && !in_array($post->post_status, array('draft', 'pending', 'auto-draft')) ) {
$unixtime = strtotime($post->post_date);
$category = '';
if ( strpos($permalink, '%category%') !== false ) {
$cats = get_the_category($post->ID);
if ( $cats ) {
usort($cats, '_usort_terms_by_ID'); // order by ID
$category = $cats[0]->slug;
if ( $parent = $cats[0]->parent )
$category = get_category_parents($parent, false, '/', true) . $category;
}
// show default category in permalinks, without
// having to assign it explicitly
if ( empty($category) ) {
$default_category = get_category( get_option( 'default_category' ) );
$category = is_wp_error( $default_category ) ? '' : $default_category->slug;
}
}
$author = '';
if ( strpos($permalink, '%author%') !== false ) {
$authordata = get_userdata($post->post_author);
$author = $authordata->user_nicename;
}
$date = explode(" ",date('Y m d H i s', $unixtime));
$rewritereplace =
array(
$date[0],
$date[1],
$date[2],
$date[3],
$date[4],
$date[5],
$post->post_name,
$post->ID,
$category,
$author,
$post->post_name,
);
$permalink = str_replace($rewritecode, $rewritereplace, $permalink);
} else { // if they're not using the fancy permalink option
}
return $permalink;
}
My new post type name is dariche.
My default permalink for all post in setting is: article/%post_id%/%postname%/.
Now, my permalink of my new post type is d/%post_id%/%postname%/. But it doesn't work and just show 404 Error! What is problem in my code?
it seems you just want to change the base of the new post type permalink. you can achieve this by setting up rewrite. When you registering the post type.
'rewrite' => array(
'slug' => 'd',
'with_front' => false,
)