PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label shortcode. Show all posts
Showing posts with label shortcode. Show all posts

Wednesday, August 3, 2022

[FIXED] How to display custom shortcode single image in visual composer in wordpress?

 August 03, 2022     image, shortcode, visual-composer, wordpress     No comments   

Issue

I am trying to display custom fileds created by me in visual composer by using custom short codes. This custom short codes run fine when i am working with heading and text area_html ,but now i want to add single image in this sort code,but in result i am not getting image,it displays alt attribute and in back-end side i am showing my single image that stores in custom shortcode field. here i am including my code.

1) code for creating custom shortcode

vc_map( array(
    'name' => __( 'trionn_header' ),
    'base' => 'trionn_header',
    'category' => ( 'trionn code' ),
    'params' => array(
                "type" => "attach_image",
            "holder" => "img",
            "class" => "",
            "heading" => __( "Hintergrundbild", "my-text-domain" ),
            "param_name" => "image_url",
            "value" => __( "", "my-text-domain" ),
            "description" => __( lade eins hoch", "my-text-domain" )
        )
) );

2) code in separate function-name file

<?php
/* Ordered List shortcode */
if (!function_exists('trionn_header')) {
    function trionn_header($atts, $content) {
           $atts = shortcode_atts(
            array(
                'image_url' => ''
            ), $atts, 'trionn_header'
        );

        $imageSrc = wp_get_attachment_image_src($image_url, 'thumbnail'); 

        $html = '<img src="' . $imageSrc[0] .'" alt="' . $atts['title'] . '"/>';
        return $html;
        }

    add_shortcode('trionn_header', 'trionn_header');
}

Solution

I found solution for your question,try this in your code

In param tag write this array after main param attribute:

array(
                "type" => "attach_image",
                "heading" => "Image",
                "param_name" => "image",
                'admin_label' => true
            )

paste below code in your function_name file:

<?php
// Trionn header custom code // 
if (!function_exists('trionn_header')) {

    function trionn_header($atts, $content = null) {
        $args = array(
            'title' => __( 'This is the custom shortcode' ),
            'title_color' => '#000000',
            'content' => 'your discrption here',
            "image"             => "",
        );

        extract(shortcode_atts($args, $atts));

        //init variables
        $html               = "";
        $image_classes      = "";
        $image_src          = $image;

        if (is_numeric($image)) {
            $image_src = wp_get_attachment_url($image);
        }


        // generate output for heading and discription
        $html = '<h1 class="trionn header ' . $atts['style']. '" style="color: ' . $atts['title_color'] . '">'. $atts['title'] . '</h1>'.   "<div class=content>" . $content . "</div>";

        // generate output for single image
        $html .= "<img itemprop='image' class='{$image_classes}' src='{$image_src}' alt='' style='{$images_styles}' />";

        return $html;
    }
    add_shortcode('trionn_header', 'trionn_header');
}

Enjoy, thank me later



Answered By - Avi
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to create page in backend via WPBakery

 August 03, 2022     backend, shortcode, visual-composer, visual-editor, wordpress     No comments   

Issue

I'm developing a plugin that creates pages for admin menu in backend via WPBakery. But when I look at generated page there is only shortcodes. How can I make plugins shortcodes execute in backend.

I've tried to use echo do_shortcode( '$content' ) but it does not work. I probably should work with plugins classes but do not know how.

I want to make a page with page builder for admin menu and execute all shortcodes that creates rows columns message boxes etc.

Any help would be appreciated.


Solution

Before using do_shortcode, add WPBMap::addAllMappedShortcodes(); function, this function loads all elements, and then do_shortcode should work fine.



Answered By - Павел Иванов
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, May 15, 2022

[FIXED] How to add if and else condition in wordpress shortcode

 May 15, 2022     php, shortcode, wordpress     No comments   

Issue

I have a shortcode showing the username of the current user, it works. What I want to do is insert conditions.

if the user has the username show it, otherwise show first name or something else.

I searched on google and here on stack, I understood this is possible thanks to the if and else conditions but I've never done it, can someone help me understand how I can insert these conditions in my shortcode?

also I would like to show other information as well, such as e-mail, last name, registration date and the like, is there a documentation / list on where to get all these values?

function display_current_username () {
    $user = wp_get_current_user();
    $name = $user->display_name;
    return $user->display_name;
}
add_shortcode('display_name', 'display_current_username');

