Skip to content

Instantly share code, notes, and snippets.

@espellcaste
Created July 18, 2013 04:00
Show Gist options
  • Save espellcaste/6026639 to your computer and use it in GitHub Desktop.
Save espellcaste/6026639 to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: WooCommerce Correios - Envelope
* Plugin URI: http://claudiosmweb.com/
* Description: Este plugin ajuda a usar uma taxa fixa para ser usada como preço de envelope
* Author: claudiosanches
* Author URI: http://claudiosmweb.com/
* Version: 1.0
* License: GPLv2 or later
*/
/**
* Register envelope metabox.
*
* @return void
*/
function cs_correios_envelope_metabox() {
add_meta_box(
'envelope',
'Correios',
'cs_correios_envelope_metabox_content',
'product',
'side',
'default'
);
}
add_action( 'add_meta_boxes', 'cs_correios_envelope_metabox' );
/**
* Envelope metabox content.
*
* @param object $post Product data.
*
* @return string Metabox HTML.
*/
function cs_correios_envelope_metabox_content( $post ) {
// Use nonce for verification.
wp_nonce_field( basename( __FILE__ ), 'cs_correios_is_envelope' );
$html = '<label for="is_envelope">' . __( 'Produto entregue utilizando envelope:' ) . '</label> ';
$html .= sprintf( '<input type="checkbox" id="is_envelope" name="is_envelope" value="1"%s />', checked( 1, get_post_meta( $post->ID, 'is_envelope', true ), false ) );
echo $html;
}
/**
* Save metabox data.
*
* @param int $post_id Post ID.
*
* @return void
*/
function cs_correios_envelope_save_metabox( $post_id ) {
// Verify nonce.
if ( ! isset( $_POST['cs_correios_is_envelope'] ) || ! wp_verify_nonce( $_POST['cs_correios_is_envelope'], basename( __FILE__ ) ) ) {
return $post_id;
}
// Verify if this is an auto save routine.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return $post_id;
}
// Check permissions.
if ( 'product' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) ) {
return $post_id;
}
} elseif ( ! current_user_can( 'edit_post', $post_id ) ) {
return $post_id;
}
if ( isset( $_POST['is_envelope'] ) ) {
update_post_meta( $post_id, 'is_envelope', $_POST['is_envelope'] );
} else {
delete_post_meta( $post_id, 'is_envelope' );
}
}
add_action( 'save_post', 'cs_correios_envelope_save_metabox' );
/**
* Verifies that there products are not envelopes.
*
* @param array $available_methods Available shipping methods.
*
* @return array New rates.
*/
function cs_correios_checks_if_exist_envelope( $available_methods ) {
global $woocommerce;
if ( isset( $available_methods['flat_rate'] ) ) {
foreach ( $woocommerce->cart->cart_contents as $item_id => $values ) {
if ( ! get_post_meta( $values['product_id'], 'is_envelope', true ) ) {
unset( $available_methods['flat_rate'] );
break;
}
}
}
return $available_methods;
}
add_filter( 'woocommerce_available_shipping_methods', 'cs_correios_checks_if_exist_envelope' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment