Update a text when cart is not empty - wordpress

I have a banner on my Wordpress website that I want to be updated when the cart is not empty by Ajax.
Here is the non Ajaxified version:
function dynamic_banner() {
$atts = '<div class="woofc-shipping">' . alg_wc_get_left_to_free_shipping('<span style="color:#F79917"><i class="fas fa-shipping-fast" style="margin-left: 5px;"></i>Add %amount_left_for_free_shipping% more for Free shipping</span> <div class="woofc-total-right"></div>') . '</div>';
if ( ! WC()->cart->is_empty() ) {
?>
<script>
jQuery(function($){
$(".ban-text").replaceWith('<?php echo $atts; ?>')});
</script>
<?php
}
}
add_action('wp_head', 'dynamic_banner');
This is the HTML
<div class="head_strip over--hide" style="display: block;">
<p><strong>Free fast delivery*</strong> in purchases over <span class="special-price">295 NIS</span> even during the closure period!</span></p>
</div>

Have found a solution thanks to those threads by LoicTheAztec
Functions.php Code:
// Shortcode for the banner
function display_free_shipping_progress() {
return get_free_shipping_progress();
}
add_shortcode('fs_progress', 'display_free_shipping_progress');
// Function that makes calculations and display
function get_free_shipping_progress() {
$atts = '<div class="woofc-shipping">' . alg_wc_get_left_to_free_shipping('<span style="color:#F79917"><i class="fas fa-shipping-fast" style="margin-left: 5px;"></i>הוסיפי עוד %amount_left_for_free_shipping% למשלוח חינם</span> <div class="woofc-total-right"></div>') . '</div>';
$prodgress = WC()->cart->total;
//Check if cart has something else show default
if( $prodgress > 0 ) {
return '<div class="head_strip over--hide" style="display: block;">' . $atts . '</div>';
} else {
return '<div class="head_strip over--hide" style="display: block;"><span class="ban-text"><strong>*משלוח מהיר חינם</strong > בקניה מעל<span class="special-price">295₪</span> גם בתקופת הסגר!</span></div>';
}
}
// Refreshing "free shipping" progress on cart ajax events
add_filter( 'woocommerce_add_to_cart_fragments', 'refresh_free_shipping_progress' );
function refresh_free_shipping_progress( $fragments ){
$fragments['.head_strip'] = get_free_shipping_progress();
return $fragments;
}
Have passed all HTML needed to shortcode for simplicity like was recommended.

Related

Why is the filter the_title not working when the_content is working fine?

Function and filter to display a player post titles:
function wpb_after_post_content($content){
if (is_single()) {
$id=get_the_ID();
$post_meta=get_post_meta(get_the_ID(), 'enclosure', TRUE);
$mp3=explode('.mp3',$post_meta);
$title=get_the_title();
if(count($mp3)>1)
{
$player = '<div class="post_player">' . do_shortcode('[fap_track url="'.trim($mp3[0]).'.mp3" title=url="'.$title.'" share="" cover="" meta="" layout="list" enqueue=no auto_enqueue=yes]')."</div>";
$content=$player.$content;
}
}
if (is_single()) {
$id=get_the_ID();
$post_meta=get_post_meta(get_the_ID(), 'enclosure', TRUE);
$mp3=explode('.mp3',$post_meta);
$title=get_the_title();
if(count($mp3)>1)
{
$player = '<div class="zoomsounds_player">'. do_shortcode('[zoomsounds_player source="'.trim($mp3[0]).'.mp3" play_in_footer_player="on" config="default" artistname="'.get_post_meta($id, 'arxiu_de_so', true).'" config="" ]');
/**if (wp_is_mobile())*/ {
if(get_post_meta($id, 'arxiu_de_so', true)!=""){
/** $player .= " <p id='arxiu_so'> Arxiu de so: ".get_post_meta($id, 'arxiu_de_so', true)."</p>";*/
/**$player .= '<span id="arxiuVal" style="opacity:1"> '.get_post_meta($id, 'arxiu_de_so', true).'</span>';*/
}
}
$player .="</div>";
$content=$player.$content;
}
}
return $content;
}
add_filter( "the_content", "wpb_after_post_content" );
The above code works fine with the_content filter and displays the player below the featured image. However, when I use this function with the the_title filter, the page doesn't load at all. The reason I want to use the_title is because I want the player to display above the featured image but below the post title.
Screenshot:-
This screenshot is to show that with the_content the player displays however it displays below post image.
Please have a look as below:
If you want to use the_title(), then you no need to pass the post_id in the the_title(), we have some params for the_title() if you want to add them like as below:
$before
(string) (Optional) Markup to prepend to the title.
Default value: ''
$after
(string) (Optional) Markup to append to the title.
Default value: ''
$echo
(bool) (Optional) Whether to echo or return the title. Default true for the echo.
Default value: true
If you want to use get_the_title(), then you must need to pass post_id inside the get_the_title($postId);
According to your code snippet, you must update your code with as below for get_the_title():
<?php
function wpb_after_post_content($content){
if (is_single()) {
$id=get_the_ID();
$post_meta=get_post_meta(get_the_ID(), 'enclosure', TRUE);
$mp3=explode('.mp3',$post_meta);
$title=get_the_title($id);
if(count($mp3)>1) {
$player = '<div class="post_player">' . do_shortcode('[fap_track url="'.trim($mp3[0]).'.mp3" title=url="'.$title.'" share="" cover="" meta="" layout="list" enqueue=no auto_enqueue=yes]')."</div>";
$content=$player.$content;
}
}
return $content;
}
add_filter( "the_content", "wpb_after_post_content" );
?>
And for the the_title(), you should update your code with as below:
<?php
function wpb_after_post_content($content){
if (is_single()) {
$id=get_the_ID();
$post_meta=get_post_meta(get_the_ID(), 'enclosure', TRUE);
$mp3=explode('.mp3',$post_meta);
$title=get_the_title();
if(count($mp3)>1)
{
$player = '<div class="post_player">' . do_shortcode('[fap_track url="'.trim($mp3[0]).'.mp3" title=url="'.the_title().'" share="" cover="" meta="" layout="list" enqueue=no auto_enqueue=yes]')."</div>";
$content=$player.$content;
}
}
return $content;
}
add_filter( "the_content", "wpb_after_post_content" );
?>
NOTE: You have not declared the title parameter in the zoomsounds_player shortcode so please pass and update accordingly.
I hope it would help you out.

Woocommerce 3 Filter Single Variation Add to cart button html

In Woocommerce 3.0 the single variation add to cart button is wrapped in a container div:
<div class="woocommerce-variation-add-to-cart variations_button">
// do_actions for before and after add_to_cart_quantity
</div>
I'd like to filter the html to remove the container div without overriding the variation-add-to-cart-button.php template file and without jquery/javascript.
Any help would be great!
Please try the following code. I haven't tested it but it supposed to work. Please try this on your dev environment first.
add_action( 'woocommerce_before_template_part', function( $template_name ) {
if ( 'single-product/add-to-cart/variation-add-to-cart-button.php' === $template_name ) {
ob_start();
}
} );
add_action( 'woocommerce_after_template_part', function( $template_name ) {
if ( 'single-product/add-to-cart/variation-add-to-cart-button.php' === $template_name ) {
$content = ob_get_clean();
$content = str_replace( '<div class="woocommerce-variation-add-to-cart variations_button">', '', $content );
$content = str_replace( '</div>', '', $content );
echo $content;
}
} );

Create defaults to use in return in shortcode - Wordpress plugin