Solution

If/Else conditionals are a foundational aspect of PHP. It doesn't matter really if it's WP or not, they work the same.

To answer the main question, you would add the conditional like this:

function display_current_username () {

    /* ADDED BASED ON WPEXPERTS ANSWER
       This is a really good check to do to make sure that WP doesn't
       throw an error if wp_get_current_user returns FALSE/0
    */
    if( !is_user_logged_in() ) :
        return 'Something if user isn\'t logged in';
    endif;

    $user = wp_get_current_user();
    $name = $user->display_name;
    
    // If the $name var is empty, return the user_firstname property.
    if ( $name === '' ) :
        return $user->user_firstname;
    endif;
    
    return $name;
}
add_shortcode('display_name', 'display_current_username');

All the documentation for the user data object returnd using wp_get_current_user() can be found here: https://developer.wordpress.org/reference/functions/wp_get_current_user/#comment-437

To get more user data, use the get_userdata() function

You can pass the user id to get all the data:

$user_data = get_userdata( $user->ID );

You can use that in your shortcode as well. Something like this:

function display_current_username () {
    $user = wp_get_current_user();
    $name = $user->display_name;
    $user_data = get_userdata( $user->ID );

    /*
    Do something with the $user_data information
    for example:
    $user_registration_date = $user_data->user_registered;
    */

    
    // If the $name var is empty, return the user_firstname property.
    if ( $name === '' ) :
        return $user->user_firstname;
    endif;
    // This is super basic and is only an example of what you can do.
    return 'User name: ' . $name . "\n\r" . 'User registered: ' . $user_registration_date;
}
add_shortcode('display_name', 'display_current_username');

get_userdata is a wrapper/helper for get_user_by(). Here is the full object returned by get_userdata(): https://developer.wordpress.org/reference/functions/get_user_by/#comment-495

EDIT

Based on question in comment

function display_current_username () {
    $user = wp_get_current_user();
    $display_name = $user->display_name;
    $first_name = $user->user_firstname;
    $name = 'Set Custom Text Here';
    
    // If display name isn't empty;
    if ( $display_name !== '' ) :
        return $display_name;
    endif;

    // If first name isn't empty;
    if ( $first_name !== '' ) :
        return $first_name;
    endif;

     /* THIS COULD ALSO BE USED
     // This just assigns the user properties to the $name var
     // instead of returning.
     if ( $display_name !== '' ) :
        $name = $display_name;
     elseif ( $first_name !== '' ) :
        $name = $first_name;
     endif;
     */
    
    // If it gets to this point, return the custom text.
    return $name;
}
add_shortcode('display_name', 'display_current_username');


Answered By - disinfor
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, May 9, 2022

[FIXED] How to Define Product in WooCommerce Shortcode to use on Custom Order Received Page

 May 09, 2022     php, product, shortcode, woocommerce, wordpress     No comments   

Issue

I am trying to understand how to define product in this code after having made some changes to it based on the answer in my previous question Why does WooCommerce Order Shortcode Generate Plugin Notice on Custom Thank You Page?

The notice message have changed and now it asks me to define product. This is the notice:

Notice: Undefined variable: product in /wp-content/themes/storefront/functions.php on line 842

The notice refers to this line:

'purchase_note' => $product ? $product->get_purchase_note() : '',

This is the full code:

function order_cost_breakdown(){

    if ( isset( $_GET['order_id']) && $_GET['order_id'] > 0 ) {

        $order_id = (int) esc_attr( $_GET['order_id'] );

        $order = wc_get_order( $order_id );

        $order_data = $order->get_data();

        $show_purchase_note    = $order->has_status( apply_filters( 'woocommerce_purchase_note_order_statuses', array( 'completed', 'processing' ) ) );

    ob_start();
    
    ?>

        <div class="woocommerce-account woocommerce-page"><div class="woocommerce">

            <table class="shop_table order_details">

                <thead>

                    <tr>
                        <th class="product-name"><?php _e( 'Product', 'woocommerce' ); ?></th>
                        <th class="product-total"><?php _e( 'Total', 'woocommerce' ); ?></th>

                    </tr>

                </thead>

            <tbody>

        <?php foreach ( $order->get_items() as $item_id => $item ) {

        wc_get_template( 'order/order-details-item.php', array (
        'order' => $order,
        'item_id' => $item_id,
        'item' => $item,
        'product' => apply_filters( 'woocommerce_order_item_product', $item->get_product( $item ), $item ),
        'show_purchase_note' => $show_purchase_note,
        'purchase_note' => $product ? $product->get_purchase_note() : '',
        ) );
        }
    ?>

    <?php do_action( 'woocommerce_order_items_table', $order ); ?>

            </tbody>
        
        <tfoot>

    <?php

        foreach ( $order->get_order_item_totals() as $key => $total ){
    ?>

    <tr>
    
        <th scope="row"><?php echo $total['label']; ?></th>
        <td><?php echo $total['value']; ?></td>
    </tr>

        <?php
    }

    ?>
            </tfoot>
    
        </table>
    
    </div>

</div>

<?php

    return ob_get_clean();
    
    }

}

