Wordpress plugin can not added to the page - wordpress

I am new with wordpress, I create a image uploader which followed a youtube video. But I found that it is only showed when I create new page. I can not add the uploader to the new page.
This is my code:
For php file
namespace image_uploader;
function register_metaboxes() {
add_meta_box('image_metabox','Image Uploader', __NAMESPACE__ . '\image_uploader_callback');
}
add_action('add_meta_boxes', __NAMESPACE__ . '\register_metaboxes');
function register_admin_script() {
wp_enqueue_script('wp_img_upload', plugins_url('image-upload.js', __FILE__), array('jquery', 'media-upload'), '1.0', true);
}
add_action('admin_enqueue_scripts', __NAMESPACE__ . '\register_admin_script');
function image_uploader_callback( $post_id ) {
wp_nonce_field( basename( __FILE__ ), 'image_nonce' );
$image_stored_meta = get_post_meta( $post_id );
?>
<div class="image-preview-wrapper">
<img id="image-preview" src="<?php if ( isset ( $image_stored_meta['image_meta'] ) ) echo $image_stored_meta['image_meta'][0]; ?>" style="max-width: 250px;">
<input type="hidden" name="image_meta" id="image-meta">
<button type="button" id="image-upload-button" class="button">Upload Image</button>
<button type="button" id="image-remove-button" class="button">Remove Image</button>
</div>
<button id="nextPage">move to the next page</button>
<?php
}
function save_custom_meta( $post_id, $post, $update ) {
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'image_nonce' ] ) && wp_verify_nonce( $_POST[ 'image_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[ 'image_meta' ] ) ) {
$image_data = json_decode( stripslashes( $_POST[ 'image_meta' ] ), true );
if(is_object($image_data)) {
$image_data = array(
'id' => intval($image_data[0]->id),
'src' => esc_url_raw($image_data[0]->url),
'width' => intval($image_data[0]->width),
'height' => intval($image_data[0]->height)
);
} else {
$image_data=[];
}
update_post_meta( $post_id, 'image_meta', sanitize_text_field( $_POST[ 'image_meta' ] ) );
}
}
add_action( 'save_post', __NAMESPACE__ . '\save_custom_meta', 10, 3 );
add_filter('wp_handle_upload_prefilter','tc_handle_upload_prefilter');
function tc_handle_upload_prefilter($file)
{
$img=getimagesize($file['tmp_name']);
$fixedSize = array('width' => '400', 'height' => '600');
$width= $img[0];
$height =$img[1];
if ($width != $fixedSize['width'] )
return array("error"=>"Image dimensions are too small. Minimum width is {$fixedSize['width']}px. Uploaded image width is $width px");
elseif ($height != $fixedSize['height'])
return array("error"=>"Image dimensions are too small. Minimum height is {$fixedSize['height']}px. Uploaded image height is $height px");
else
return $file;
}
for js file
addEventListener("DOMContentLoaded", function() {
console.log('DOMContentLoaded');
var addButton = document.getElementById('image-upload-button');
var removeButton = document.getElementById('image-remove-button');
var image = document.getElementById('image-preview');
var hidden = document.getElementById('image-meta');
var next = document.getElementById('nextPage');
image.setAttribute('required', 'required');
var uploader = wp.media({
title: 'Select an image',
button: {
text: 'Use this image'
},
multiple: false
});
addButton.addEventListener('click', function(e) {
e.preventDefault();
if(uploader) {
uploader.open();
}
});
uploader.on('select', function() {
var attachment = uploader.state().get('selection').first().toJSON();
image.setAttribute('src', attachment.url);
hidden.setAttribute('value', JSON.stringify({id: attachment.id, url: attachment.url}));
});
removeButton.addEventListener('click', function(e) {
image.removeAttribute('src');
hidden.removeAttribute('value');
});
next.addEventListener('click', function(e) {
e.preventDefault();
window.location.href = "http://google.com";
});
});
I did a lot of research, but still can not figure it out.
Please give me some advices, thanks a lot!

Related

Add "insert button" on toolbar tinymce editor

I want to add an "insert button" on my toolbar tinymce editor.
An example of what I want :
An example of what I want
With the toolbar button, I would like to create a button in my editor and change its style. (Like the gutenberg editor does)
gutenberg editor
To use the tinymce editor, I have this code :
function wpc_boutons_tinymce($buttons) {
$buttons[] = 'underline';
$buttons[] = 'fontselect';
$buttons[] = 'fontsizeselect';
$buttons[] = 'edit-block';
return $buttons;
}
add_filter("mce_buttons_3", "wpc_boutons_tinymce");
$content = '';
$editor_id = 'mycustomeditor';
$settings = array(
'wpautop' => false,
'media_buttons' => false,
'quicktags' => array(
'buttons' => 'strong,em,del,ul,ol,li,block,close'
),
);
wp_editor( $content, $editor_id, $settings );
I didn't find how to do, can you help me ?
Here is my implemented code Follow the step
Paste the code in your theme functions.php
add_action( 'init', 'wptuts_buttons' );
function wptuts_buttons() {
add_filter( "mce_external_plugins", "wptuts_add_buttons" );
add_filter( 'mce_buttons', 'wptuts_register_buttons' );
}
function wptuts_add_buttons( $plugin_array ) {
$plugin_array['wptuts'] = get_template_directory_uri() . '/wptuts-editor-buttons/wptuts-plugin.js';
return $plugin_array;
}
function wptuts_register_buttons( $buttons ) {
array_push( $buttons, 'dropcap', 'showrecent' ); // dropcap', 'recentposts
return $buttons;
}
require( 'wptuts-editor-buttons/wptuts.php' );
Create a folder in your theme root file named wptuts-editor-buttons
Then create a file in wptuts-editor-buttons named wptuts.php and paste the code
<?php
add_shortcode( 'recent-posts', 'wptuts_recent_posts' );
function wptuts_recent_posts( $atts ) {
extract( shortcode_atts( array(
'numbers' => '5',
), $atts ) );
$rposts = new WP_Query( array( 'posts_per_page' => $numbers, 'orderby' => 'date' ) );
if ( $rposts->have_posts() ) {
$html = '<h3>Recent Posts</h3><ul class="recent-posts">';
while( $rposts->have_posts() ) {
$rposts->the_post();
$html .= sprintf(
'<li>%s</li>',
get_permalink($rposts->post->ID),
get_the_title(),
get_the_title()
);
}
$html .= '</ul>';
}
wp_reset_query();
return $html;
}
Also, You need to create a js file in wptuts-editor-buttons > wptuts-plugin.js and paste the code
(function() {
tinymce.create('tinymce.plugins.Wptuts', {
init : function(ed, url) {
ed.addButton('dropcap', {
title : 'DropCap',
cmd : 'dropcap',
image : url + '/dropcap.jpg'
});
ed.addButton('showrecent', {
title : 'Add recent posts shortcode',
cmd : 'showrecent',
image : url + '/images.jpg'
});
ed.addCommand('dropcap', function() {
var selected_text = ed.selection.getContent();
var return_text = '';
return_text = '<span class="dropcap">' + selected_text + '</span>';
ed.execCommand('mceInsertContent', 0, return_text);
});
ed.addCommand('showrecent', function() {
var number = prompt("How many posts you want to show ? "),
shortcode;
if (number !== null) {
number = parseInt(number);
if (number > 0 && number <= 20) {
shortcode = '[recent-post number="' + number + '"/]';
ed.execCommand('mceInsertContent', 0, shortcode);
}
else {
alert("The number value is invalid. It should be from 0 to 20.");
}
}
});
},
// ... Hidden code
});
// Register plugin
tinymce.PluginManager.add( 'wptuts', tinymce.plugins.Wptuts );
})();
Whole the Solution I followed the article
https://code.tutsplus.com/tutorials/guide-to-creating-your-own-wordpress-editor-buttons--wp-30182

How to rename the Add to Cart button if the product is already added to cart in WooCommerce