I'm making my first plugin to Wordpress which adds a shortcode that I can use in my header.
The plugin integrates with Wordpress option page. All admin related works fine including writing top wp_options table and/or delete/update fields.
My problem is in the custom shortcode itself (at the bottom).
What I want to achieve is, when get_option('bfcsc_logout_link') is not set in admin, a default value should be returned.
And of course, I am looking for the 'nice way', so my code looks good as well :) When the plugin works as I want to in the end, I'm thinking about taking it a step further and separate the code into init files etc, making it more professional.
Below is the full code (excluding assets):
<?php
/*
Plugin Name: Brokenfruit Custom Login Shortcode
Plugin URI: https://www.brokenfruit.dk/
Description: Adds custom login shortcode for Brokenfruit
Version: 1.0
Author: Kenn Nielsen
Author URI: https://www.brokenfruit.dk/
License: GPL
*/
// Meaning of abbreviations:
// bfclsc = brokenfruit custom login shortcode
/* Register styles and scripts */
function bfcsc_enqueue_scripts() {
global $wpdb;
$screen = get_current_screen();
if ( $screen->id != 'settings_page_brokenfruit-custom-shortcodes' )
return; // exit if incorrect screen id
wp_enqueue_style( 'brokenfruit-shortcodes-styles', plugins_url( '/css/styles.css', __FILE__ ) );
wp_enqueue_style( 'bootstrap', plugins_url( '/css/bootstrap.css', __FILE__ ) );
wp_enqueue_script('admin_js_bootstrap_hack', plugins_url( '/scripts/bootstrap-hack.js', __FILE__ ), false, '1.0.0', false);
}
add_action('admin_enqueue_scripts', 'bfcsc_enqueue_scripts' );
/* Runs when plugin is activated */
register_activation_hook(__FILE__,'bfcsc_install');
/* Runs on plugin deactivation*/
register_deactivation_hook( __FILE__, 'bfcsc_remove' );
function bfcsc_install() {
/* Creates new database field */
add_option('bfcsc_logout_link', '', '', 'yes');
add_option('bfcsc_login_link', '', '', 'yes');
add_option('bfcsc_account_link', '', '', 'yes');
}
function bfcsc_remove() {
/* Deletes the database field */
delete_option('bfcsc_logout_link');
delete_option('bfcsc_login_link');
delete_option('bfcsc_account_link');
}
if (is_admin() ) {
function add_bfcsc_option_page() {
add_options_page(
'Brokenfruit Custom Shortcodes', // The text to be displayed in the title tag
'Brokenfruit Custom Shortcodes', // The text to be used for the menu
'administrator', // The capability required to display this menu
'brokenfruit-custom-shortcodes', // The unique slug name to refer to this menu
'bfcsc_html_page'); // The function tooutput the page content
}
/* Call the html code */
add_action('admin_menu', 'add_bfcsc_option_page');
}
function bfcsc_html_page(){
?>
<form method="post" action="options.php">
<?php wp_nonce_field('update-options'); ?>
<div class="bootstrap-wrapper">
<div class="row top-buffer">
<div class="col-md-8">
<div><h1>Brokenfruit Custom Login Shortcode</h1></div>
<p>Til brug for shortcode:<br/><span class="shortcode-preview">[custom_login]</span></p>
<div class="top-buffer"></div>
<h5>Link til log ud:</h5><input placeholder="Eksempel: wp-login.php?action=logout" class="form-control" name="bfcsc_logout_link" type="text" id="bfcsc_logout_link" value="<?php echo get_option('bfcsc_logout_link'); ?>" /></td>
<div class="top-buffer"></div>
<h5>Link til log ind:</h5><input placeholder="Eksempel: /log-ind/" class="form-control" name="bfcsc_login_link" type="text" id="bfcsc_login_link" value="<?php echo get_option('bfcsc_login_link'); ?>" /></td>
<div class="top-buffer"></div>
<h5>Link til min konto:</h5><input placeholder="Eksempel: /min-brokenfruit/" class="form-control" name="bfcsc_account_link" type="text" id="bfcsc_account_link" value="<?php echo get_option('bfcsc_account_link'); ?>" /></td>
<input type="hidden" name="action" value="update" />
<input type="hidden" name="page_options" value="bfcsc_logout_link,bfcsc_login_link,bfcsc_account_link" />
<input class="btn btn-primary top-buffer" type="submit" value="<?php _e('Save Changes') ?>" />
</div>
</div>
</div>
</form>
<?php
}
/*---------------------------------------------------*/
/* Custom login shortcode - start */
/*---------------------------------------------------*/
function mydefaults (){
if (!get_option('bfcsc_logout_link')){
$logout_link = '/log-ud/';
} else {
$logout_link = get_option('bfcsc_logout_link');
}
if (!get_option('bfcsc_login_link')){
$login_link = '/log-ind';
} else {
$login_link = get_option('bfcsc_login_link');
}
if (!get_option('bfcsc_account_link')){
$account_link = '/min-brokenfruit/';
} else {
$account_link = get_option('bfcsc_account_link');
}
}
function custom_login_shortcode ( $atts ){
if ( is_user_logged_in() ) {
return '<i class="fa icon-user"></i>Mit Brokenfruit | <i class="fa icon-logout"></i>Log ud';
} else {
return '<i class="fa icon-login"></i>Log ind';
}
}
add_shortcode( 'custom_login', 'custom_login_shortcode' );
/*---------------------------------------------------*/
/* Custom login shortcode - end */
/*---------------------------------------------------*/
?>
Thank you all in advance!
Cheers Kenn
Correct. Your variable was not available inside that method.
As to the parameters, the shortcode api is not meant to work like that. The lone parameter $atts is used to pass the variables you need from the shortcode (the part inside the bracket) as an array.
I'm not sure how you're planning to use the shortcode. But you could pass your parameters with
[custom_login login='different_login' ]
then pick them up in the shortcode in the $atts array:
function custom_login_shortcode ( $atts ){
$a = shortcode_atts( array(
'login' => '/log-ind/', // default value for login
'account' => '/min-brokenfruit/', // default value for account
), $atts );
return $a['login']; // returns 'different_login'
return $a['account'] // returns '/min-brokenfruit/'
You could also define your variables as constants (with a global scope) so they are available inside your shortcode and all your methods:
define('MY_LOGIN_LINK','/log-ind');
Then you can use if (!defined('MY_LOGIN_LINK')) to see if you have something to work with. See http://php.net/manual/en/function.define.php for more on that.
But if you only need these values in this one method, this would work in your re-written code to streamline it a little:
$login_link = get_option('bfclsc_login_link','/log-ind/');
get_option() has an optional parameter for a default value:
$no_exists_value = get_option( 'no_exists_value', 'default_value' );
var_dump( $no_exists_value ); /* outputs 'default_value' */
https://codex.wordpress.org/Function_Reference/get_option
I found a solution.
I needed to put the content of function mydefaults into the function custom_login_shortcode. I guess my variables was created in the global state and could not be used?
After all, I don't understand why I could not pass the variables into the shortcode like:
function custom_login_shortcode ( $atts, $logout_link, $login_link, $account_link ){
Below is the working shortcode function:
/*---------------------------------------------------*/
/* Custom login shortcode - start */
/*---------------------------------------------------*/
/*function mydefaults (){
if (!get_option('bfclsc_logout_link')){
$logout_link = '/log-ud/';
} else {
$logout_link = get_option('bfclsc_logout_link');
}
if (!get_option('bfclsc_login_link')){
$login_link = '/log-ind';
} else {
$login_link = get_option('bfclsc_login_link');
}
if (!get_option('bfclsc_account_link')){
$account_link = '/min-brokenfruit/';
} else {
$account_link = get_option('bfclsc_account_link');
}
}*/
function custom_login_shortcode ( $atts ){
if (!get_option('bfclsc_logout_link')){
$logout_link = wp_logout_url( home_url()); //call wordpress logout with home redirect: wp_logout_url( home_url())
} else {
$logout_link = get_option('bfclsc_logout_link');
}
if (!get_option('bfclsc_login_link')){
$login_link = '/log-ind/';
} else {
$login_link = get_option('bfclsc_login_link');
}
if (!get_option('bfclsc_account_link')){
$account_link = '/min-brokenfruit/';
} else {
$account_link = get_option('bfclsc_account_link');
}
if ( is_user_logged_in() ) {
return '<i class="fa icon-user"></i>Mit Brokenfruit | <i class="fa icon-logout"></i>Log ud';
} else {
return '<i class="fa icon-login"></i>Log ind';
}
}
add_shortcode( 'custom_login', 'custom_login_shortcode' );
/*---------------------------------------------------*/
/* Custom login shortcode - end */
/*---------------------------------------------------*/

How to remove redundant <p> and <br/> from the result of WordPress shortcode

I use shortcode to output the following html in a variable, but there are too many redundant code such as br and p tags, how to remove them? Thanks!
My shortcode function:
add_shortcode('portfolios', 'van_portfolios_shortcode');
function van_portfolios_shortcode( $atts, $content) {
extract(shortcode_atts(array(
'number'=>'9',
'slug'=>''
), $atts));
$str=van_portfolios($slug,$number,false);
return $str;
}
function van_process_shortcode($content) {
global $shortcode_tags;
// Backup current registered shortcodes and clear them all out
$orig_shortcode_tags = $shortcode_tags;
$shortcode_tags = array();
add_shortcode('portfolios', 'van_portfolios_shortcode');
// Do the shortcode (only the one above is registered)
$content = do_shortcode($content);
// Put the original shortcodes back
$shortcode_tags = $orig_shortcode_tags;
return $content;
}
add_filter('the_content', 'van_process_shortcode', 7);
Correct makeup is
<div class="portfolio-item">
<a class="overlay" href="#">
<h3>...</h3>
<p>...</p>
</a>
<div class="tools">ZoomInInfo</div>
...
</div>
Output:
<div class="portfolio-item">
<a class="overlay" href="#">
<br /><!--This <br />is redundant code-->
<h3>...</h3>
<p>...</p><p><!--This <p> is redundant code-->
</a>
<div class="tools">ZoomInInfo</div>
<p><!--This <p> is redundant code-->...
</div>
Try adding this code before content is displayed:
UPDATED
// From your question
$content = do_shortcode($content);
// Put the original shortcodes back
$shortcode_tags = $orig_shortcode_tags;
// Add this code
$content = preg_replace( '%<p> \s*</p>%', '', $content ); // Remove all instances of "<p> </p>" to avoid extra lines.
$Old = array( '<br />', '<br>' );
$New = array( '','' );
$content = str_replace( $Old, $New, $content );
// From your question
return $content;

When I move a Wordpress custom option menu to the top level it stop saving input settings?

This code adds a menu in the Settings section of Wordpress' administrator
Right now add_options_page is declared, so the custom menu appears inside Settings
I changed add_options_page to add_menu_page in order to bring that menu to the top-level, but then it stopped working (when I click the custom menu opens, but can't save settings anymore).
What's the remaining code I have to change in order to make this work?
Thanks in advance!
<?php
add_action('admin_menu', 'create_theme_options_page');
add_action('admin_init', 'register_and_build_fields');
function create_theme_options_page() {
add_options_page('Theme Options', 'Theme Options', 'administrator', __FILE__, 'options_page_fn');
}
function register_and_build_fields() {
register_setting('plugin_options', 'plugin_options', 'validate_setting');
add_settings_section('main_section', 'Main Settings', 'section_cb', __FILE__);
add_settings_field('color_scheme', 'Color Scheme:', 'color_scheme_setting', __FILE__, 'main_section');
add_settings_field('logo', 'Logo:', 'logo_setting', __FILE__, 'main_section'); // LOGO
add_settings_field('banner_heading', 'Banner Heading:', 'banner_heading_setting', __FILE__, 'main_section');
add_settings_field('adverting_information', 'Advertising Info:', 'advertising_information_setting', __FILE__, 'main_section');
add_settings_field('ad_one', 'Ad:', 'ad_setting_one', __FILE__, 'main_section'); // Ad1
add_settings_field('ad_two', 'Second Ad:', 'ad_setting_two', __FILE__, 'main_section'); // Ad2
}
function options_page_fn() {
?>
<div id="theme-options-wrap" class="widefat">
<div class="icon32" id="icon-tools"></div>
<h2>My Theme Options</h2>
<p>Take control of your theme, by overriding the default settings with your own specific preferences.</p>
<form method="post" action="options.php" enctype="multipart/form-data">
<?php settings_fields('plugin_options'); ?>
<?php do_settings_sections(__FILE__); ?>
<p class="submit">
<input name="Submit" type="submit" class="button-primary" value="<?php esc_attr_e('Save Changes'); ?>" />
</p>
</form>
</div>
<?php
}
// Banner Heading
function banner_heading_setting() {
$options = get_option('plugin_options');
echo "<input name='plugin_options[banner_heading]' type='text' value='{$options['banner_heading']}' />";
}
// Color Scheme
function color_scheme_setting() {
$options = get_option('plugin_options');
$items = array("White", "Black", "#DDDDDD", "#444444");
echo "<select name='plugin_options[color_scheme]'>";
foreach ($items as $item) {
$selected = ( $options['color_scheme'] === $item ) ? 'selected = "selected"' : '';
echo "<option value='$item' $selected>$item</option>";
}
echo "</select>";
}
// Advertising info
function advertising_information_setting() {
$options = get_option('plugin_options');
echo "<textarea name='plugin_options[advertising_information]' rows='10' cols='60' type='textarea'>{$options['advertising_information']}</textarea>";
}
// Ad one
function ad_setting_one() {
echo '<input type="file" name="ad_one" />';
}
// Ad two
function ad_setting_two() {
echo '<input type="file" name="ad_two" />';
}
// Logo
function logo_setting() {
echo '<input type="file" name="logo" />';
}
function validate_setting($plugin_options) {
$keys = array_keys($_FILES);
$i = 0;
foreach ($_FILES as $image) {
// if a files was upload
if ($image['size']) {
// if it is an image
if (preg_match('/(jpg|jpeg|png|gif)$/', $image['type'])) {
$override = array('test_form' => false);
$file = wp_handle_upload($image, $override);
$plugin_options[$keys[$i]] = $file['url'];
} else {
$options = get_option('plugin_options');
$plugin_options[$keys[$i]] = $options[$logo];
wp_die('No image was uploaded.');
}
}
// else, retain the image that's already on file.
else {
$options = get_option('plugin_options');
$plugin_options[$keys[$i]] = $options[$keys[$i]];
}
$i++;
}
return $plugin_options;
}
function section_cb() {}
// Add stylesheet
add_action('admin_head', 'admin_register_head');
function admin_register_head() {
$url = get_bloginfo('template_directory') . '/functions/options_page.css';
echo "<link rel='stylesheet' href='$url' />\n";
}
Supply a proper handle when registering the menu page(fourth parameter).
Add menu example
Add top level menu page
add_menu_page( 'Theme Options', 'Theme Options', 'manage_options', 'my-theme-options', 'options_page_fn' );
Add submenu example
Add a submenu page to the new top level page
add_submenu_page( 'my-theme-options', 'Theme Sub1', 'Theme Sub1', 'manage_options', 'my-theme-options-subpage1', 'my_callback_function' );
Hope that helps..
And please consider posting your future WordPress questions on the WordPress Stack Exchange.
Regarding your main problem though, try updating the do_settings_section call to..
<?php do_settings_sections( 'main_section' ); ?>

Resources