Any advice is helpful as I am clearly not an expert.


Solution

To fix the notice

Replace

<?php foreach ( $order->get_items() as $item_id => $item ) {

    wc_get_template( 'order/order-details-item.php', array (
    'order' => $order,
    'item_id' => $item_id,
    'item' => $item,
    'product' => apply_filters( 'woocommerce_order_item_product', $item->get_product( $item ), $item ),
    'show_purchase_note' => $show_purchase_note,
    'purchase_note' => $product ? $product->get_purchase_note() : '',
    ) );
    }
?>

With

<?php foreach ( $order->get_items() as $item_id => $item ) {
    $product = $item->get_product();

    wc_get_template( 'order/order-details-item.php', array (
        'order'              => $order,
        'item_id'            => $item_id,
        'item'               => $item,
        'product'            => apply_filters( 'woocommerce_order_item_product', $item->get_product( $item ), $item ),
        'show_purchase_note' => $show_purchase_note,
        'purchase_note'      => $product ? $product->get_purchase_note() : '',
    ));
}       
?>

That should suffice



Answered By - 7uc1f3r
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to display the last ordered product in WooCommerce via a shortcode

 May 09, 2022     orders, product, shortcode, woocommerce, wordpress     No comments   

Issue

I'm looking for a way to display the last ordered product on another page.

I think it would be possible to maybe create a shortcode in the functions that takes the order details and displays them wherever I add the shortcode.

Here is an example of what I mean.


But I can't seem to figure out how to get it to work. So far I got this information to work with:

add_shortcode( 'displaylast', 'last' );
function last(){
    $customer_id = get_current_user_id();
    $order = wc_get_customer_last_order( $customer_id );
    return $order->get_order();
}

[displaylast] is currently showing me noting. It does work when I change get_order() to get_billing_first_name().

That displays the order name. But I can't seem to get the item that was bought. Maybe there is a get_() that I'm not seeing?


Solution

You are close, however you must obtain the last product from the order object.

So you get:

function last() {
    // Not available
    $na = __( 'N/A', 'woocommerce' );
    
    // For logged in users only
    if ( ! is_user_logged_in() ) return $na;

    // The current user ID
    $user_id = get_current_user_id();

    // Get the WC_Customer instance Object for the current user
    $customer = new WC_Customer( $user_id );

    // Get the last WC_Order Object instance from current customer
    $last_order = $customer->get_last_order();
    
    // When empty
    if ( empty ( $last_order ) ) return $na;
    
    // Get order items
    $order_items = $last_order->get_items();
    
    // Latest WC_Order_Item_Product Object instance
    $last_item = end( $order_items );

    // Get product ID
    $product_id = $last_item->get_variation_id() > 0 ? $last_item->get_variation_id() : $last_item->get_product_id();
    
    // Pass product ID to products shortcode
    return do_shortcode("[product id='$product_id']");
} 
// Register shortcode
add_shortcode( 'display_last', 'last' ); 

SHORTCODE USAGE

In an existing page:

[display_last]

Or in PHP:

echo do_shortcode('[display_last]');


Answered By - 7uc1f3r
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, April 12, 2022

[FIXED] Woocommerce - How to fix Uncaught Error: Call to a member function get_image() on bool in

 April 12, 2022     html, php, shortcode, woocommerce, wordpress     No comments   

Issue

I have this shortcode which returns information of all orders placed by a user. Works well! However, I have come to the point of introducing some $product variable to call images, download

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, March 18, 2022

[FIXED] Show WooCommerce product tag name set for a product with a shortcode

 March 18, 2022     php, shortcode, taxonomy-terms, woocommerce, wordpress     No comments   