When Ajax add to cart functionality is active on my WooCommerce store, on Ajax add to cart first click It shows a checked icon symbol like:
The code below changes the add to button cart text to "Seçildi !" if product is already in to cart, only after refreshing page like:
//Rename the button on the Product page
add_filter( 'woocommerce_product_single_add_to_cart_text', 'ts_product_add_cart_button' );
function ts_product_add_cart_button( $label ) {
foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
$product = $values['data'];
if( get_the_ID() == $product->get_id() ) {
$label = __('Seçildi !', 'woocommerce');
}
}
return $label;
}
//Rename the button on the Shop page
add_filter( 'woocommerce_product_add_to_cart_text', 'ts_shop_add_cart_button', 99, 2 );
function ts_shop_add_cart_button( $label, $product ) {
if ( $product->get_type() == 'simple' && $product->is_purchasable() && $product->is_in_stock() )
{
foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if( get_the_ID() == $_product->get_id() ) {
$label = __('Seçildi !', 'woocommerce');
}
}
}
return $label;
}
But if you don't refresh the page the button remains like before with the checked icon symbol.
What I would like is to change add to cart button with the quantity that has been added for this product like:
Is this possible? What do I need to change? Any help is appreciated.
You can use WC woocommerce_product_add_to_cart_text action hook and you can get wc cart loop through all products and compare path second params $prodcuct object. check below code. code will go active theme functions.php file.
function change_add_to_cart_text_if_product_already_in_cart( $add_to_cart_text, $product ) {
if ( WC()->cart ) {
$cart = WC()->cart; // Get cart
if ( ! $cart->is_empty() ) {
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
$_product_id = $cart_item['product_id'];
if ( $product->get_id() == $_product_id ) {
$add_to_cart_text = '('.$cart_item['quantity'].')'.' Already in cart';
break;
}
}
}
}
return $add_to_cart_text;
}
add_filter( 'woocommerce_product_add_to_cart_text', 'change_add_to_cart_text_if_product_already_in_cart', 10, 2 );
add_filter( 'woocommerce_product_single_add_to_cart_text', 'change_add_to_cart_text_if_product_already_in_cart', 10, 2 );
Updated ( as per OP request how to change text quick on click with quantity ).
There is two way You can do this.
you can use woocommerce_loop_add_to_cart_args and add product qty attribute and based on that you can display.
function add_product_qty( $args, $product ){
if ( WC()->cart ) {
$cart = WC()->cart; // Get cart
if ( ! $cart->is_empty() ) {
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
$_product_id = $cart_item['product_id'];
if ( $product->get_id() == $_product_id ) {
$args['attributes']['data-product-qty'] = $cart_item['quantity'];
}else{
$args['attributes']['data-product-qty'] = 0;
}
}
}else{
$args['attributes']['data-product-qty'] = 0;
}
}
return $args;
}
add_filter( 'woocommerce_loop_add_to_cart_args', 'add_product_qty', 10, 2 );
add_action( 'wp_footer', 'ajax_button_text_quick_change_js_script' );
function ajax_button_text_quick_change_js_script() {
?>
<script>
(function($) {
$(document.body).on('click', '.ajax_add_to_cart', function(event){
$this = $(this);
var product_qty = parseInt($this.attr('data-product-qty')) + 1;
$this.attr('data-product-qty',product_qty);
var buttonText = '<span class="add_to_cart_text product-is-added">('+product_qty+') Already in cart</span><i class="cart-icon pe-7s-cart"></i>';
$this.html(buttonText).attr('data-tip','('+product_qty+') Already in cart');
});
})(jQuery);
</script>
<?php
}
You can use added_to_cart jQuery event that triggers after adding to the cart you call ajax and get add_to_cart_text in response.
add_action( 'wp_footer', 'ajax_button_text_js_script' );
function ajax_button_text_js_script() {
?>
<script>
(function($) {
$(document.body).on('added_to_cart', function(event, fragments, cart_hash, button){
var product_id = button.data('product_id'),
product_qty = button.data('quantity');
button.addClass('loading');
$.ajax({
url: "<?php //echo admin_url('admin-ajax.php'); ?>",
method: 'POST',
data:{action:'change_add_to_cart_text',product_id:product_id},
dataType: "json",
success: function( response ){
var buttonText = '<span class="add_to_cart_text product-is-added">'+response.data.button_text+'</span><i class="cart-icon pe-7s-cart"></i>';
button.html(buttonText).attr('data-tip',response.data.button_text);
button.removeClass('loading');
},error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
},
});
});
})(jQuery);
</script>
<?php
}
add_action('wp_ajax_change_add_to_cart_text', 'change_add_to_cart_text');
add_action('wp_ajax_nopriv_change_add_to_cart_text', 'change_add_to_cart_text');
function change_add_to_cart_text(){
$product_id = $_POST['product_id'];
if ( WC()->cart ) {
$cart = WC()->cart; // Get cart
if ( ! $cart->is_empty() ) {
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
$_product_id = $cart_item['product_id'];
if ( $product_id == $_product_id ) {
$add_to_cart_text = '('.$cart_item['quantity'].')'.' Already in cart';
break;
}
}
}
}
wp_send_json_success(array(
'button_text' => $add_to_cart_text
));
}
This below code only for OP site.
add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_add_quantity_fields', 99, 2 );
function custom_add_quantity_fields($html, $product) {
//add quantity field only to simple products
if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
if ( WC()->cart ) {
$cart = WC()->cart; // Get cart
if ( ! $cart->is_empty() ) {
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
$_product_id = $cart_item['product_id'];
if ( $product->get_id() == $_product_id ) {
$data_product_qty = $cart_item['quantity'];
}else{
$data_product_qty = 0;
}
}
}else{
$data_product_qty = 0;
}
}
//rewrite form code for add to cart button
$html = '<form action="' . esc_url( $product->add_to_cart_url() ) . '" class="cart" method="post" enctype="multipart/form-data">';
$html .= woocommerce_quantity_input( array(), $product, false );
$html .= '<button type="submit" data-quantity="1" data-product_id="' . $product->get_id() . '" class="button alt ajax_add_to_cart add_to_cart_button product_type_simple" data-product-qty="'.$data_product_qty.'">' . esc_html( $product->add_to_cart_text() ) . '</button>';
$html .= '</form>';
}
return $html;
}
Tested and works.

how convert simple form submit to ajax submit without loading page like add product to cart function

how convert simple form submit to ajax submit without loading page like add the product to cart function
`
">
">
<button type="submit" name="addift_add_wl_btn_popup">Add to Wishlist</button>
</form>
session
public function addify_get_sectiuon_btn() {
$wl_p_id = '';
if ( isset( $_POST['addift_add_wl_btn_popup'] ) ) {
if ( isset( $_POST['addify_wl_product_id'] ) ) {
$addify_add_to_wl_pro = sanitize_text_field( wp_unslash( $_POST ['addify_wl_product_id'] ) );
}
$addify_wl_var1 = array();
$addify_wl_var1 = WC()->session->get( 'addify_section_name' );
if ( !empty( $addify_wl_var1) ) {
$addify_wl_var2 =$addify_add_to_wl_pro;
array_push( $addify_wl_var1 ,$addify_wl_var2);
WC()->session->set( 'addify_section_name', $addify_wl_var1 );
} else {
WC()->session->set( 'addify_section_name', array($addify_add_to_wl_pro) );
}
// WC()->session->set( 'addify_section_name', null );
}
}
#In jQuery#
listen to form submit and attach this code.
Remember to add event.preventDefault()'
$.post(
ajaxurl,
{ action: 'action_registered_by_add_action', addift_add_wl_btn_popup: addift_add_wl_btn_popup, addify_wl_product_id:addify_wl_product_id },
function( response ) {
//do something
}
);
#In PHP#
//register ajax
add_action( 'wp_ajax_ACTION_NAME', function(){
//base stufs here
} );
```--
###or###
add_action( 'wp_ajax_ACTION_NAME', [$this, 'method'] );
##EDITED##
//add this register to handle both logged in and not logged in users
//add_action( 'wp_ajax_addify_get_sectiuon_btn',array( $this, 'addify_get_sectiuon_btn'));
//add_action( 'wp_ajax_nopriv_addify_get_sectiuon_btn',array( $this, 'addify_get_sectiuon_btn'));
( function ( $ ) {
$( function () {
$( document ).ready( function ( $ ) {
jQuery( '.addift_add_wl_btn_popup_class' ).click( function () {
alert( "ok" );
} );
$( '.addift_add_wl_btn_popup_class' ).click( function ( event ) {
event.preventDefault(); //prevent default behaviour - you have must add function param named `event`
/*
* if its *.js file you must localize script to add variable see more https://wordpress.stackexchange.com/a/190299
* if its *.php file you can do this dirty inline php inside script
*/
let ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ) ?>"; // wp ajax url obtain by wc helper {{ admin_url( 'admin-ajax.php' ) }}
let addift_add_wl_btn_popup = $('#addift_add_wl_btn_popup').val(); // or anything else - value taken from form
let addify_wl_product_id = $('#addify_wl_product_id').val(); // or anything else - value taken from form
$.post( ajaxurl, {
action: 'addify_get_sectiuon_btn',
addift_add_wl_btn_popup: addift_add_wl_btn_popup,
addify_wl_product_id: addify_wl_product_id
},
function ( response ) {
//do something s
} );
} );
} );
} );
} )( jQuery );
my jquery
hook
add_action( 'wp_ajax_addify_get_sectiuon_btn',array( $this, 'addify_get_sectiuon_btn'));
hook call back is
public function addify_get_sectiuon_btn() {
$wl_p_id = '';
if ( isset( $_POST['addift_add_wl_btn_popup'] ) ) {
if ( isset( $_POST['addify_wl_product_id'] ) ) {
$addify_add_to_wl_pro = sanitize_text_field( wp_unslash( $_POST ['addify_wl_product_id'] ) );
}
$addify_wl_var1 = array();
$addify_wl_var1 = WC()->session->get( 'addify_section_name' );
if ( !empty( $addify_wl_var1) ) {
$addify_wl_var2 =$addify_add_to_wl_pro;
array_push( $addify_wl_var1 ,$addify_wl_var2);
WC()->session->set( 'addify_section_name', $addify_wl_var1 );
} else {
WC()->session->set( 'addify_section_name', array($addify_add_to_wl_pro) );
}
// WC()->session->set( 'addify_section_name', null );
}
}

Checkbox field that add a subscription product and change prices of other products

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

WordPress page shows shortcodes

My WordPress page shows shortcodes like [vc_row][vc_column][vc_column_text] .
Help me identify the root cause.
I have migrated the wordpress sql files from one host to another.
You could modify this Utility Script Runner script to remove shortcodes that no longer exist but are in your page content. Definitely do this on staging before you do it on live. high likelyhood of wrecking up the place. This script has been sitting for close to a year and I honestly can't remember if any of it doesn't work as expected. test a lot on staging before running this on anything you really care about.
<?php if(!defined('ABSPATH')) { die(); }
/**
* Utility Name: Remove and Flatten Shortcodes
* Description: Strip Shortcodes from all posts, with several processing options
* Supports: input
* Version: 0.0.2
**/
if (!class_exists('StripShortcodes')) {
class StripShortcodes {
var $wrappers = array(),
$swaps = array();
public static function Instance() {
static $instance = null;
if ($instance === null) {
$instance = new self();
}
return $instance;
}
public function __construct() {
add_filter('wp_util_script', array($this, 'strip_shortcodes_run'), 10, 3);
add_filter('wp_util_input_html', array($this, 'strip_shortcodes_input_html'));
}
public function strip_shortcodes_input_html( $html ) {
global $shortcode_tags;
$post_types = get_post_types( array(
'exclude_from_search' => false
), 'names' );
$post_types = array_diff( $post_types, array( 'revision', 'attachment' ) );
?>
<p>
<strong>WARNING! DO NOT RUN THIS ON A LIVE SITE!</strong><br>
This utility may cause data loss. Even restoring a backup may wipe out any changes since the last run of this utility.
</p>
<label>
<input type="checkbox" name="restore" value="restore"/>
<span>Restore From Backup</span>
</label>
<label>
<span>Post Types to Process</span>
<select name="post_types[]" multiple="multiple">
<option value="none" selected="selected">none</option>
<option value="any">all</option>
<?php
foreach( $post_types as $post_type ) {
echo '<option value="' . esc_attr( $post_type ) . '">' . $post_type . '</option>';
}
?>
</select>
</label>
<hr/>
<p>
Select what you would like to do with each shortcode.
</p>
<?php
if( !empty( $shortcode_tags ) ) {
foreach( $shortcode_tags as $tag => $callable ) {
?>
<div class="shortcode-options-wrapper">
<label>
<span>[<?php echo $tag; ?>]</span>
<select class="shortcode-select" name="shortcodes[<?php echo esc_attr( $tag ); ?>]"/>
<option value="skip">Skip (do not process)</option>
<option value="strip">Remove (deletes shortcode content)</option>
<option value="unwrap">Unwrap Content</option>
<option value="parse">Flatten (parses to HTML)</option>
<option value="swap">Swap (Replace with another shortcode)</option>
</select>
</label>
</div>
<?php
}
}
echo $this->build_form_script();
return ob_get_clean();
}
private function build_form_script () {
global $shortcode_tags;
ob_start(); ?>
<script type="text/javascript">
(jQuery)(function($) {
'use strict';
var unwrap = '<div class="wrap-wrapper"><p>Wrapper for content (use "sprintf()" formatting, including the %s for the content)</p><label>Wrapper<input class="shortcode-wrap"></label></div>';
var swap = '<div class="swap-wrapper"><select class="shortcode-swap"><?php foreach ($shortcode_tags as $tag => $callable) { echo '<option value="' . $tag . '">' . esc_attr($tag) . '</option>'; }?></select></div>'
$(document).on('change', '.shortcode-select', function () {
var $this = $(this);
var name = $this.attr('name');
if ($this.val() == 'unwrap') {
$this.closest('.shortcode-options-wrapper').append(unwrap);
$this.closest('.shortcode-options-wrapper').find('.shortcode-wrap').attr('name', 'wrap_' + name);
$this.closest('.shortcode-options-wrapper').find('.swap-wrapper').remove();
}
else if ($this.val() == 'swap') {
$this.closest('.shortcode-options-wrapper').append(swap);
$this.closest('.shortcode-options-wrapper').find('.shortcode-swap').attr('name', 'swap_' + name);
$this.closest('.shortcode-options-wrapper').find('.wrap-wrapper').remove();
} else {
$this.closest('.shortcode-options-wrapper').find('.wrap-wrapper').remove();
$this.closest('.shortcode-options-wrapper').find('.swap-wrapper').remove();
}
})
});
</script>
<?php return ob_get_clean();
}
public function strip_shortcodes_run( $legacy, $state, $atts ) {
$batch = 10;
$offset = 0;
if( !empty( $state['offset'] ) ) {
$offset = $state['offset'];
}
$result = array(
'state' => 'error',
'message' => 'an unknown error has occurred',
);
$post_types = 'none';
if( !empty( $atts['post_types'] ) && !in_array( 'none', $atts['post_types'] ) ) {
$post_types = $atts['post_types'];
}
$shortcode_settings = array();
if( !empty( $atts['shortcodes'] ) ) {
$shortcode_settings['core'] = $atts['shortcodes'];
$shortcode_settings['wrap'] = $atts['wrap_shortcodes'];
$shortcode_settings['swap'] = $atts['swap_shortcodes'];
}
$restore = true;
if( empty( $atts['restore'] ) ) {
$this->replace_shortcode_functions( $shortcode_settings );
$restore = false;
}
$query = new WP_Query( array(
'posts_per_page' => $batch,
'offset' => $offset,
'post_type' => $post_types
) );
if( !$query->have_posts() ) {
$result = array(
'state' => 'complete',
'message' => 'successfully processed all posts'
);
} else {
$offset += $query->post_count;
while( $query->have_posts() ) {
$query->the_post();
$post = get_post();
$backup = get_post_meta( $post->ID, 'flatten_shortcodes_backup', true );
if( $restore ) {
if( $backup ) {
$post->post_content = $backup;
wp_update_post( $post );
delete_post_meta( $post->ID, 'flatten_shortcodes_backup' );
}
} else {
if( !$backup ) {
update_post_meta( $post->ID, 'flatten_shortcodes_backup', $post->post_content );
}
$post->post_content = do_shortcode( $post->post_content );
wp_update_post( $post );
}
}
$result = array(
'state' => array(
'offset' => $offset
),
'message' => $offset . ' posts processed'
);
}
return $result;
}
private function replace_shortcode_functions( $settings = array() ) {
global $shortcode_tags;
foreach( $shortcode_tags as $tag => $callable ) {
$setting = 'skip';
if( !empty( $settings['core'][$tag] ) ) {
$setting = $settings['core'][$tag];
}
switch( $setting ) {
case 'strip' :
$shortcode_tags[$tag] = "__return_empty_string";
break;
case 'unwrap':
$shortcode_tags[$tag] = array($this, 'replace_shortcode_unwrap');
$this->wrappers[$tag] = $settings['wrap'][$tag];
break;
case 'parse' :
// nothing needed
break;
case 'swap' :
$shortcode_tags[$tag] = array($this, 'swap_shortcode');
$this->swaps[$tag] = $settings['swap'][$tag];
break;
case 'skip' :
default :
unset( $shortcode_tags[$tag] );
}
}
}
public function replace_shortcode_unwrap( $atts=array(), $content='', $tag ) {
return sprintf($this->wrappers[$tag], $content);
}
public function swap_shortcode( $atts=array(), $content='', $tag ) {
$attString = '';
$newTag = $this->swaps[$tag];
if (!empty($atts)) {
foreach ($atts as $key => $att) {
$attString .= ' ' . $key . '="' . $att . '"';
}
}
$output = '[' . $newTag . $attString . ']';
if ($content) {
$output .= $content . '[/' . $newTag . ']';
}
return $output;
}
}
StripShortcodes::Instance();
}
I have got same result. My theme is wp baker. I activated edge core plugin and other required plug ins and it was solved.

Resources