Issue

As the title says I’m looking for a shortcode I can use to show the tag of a specific product. All my products have only one product tag set for each.

For example, if the product with ID: 1250 has the tag “Horse” I need the way to put a shortcode specifying the ID of the product and show your respective tag. In the example the shortcode should show on the screen the word “Horse”

Tyring to modify the following code to achieve it:

$terms = wp_get_post_terms( get_the_id(), 'product_tag' );

if( count($terms) > 0 ){
foreach($terms as $term){
$term_id = $term->term_id; // Product tag Id
$term_name = $term->name; // Product tag Name
$term_slug = $term->slug; // Product tag slug
$term_link = get_term_link( $term, 'product_tag' );

$output[] = '.$term_name.';
}

$output = implode( ', ', $output );

echo $output;
}

But I don't have the enough knowledge to achieve it

Any help is appreciated.


Solution

If you have only one product tag set for each product, the following shortcode function will output the product tag term name set for the current product (or a string of coma separated term names, when there are multiple terms set for a product). It works also for a defined product Id as argument in the shortcode (see usage examples).

The function code:

add_shortcode( 'wc_product_tag', 'get_tag_term_name_for_product_id' );
function get_tag_term_name_for_product_id( $atts ) {
    // Shortcode attribute (or argument)
    extract( shortcode_atts( array(
        'taxonomy'   => 'product_tag', // The WooCommerce "product tag" taxonomy (as default)
        'product_id' => get_the_id(), // The current product Id (as default)
    ), $atts, 'wc_product_tag' ) );
    
    $term_names = (array) wp_get_post_terms( $product_id, $taxonomy, array('fields' => 'names') );
 
    if( ! empty($term_names) ){
        // return a term name or multiple term names (in a coma separated string)
        return implode(', ', $term_names);
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

USAGE examples:

  • For the current product: [wc_product_tag]
    or in php: echo do_shortcode('[wc_product_tag]');
  • For a defined product id: [wc_product_tag product_id="37"]
    or in php: echo do_shortcode('[wc_product_tag product_id="37"]');

This also works for any product custom taxonomy, as WooCommerce product category…

To display WooCommerce product category term names set for a product you need to replace:

        'taxonomy'   => 'product_tag', // The WooCommerce "Product Tag" taxonomy (as default)

by the following line:

        'taxonomy'   => 'product_cat', // The WooCommerce "Product Category" taxonomy (as default)


Answered By - LoicTheAztec
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to fix php shortcode to show woocommerce download button

 March 18, 2022     html, php, shortcode, woocommerce, wordpress     No comments   

Issue

I am trying to view the download button belonging to the last order placed by a customer. Basically I have this code. It worked for other things like: displaying the purchase date, order total, product name etc, but it doesn't work with the downlad.

<?php

add_shortcode( 'order_download' , 'last_order_info_08' );
function last_order_info_08(){

// Get the WC_Customer instance Object for the current user
$customer = new WC_Customer( get_current_user_id() );

// Get the last WC_Order Object instance from current customer
$last_order = $customer->get_last_order();

// If this is the last order, then it shows the data from it
  if ( is_a( $last_order, 'WC_Order' ) ) {
     return $last_order->get_downloadable_items();
     }
}

return $last_order->get_downloadable_items(); it shows the word array instead of the download button. Could someone tell me where am I wrong? Excuse me, but I am relatively new to php.

// Edit - With probable solution //

Maybe I have found a solution. I modified the code by adding wc_get_template and array. This works well for users who have a download available. Unfortunately, however, users who have not made any purchases and therefore do not have a download available find themselves with a broken layout.

Is there any way to display an error message? or to correct this in any other way?

<?php
add_shortcode( 'order_download' , 'last_order_info_08' );
function last_order_info_08(){

// Get the WC_Customer instance Object for the current user
$customer = new WC_Customer( get_current_user_id() );

// Get the last WC_Order Object instance from current customer
$last_order = $customer->get_last_order();

// Works with array
$downloads = $last_order->get_downloadable_items();

// If this is the last order, then it shows the data from it
    if ( is_a( $last_order, 'WC_Order' ) ) {
        wc_get_template('button-downloads.php',
        array(
            'downloads'  => $downloads,
            'show_title' => true,
         )
     );
     } 
}

Solution

<?php
add_shortcode( 'order_download' , 'last_order_info_08' );
function last_order_info_08(){

// Get the WC_Customer instance Object for the current user
$customer = new WC_Customer( get_current_user_id() );

// Get the last WC_Order Object instance from current customer
$last_order = $customer->get_last_order();

// If this is the last order shows the data from it
  if ( is_a( $last_order, 'WC_Order' ) ) {

     // Works with array below
     $downloads = $last_order->get_downloadable_items();
     
     if ($downloads){
         wc_get_template(
         'button-downloads.php', // This is a template I placed in wp-content/themes/theme-child/woocommerce
         array(
         'downloads'  => $downloads,
         'show_title' => true,
         ));
         }
     } 
     
//The else part shows the warning message when a user has no order, this does not break the layout.
  else {
        ?><div class="woocommerce-message woocommerce-message--info woocommerce-Message woocommerce-Message--info woocommerce-info">
        <a class="woocommerce-Button button" href="<?php echo esc_url( apply_filters( 'woocommerce_return_to_shop_redirect', wc_get_page_permalink( 'shop' ) ) ); ?>"><?php esc_html_e( 'Browse products', 'woocommerce' ); ?></a>
        <?php esc_html_e( 'No order has been made yet.', 'woocommerce' ); ?>
        </div><?php
    }   
}


Answered By - Snake
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, February 6, 2022

[FIXED] how to create shortcode using post content for each post when the post is published

 February 06, 2022     plugins, shortcode, wordpress     No comments   

Issue

I want to create short code every time when post is published using that specific post content so that i have short codes for each different post, for this i wrote this code, but its not working, can anyone please help.

add_action('publish_adsmanager_banner','create_banner_shortcode');

function create_banner_shortcode()
{    
    add_shortcode( 'banner_'.get_the_ID().'', 'custom_shortcode' ); 
}


function custom_shortcode($post_id) {

    $message = get_the_content($post_id);
    return $message;

}

Solution

What if you will just pass an id as an attribute to this shortcode?

    add_shortcode( 'my_banner', 'custom_shortcode' ); // [my_banner id="123"]

function custom_shortcode( $atts ) {
    $atts = shortcode_atts(
        array(
            'id' => null,
        ),
        $atts
    );
    $message = get_the_content( $atts['id'] );
    return $message;
}

In your original idea, you cannot create an id-named shortcode just once, it should be registered on each wp init. But in this case, it is hard to get a post context just from the shortcode name, you have to pass an id on each shortcode registration. The solution above will allow you to keep DRY especially if you know the ID of each banner when using them.



Answered By - Ivan Karpushchenko
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, February 5, 2022

[FIXED] How to work if, endif, else in wordpress shortcode

 February 05, 2022     html, php, shortcode, woocommerce, wordpress     No comments   

Issue

I'm trying to get some php code to work in a shortcode.

Here is what i did in woocommerce dashboard.php. This code shows the data of the last order placed by the customer, everything works perfectly. As you can see it contains if, endif and else.

<?php
// For logged in users only
if ( is_user_logged_in() ) :

// Get the current WC_Customer instance Object
$customer = new WC_Customer( get_current_user_id() );

// Get the last WC_Order Object instance from current customer
$last_order = $customer->get_last_order();
?>

<?php if( is_a($last_order, 'WC_Order') ) : ?>
   
<?php foreach ( $last_order->get_items() as $item ) : ?>

<div class="last_order_items"><?php echo $item->get_name(); ?></div>
<div class="last_order_items"><?php echo $item->get_total(); ?>€</div>

<div class="order_number">#<?php echo $last_order->get_order_number(); ?> </div>
<div class="order_number">Data acquisto <?php echo $last_order->get_date_created()->date('d/m/Y - H:i'); ?> </div>
<div class="order_number">Stato dell'ordine <?php echo esc_html( wc_get_order_status_name( $last_order->get_status() ) ); ?>
  
<?php endforeach; ?>

<?php else : ?>

<div class="woocommerce-message woocommerce-message--info woocommerce-Message woocommerce-Message--info woocommerce-info">
        <a class="woocommerce-Button button" href="<?php echo esc_url( apply_filters( 'woocommerce_return_to_shop_redirect', wc_get_page_permalink( 'shop' ) ) ); ?>"><?php esc_html_e( 'Browse products', 'woocommerce' ); ?></a>
        <?php esc_html_e( 'No order has been made yet.', 'woocommerce' ); ?>
        </div>

<?php endif; ?>
<?php endif; ?>

Here is what I did in the functions.php file. The shortcode works fine, but if user is not logged in or has not placed an order, an error occurs. In dashboard.php file the error is not there because the if (is_user_logged_in ()) part exists and the else part which shows the message when a user has not placed any order.

//// LAST ORDER ON DASHBOARD WOOCOMMERCE SHORTCODE ////

add_shortcode( 'short_test' , 'test' );
function test(){    
    $customer = new WC_Customer( get_current_user_id() );
    $last_order = $customer->get_last_order();
    return $last_order->get_order_number();

}

How can i implement if, endif and else in this shortcode ? I would like to be able to show data only to logged in users, and for those who have not placed any orders I would like to display a message just like I did in the dashboard.php file. I tried a number of ways but couldn't. I would like to use the shortcode because it is more convenient for me, moreover I prefer to keep the woocommerce templates "clean" and write everything directly in the functions.php file

Sorry, but I'm a fan and don't have a lot of knowledge on the subject.


Solution

I found a solution, here's what I did:

<?php

add_shortcode( 'short_test' , 'test' );

function test() {

// Get the WC_Customer instance Object for the current user
$customer = new WC_Customer( get_current_user_id() );

// Get the last WC_Order Object instance from current customer
$last_order = $customer->get_last_order();

// Then I added the if condition. If this is the last order, then it shows the data from it
if ( is_a( $last_order, 'WC_Order' ) ) {
return $last_order->get_order_number();  // Change get_order_number to another parameter if you want to show different information  
} 
    
// With else show the warning message if the user has not placed any order
else {
?><div class="woocommerce-message woocommerce-message--info woocommerce-Message woocommerce-Message--info woocommerce-info">
<a class="woocommerce-Button button" href="<?php echo esc_url( apply_filters( 'woocommerce_return_to_shop_redirect', wc_get_page_permalink( 'shop' ) ) ); ?>"><?php esc_html_e( 'Browse products', 'woocommerce' ); ?></a>
<?php esc_html_e( 'No order has been made yet.', 'woocommerce' ); ?>
</div><?php
} 
}

I leave below some information for those who have encountered the same problem.

  1. In case you want to change the type of information to be displayed, just change get_order_number(); with the parameter you want. An example could be the following: $last_order = $customer->get_formatted_order_total(); will show the order total instead of the order number. Here you find a list of all woocommerce parameters https://www.businessbloomer.com/woocommerce-easily-get-order-info-total-items-etc-from-order-object/

  2. If you want to add different parameters such as items, then you have to introduce foreach inside the if as follows.

// Get and Loop Over Order Items
if ( is_a( $last_order, 'WC_Order' ) ) {
     foreach ( $last_order->get_items() as $item ) {
     return $last_order = $item->get_product_id();   
     }
    } 
  1. If you want to show more information within the same shortcode then edit the if part as follows. Remember that only $ items go into the foreach. If you don't need $ item parameters you can also delete the foreach.
if ( is_a( $last_order, 'WC_Order' ) ) {
      
     ?><div class="last_order" style="display:block">Order Number <?php echo $last_order->get_order_number();
     ?><div class="last_order">Order Total <?php echo $last_order->get_formatted_order_total();
     ?><div class="last_order">Order Status <?php echo $last_order->get_status();
      
     foreach ( $last_order->get_items() as $item ) {
     ?><div class="last_order">Product ID <?php echo $last_order = $item->get_product_id(); 
     }
    } 

Edit with @Josh Bonnick's solution After "playing" a bit with various ways to get an error message instead of breaking the layout I also tried @Josh Bonnick's solution which I implemented in the following motion. (I took the first part of the code and not the second that requires the template).

<?php

add_shortcode( 'short_test' , 'test' );

function test() {

// Get the WC_Customer instance Object for the current user
$customer = new WC_Customer( get_current_user_id() );

// Get the last WC_Order Object instance from current customer
$last_order = $customer->get_last_order();

// Then I added the if condition. If this is the last order, then it shows the data from it
if ( is_a( $last_order, 'WC_Order' ) ) {
return $last_order->get_order_number();  // Change get_order_number to another parameter if you want to show different information  
} 

// Josh Bonnick recommended piece of code
$order_count = wc_get_customer_order_count(get_current_user_id()); 
if ($order_count == 0) { 
return '<p>This is where you would put your HTML</p>'; 
}


Answered By - Emanuele Daniele
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, February 4, 2022

[FIXED] WooCommerce how to get current order info on the thank you page using shortcode

 February 04, 2022     php, shortcode, woocommerce, woocommerce-theming, wordpress     No comments   

Issue

I'm trying to introduce a shortcode on the thankyou.php page to show the details of the order just placed by a customer.

If I write the code in php like this it works and shows the total: <?php echo $order->get_total(); ?>

Now I'm trying to get the same result through a shortcode, but I don't know some parameters and therefore can't get it to work.

<?php
add_shortcode( 'custom-woocommerce-total' , 'custom_total' );
function custom_total(){
    $customer_id = get_current_user_id();
    $order = new WC_Order($order_id); // I suppose that's not right.
    return $order->get_total();
} ?>

can anyone help me understand what I'm doing wrong?


Solution

You would need to get the order id first by using global $wp variable. Try this:

add_shortcode('custom-woocommerce-total', 'custom_total');

function custom_total($attr)
{
    if (is_wc_endpoint_url('order-received')) 
    {
        global $wp;

        $order_id  = absint($wp->query_vars['order-received']);

        if ($order_id) 
        {
            $order = new WC_Order($order_id);

            if($order)
            {
              return $order->get_total();
            }

        }
    }
}

And in the thankyou page template use it like this:

echo do_shortcode('[custom-woocommerce-total]');

Don't forget to override the template.



Answered By - Ruvee
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, February 2, 2022

[FIXED] Plugin development - Revised shortcode attribute name as part of update

 February 02, 2022     plugins, posts, shortcode, tags, wordpress     No comments   

Issue

In a plugin I am coding and supporting, I have revised a shortcode attribute recognised by the plugin to a name which makes more sense to a user.

I want to update every post where the attribute is used. I'm guessing it's not sensible to run code to update users' pages and posts by going through each one, and where found, changing the attribute from the old one to the new one. That seems very dangerous to me.

An option I know I have is to add the filter do_shortcode_tag, so every time the shortcode is called, I can treat the old attribute the same as the revised one. It's a tiny overhead I know, but literally speaking it is just a patch.

I'm thinking I can't be the only one faced with something like this. Ideally, I'd be able to run an action, or something available from the core to update relevant posts. Does anyone know of a solution?


Solution

It could be something like this:

add_shortcode('sample_shortcode', 'render_sample_shortcode');

function render_sample_shortcode($attrs)
{
    $attribute = isset($attrs["newattr"]) && !empty($attrs["newattr"]) ? $attrs["newattr"] : $attrs["oldattr"];

    return "Iam reading this attribute value: " . $attribute;
}

Your shortcode:[sample_shortcode newattr="I am new" oldattr="I am old"]

Or in a PHP file: echo do_shortcode('[sample_shortcode newattr="I am new" oldattr="I am old"]');



Answered By - Miguel Angel Martinez
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, January 18, 2022

[FIXED] How to add a custom shortcode below the product table on woocommerce checkout page

 January 18, 2022     hook-woocommerce, php, shortcode, woocommerce, wordpress     No comments   

Issue

Problem:
I need to add a shortcode [wc_sc_available_coupons] below the product table on the checkout page.
I added the following code in functions.php
The problem is the shortcode displays at the very bottom of the checkout form.
I changed the number 10 to 120 but still the same.
Would you please let me know how to add the shortcode below the product table (=above the payment)?

Code I tried:

add_action( 'woocommerce_after_checkout_form', 'wnd_checkout_code', 10 );

function wnd_checkout_code( ) {
  echo do_shortcode('[wc_sc_available_coupons]');
}

Thank you.


Solution

Would woocommerce_checkout_after_customer_details hook work for you? So your code would be something like this:

add_action( 'woocommerce_checkout_after_customer_details', 'wnd_checkout_code' );

function wnd_checkout_code( )
{
  echo do_shortcode('[wc_sc_available_coupons]');
}

If not then you could try other hooks such as woocommerce_checkout_before_order_review or you could try this woocommerce_before_order_notes as well.

This one is right before the payment:

add_action( 'woocommerce_review_order_before_payment', 'wnd_checkout_code' );

function wnd_checkout_code( ) 
{
  echo do_shortcode('[wc_sc_available_coupons]');
}


Answered By - Ruvee
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing