functions Archives - PluginsForWP https://plugins-for-wp.world/blog/tag/functions/ Premium WordPress Plugins And Themes For An Affordable Price Fri, 19 Jul 2024 17:17:20 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.3 https://plugins-for-wp.world/wp-content/uploads/2020/01/cropped-Pluginsforwp-Favicon-32x32.jpg functions Archives - PluginsForWP https://plugins-for-wp.world/blog/tag/functions/ 32 32 How To Redirect WooCommerce and EDD Empty Checkout Pages https://plugins-for-wp.world/blog/how-to-redirect-woocommerce-and-edd-empty-checkout-pages/ https://plugins-for-wp.world/blog/how-to-redirect-woocommerce-and-edd-empty-checkout-pages/#respond Fri, 19 Jul 2024 17:16:36 +0000 https://plugins-for-wp.world/?p=7665 The empty checkout page is no fun. Not for the store owner or the website visitor. Besides being unuser-friendly, a cart page without items will ultimately cost you revenue. When the user removes items from the cart, there is a better chance for him to navigate away from your website afterward. To prevent it from […]

The post How To Redirect WooCommerce and EDD Empty Checkout Pages appeared first on PluginsForWP.

]]>
The empty checkout page is no fun. Not for the store owner or the website visitor.

Besides being unuser-friendly, a cart page without items will ultimately cost you revenue.

When the user removes items from the cart, there is a better chance for him to navigate away from your website afterward. To prevent it from happening, it will be better to direct them to some of the products that may interest them.

Please take a look at our website, for example. When you try to load our checkout page plugins-for-wp.world/checkout when it’s empty, you’ll be redirected to our subscription page.

By doing so, I focused your attention on our available plans rather than giving you the option of where to go next, saving you valuable page load time.

This tutorial will redirect WooCommerce and Easy Digital Downloads empty cart pages to different pages.

Both codes below must be pasted in the functions.php file of your child theme or a site-specific plugin. Read our article and learn how to create a custom site-specific plugin in WordPress.

Please apply the functions below to a child theme and remember to back up WordPress before editing core files.

Redirect an Empty Checkout Page in WooCommerce

If you’re using the WooCommerce plugin to sell your goods, use the code below:

add_action("template_redirect", 'redirect_empty_checkout_woocommerce');
function redirect_empty_checkout_woocommerce(){
    global $woocommerce;
    if( is_cart() && WC()->cart->cart_contents_count == 0){
        wp_safe_redirect( site_url( 'shop' ) );
    }
}

The code above will redirect the visitors from an empty checkout or cart page to the archive Shop page.

However, if you prefer to land them on a different page, such as a specific product or the pricing page, change the URL address from 'shop' to 'product/product-name/'.

Redirect an Empty Checkout Page in Easy Digital Downloads

If you’re using the EDD plugin to sell your goods, use the code below

add_action( 'template_redirect', 'redirect_empty_checkout_edd', 11 );
function redirect_empty_checkout_edd(){
	if ( is_page( edd_get_option( 'purchase_page' ) ) && edd_get_cart_quantity() == 0 ) {
        wp_safe_redirect( site_url( 'downloads' ) );
		exit;
	}
}

Like the WooCommerce redirection function, the code above will redirect the users to the archive Downloads page, where they can view all your available products.

If you want to set a different URL, change 'downloads' to your desired address, such as 'downloads/product-name/'.

Related Articles

Conclusion

This article teaches you how to redirect empty checkout pages in WooCommerce and Easy Digital Downloads to another page.

Let us know which code snippet you used to achieve that.

The post How To Redirect WooCommerce and EDD Empty Checkout Pages appeared first on PluginsForWP.

]]>
https://plugins-for-wp.world/blog/how-to-redirect-woocommerce-and-edd-empty-checkout-pages/feed/ 0
How to Fix the Theme File Editor is Missing in WordPress https://plugins-for-wp.world/blog/how-to-fix-the-theme-file-editor-is-missing-in-wordpress/ https://plugins-for-wp.world/blog/how-to-fix-the-theme-file-editor-is-missing-in-wordpress/#respond Fri, 07 Jul 2023 17:04:31 +0000 https://plugins-for-wp.world/?p=456067 Are you having trouble finding the theme file editor or plugin file editor in your WordPress dashboard? Don’t worry. We’ve got you covered! This blog post will show you how to fix this issue and regain access to these essential editor screens. Identifying the Issue: Theme File Editor and Plugin File Editor Missing in WordPress […]

The post How to Fix the Theme File Editor is Missing in WordPress appeared first on PluginsForWP.

]]>
Are you having trouble finding the theme file editor or plugin file editor in your WordPress dashboard? Don’t worry. We’ve got you covered!

This blog post will show you how to fix this issue and regain access to these essential editor screens.

Identifying the Issue: Theme File Editor and Plugin File Editor Missing in WordPress Dashboard

To begin, navigate to the “Appearance” tab on your WordPress website and search for the Theme File Editor option. Alternatively, you can search for the Plugin File Editor screen under the Plugins tab.

Missing Theme File Editor Screen

In some cases, especially with new themes developed by the official WordPress team, the editor screens can be found under the Tools tab.

Theme File Editor under Tools

If you can’t find either, a function inside the wp-config.php file prevents it from appearing. Therefore, we will need to access the file and modify the function.

You can access WordPress core files through FTP or a file manager plugin. Once you’ve made the necessary changes, refresh your website, and voila! You’ll have the theme file editor and plugin file editor back in your dashboard.

Fix the Missing File Editor Screens in WordPress

The following steps will show you how to fix the missing Theme and Plugin File Editor screens:

  1. Download a File Manager plugin

    The first step to accessing the WordPress core files is using an FTP or a file manager plugin. Therefore, navigate to Plugins -> Add New, and install the WP File Manager plugin.WP File Manager Plugin

  2. Open the wp-config.php file.

    Navigate to the WP File Manager tab, right-click on the wp-config.php file, and choose Code Editor. Edit the wp config file

  3. Modify the ‘DISALLOW_FILE_EDIT’ function.

    Search for the define(‘DISALLOW_FILE_EDIT’, true); and replace it with define(‘DISALLOW_FILE_EDIT’, false);. Alternatively, you can also comment it out from executing by adding double dashes (//) to its left or delete the row completely.Allow File Edit WordPress

  4. Save and Validate

    Click on the Save & Close button, and refresh the page. Now, when you go to the “Appearance” tab, you should be able to see the theme file editor or plugin file editor.Theme File Editor Restored

Following these steps will restore the missing options in your WordPress dashboard, allowing you to edit themes or plugins effortlessly.

Please remember to back up your website before editing core files.

Conclusion

The file editor screens are handy when using code snippets or modifying certain pages and templates.

Not having the option to access those screens can slow us down or prevent us from achieving our desired website look.

This tutorial showed you how to restore the theme file editor and plugin file editor back in your dashboard.

The post How to Fix the Theme File Editor is Missing in WordPress appeared first on PluginsForWP.

]]>
https://plugins-for-wp.world/blog/how-to-fix-the-theme-file-editor-is-missing-in-wordpress/feed/ 0
How to Set the Elementor Accordion Widget Closed by Default https://plugins-for-wp.world/blog/elementor-accordion-widget-closed-default/ https://plugins-for-wp.world/blog/elementor-accordion-widget-closed-default/#respond Fri, 19 May 2023 18:56:07 +0000 https://plugins-for-wp.world/?p=454320 The Elementor Accordion widget will have the first tab open by default. The rest of the tabs are closed. You’ll need to click on each to open and view their content. If you want the first tab closed on default for aesthetic, design, or any other reason, you won’t find the option to do it […]

The post How to Set the Elementor Accordion Widget Closed by Default appeared first on PluginsForWP.

]]>
The Elementor Accordion widget will have the first tab open by default.

The rest of the tabs are closed. You’ll need to click on each to open and view their content.

If you want the first tab closed on default for aesthetic, design, or any other reason, you won’t find the option to do it through the plugin’s edit panel.

However, setting the accordion widget closed on page load is still possible using a simple script.

This tutorial will show you how to set the Elementor accordion widget closed by default.

How to Default Close Elementor Accordions

Elementor widgets generate the content with HTML elements added to the screen.

Each section or element gets its own set of body classes based on your assigned settings.

The CSS and JavaScript files are fired on page load, and the design or behavior for each element is applied based on its class.

While inspecting the accordion HTML element, you’ll notice that the elementor-active class triggers a specific behavior.

Inspect Elementor accordion class

To close the accordion by default, we must run JavaScript code to remove that class.

We will cover all scenarios of how to close the accordions:

  • Single accordion
  • All accordions together
  • Specific accordions only

Let’s start with the first option, close a single accordion,

Default Close a Single Accordion

This method is perfect if you only want to close a single accordion on a page.

In this case, drag an HTML widget above the accordion widget, and paste this JavaScript code inside.

<script>
jQuery(document).ready(function($) {
var delay = 100; setTimeout(function() {
$('.elementor-tab-title').removeClass('elementor-active');
 $('.elementor-tab-content').css('display', 'none'); }, delay);
});
</script>

Save the changes and reload the page to ensure the accordion is closed.

Close accordion script in HTML widget

You may see it open for a split second until the JavaScript file executes and close it.

Close All Elementor Accordions by Default

If you want to close all current and future accordions on your website, you’ll need to fire the same code above from your header template.

You can place the code above in your template files by using any code snippet plugin or the Custom Codes option of Elementor Pro.

You can read more about the different options in our Add JavaScript to Elementor article.

With Elementor Pro, navigate to the Custom Codes screen and click Add New.

Add new custom code in Elementor

Give the code snippet a name, paste it inside the code box, and publish it.

Elementor custom code default close accordion

Once published, revisit any page with accordion and verify it’s now closed by default.

Default Close Specific Accordions

We understand that, in some cases, you would like to have some accordions closed while others can stay open.

We’ll need to assign a unique class name to the accordions we want to close by default, to differentiate them from the others.

First, click on the Advanced tab of the accordion widgets you would like to close, and enter closeAccordion in their CSS Classes box.

Add close accordion class to Element

Then, create a custom code in Elementor Pro, paste the following code inside, and save the changes.

<script>
jQuery(document).ready(function($) {
var delay = 100; setTimeout(function() {
$('.closeAccordion .elementor-tab-title').removeClass('elementor-active');
 $('.closeAccordion .elementor-tab-content').css('display', 'none'); }, delay);
});
</script>

Once saved, refresh any page containing an accordion widget with the closeAccordion class and verify it’s closed now.

You can also check the other accordion widget without the added class and verify that it functions as usual.

Troubleshooting if Accordion is Not Closed by Default

The JavaScript code we use above holds a delay function that will be triggered one second after the page is fully loaded.

The idea is to fire the script only after all the Elementor files are rendered on the page.

While it will work flawlessly for most designs, it will take longer than a second to load for heavy-content websites. Therefore, the code will be firing before Elementor is finished loading.

In such cases, the Elementor default files will overwrite our custom code and keep the accordion open.

To fix that, change the set time of the delay function to a more significant number. For example, switch 100 to 1000, and test it again.

Increase delay value number

Keep increasing the delay property number until you find the proper delay value for your website. 

Remember not to get discouraged by a high number because it will take the visitors more than a couple of seconds to scroll to the accordion section, which will be close by then. 

Conclusion

Elementor doesn’t have the option to toggle close the accordion widget by default.

However, we could still default close the accordion with a simple script; this tutorial showed you how to do that easily.

Leave a comment and tell us which one of the methods we presented works the best for you.

The post How to Set the Elementor Accordion Widget Closed by Default appeared first on PluginsForWP.

]]>
https://plugins-for-wp.world/blog/elementor-accordion-widget-closed-default/feed/ 0
How to Disable Image Zoom and Lightbox for WooCommerce Products https://plugins-for-wp.world/blog/disable-product-image-zoom-lightbox-woocommerce/ https://plugins-for-wp.world/blog/disable-product-image-zoom-lightbox-woocommerce/#respond Wed, 08 Mar 2023 17:13:09 +0000 https://plugins-for-wp.world/?p=444736 Image zooming is a default feature automatically enabled with WooCommerce. Zooming into a product image is often necessary to see more critical details. However, it’s unnecessary in other cases, and we should disable it. This article will show you how to disable the zoom and lightbox preview for WooCommerce products. Paste the functions below inside […]

The post How to Disable Image Zoom and Lightbox for WooCommerce Products appeared first on PluginsForWP.

]]>
Image zooming is a default feature automatically enabled with WooCommerce.

Zooming into a product image is often necessary to see more critical details. However, it’s unnecessary in other cases, and we should disable it.

This article will show you how to disable the zoom and lightbox preview for WooCommerce products.

Paste the functions below inside the functions.php file of your child theme. Please remember to back up your website before editing core files.

Disable Image Zoom in WooCommerce

We are all know and familiar with the zoom effect that every WooCommerce store has.

Hovering over a product image will enlarge the item to view it bigger.

Image Zoom WooCommerce

To disable the zoom feature on single product pages in WooCommerce, navigate to Appearance -> Theme File Editor and paste this code at the bottom of the functions.php file.

remove_theme_support( 'wc-product-gallery-zoom' );

Once saved, refresh the product page and verify that the zoom feature was disabled successfully.

Keep reading if you’re interested in keeping the zoom option but want to disable the lightbox feature.

Disable Product Lightbox in WooCommerce

When clicking on a product’s image, the lightbox feature will open it in a gallery view.

That will help customers to get see more details about the desired item.

Product Lightbox WooCommerce

However, not all products need it, and the lighbox modal can be disabled easily.

Disabling the lightbox modal in WooCommerce is a simple process similar to the one above (image zoom).

From your WordPress dashboard, navigate to Appearance -> Theme File Editor, and paste this code at the bottom of the functions.php file.

remove_theme_support( 'wc-product-gallery-lightbox' );

Once saved, revisit the product page and click on the product’s image to ensure it was disabled successfully.

Conclusion

This article showed you how to easily disable zoom and lightbox for WooCommerce products.

If you would like to reverse the process in the future, delete the codes above from the functions file.

Please comment and tell us if you have any questions about the process.

The post How to Disable Image Zoom and Lightbox for WooCommerce Products appeared first on PluginsForWP.

]]>
https://plugins-for-wp.world/blog/disable-product-image-zoom-lightbox-woocommerce/feed/ 0
How to Get Product Info (Price, ID, Name, Etc) from WooCommerce $product Object https://plugins-for-wp.world/blog/woocommerce-product-object-tutorial/ https://plugins-for-wp.world/blog/woocommerce-product-object-tutorial/#respond Wed, 21 Dec 2022 15:54:58 +0000 https://plugins-for-wp.world/?p=431936 The WooCommerce $product object holds every piece of data that we need to work with products. If you’re a WooCommerce developer, you’ll need to access some or all of that information at some point or another. Whether you’re developing a plugin, theme, or just a code snippet, knowing how to get the relevant product information […]

The post How to Get Product Info (Price, ID, Name, Etc) from WooCommerce $product Object appeared first on PluginsForWP.

]]>
The WooCommerce $product object holds every piece of data that we need to work with products.

If you’re a WooCommerce developer, you’ll need to access some or all of that information at some point or another.

Whether you’re developing a plugin, theme, or just a code snippet, knowing how to get the relevant product information is the key to success.

Once you access the $product variable, you can use any class object method.

Some of the product data you can get from the $product object is the item name, order, ID, SKU, price, stock level, order notes, etc. We can retrieve complete information about the item simply by getting the $product object.

For example, when a customer asks us to create a code snippet to disable a payment method for a specific product, we need to check if the item exists on the cart page and conditionally execute the function based on true or false.

This was just one scenario out of many possibilities, and you can find many more in some of the most useful WooCommerce functions.

Now that we know how essential the product object is let’s discover how to get the data from it.

Get Data from the $product Variable

Some additional arguments are passed through the function when working with WooCommerce hooks (actions and filters).

If you can use the $product object as an argument in the function, you’re golden. However, if the process doesn’t accept it as an argument, you’ll need to define the ‘global $product’ inside it to access all the object’s methods.

Once you’re ‘in,’ here is the product’s data you can get.

Get Product ID:

$product->get_id();

Get Product General Info:

$product->get_type();
$product->get_name();
$product->get_slug();
$product->get_date_created();
$product->get_date_modified();
$product->get_status();
$product->get_featured();
$product->get_catalog_visibility();
$product->get_description();
$product->get_short_description();
$product->get_sku();
$product->get_menu_order();
$product->get_virtual();
get_permalink( $product->get_id() );

Get Product Prices:

$product->get_price();
$product->get_regular_price();
$product->get_sale_price();
$product->get_date_on_sale_from();
$product->get_date_on_sale_to();
$product->get_total_sales();

Get Tax, Shipping, and Stock:

$product->get_tax_status();
$product->get_tax_class();
$product->get_manage_stock();
$product->get_stock_quantity();
$product->get_stock_status();
$product->get_backorders();
$product->get_sold_individually();
$product->get_purchase_note();
$product->get_shipping_class_id();

Get Product Dimensions:

$product->get_weight();
$product->get_length();
$product->get_width();
$product->get_height();
$product->get_dimensions();

Get Similar / Linked Products:

$product->get_upsell_ids();
$product->get_cross_sell_ids();
$product->get_parent_id();

Get Variations and Attributes:

$product->get_children(); // get variations
$product->get_attributes();
$product->get_default_attributes();
$product->get_attribute( 'attributeid' );

Get Product Taxonomies:

$product->get_categories();
$product->get_category_ids();
$product->get_tag_ids();

Get Product Downloads:

$product->get_downloads();
$product->get_download_expiry();
$product->get_downloadable();
$product->get_download_limit();

Get Product Images:

$product->get_image_id();
$product->get_image();
$product->get_gallery_image_ids();

Get Product Reviews:

$product->get_reviews_allowed();
$product->get_rating_counts();
$product->get_average_rating();
$product->get_review_count();

No $product Variable? No Worries!

If the hooks don’t accept the $product variable as is, you can still get to the object by adding another step.

The following sections will show how to retrieve the $product object from different variables and objects.

Access the $product Object from the $product_id

$product = wc_get_product( $product_id );
    
$product->get_type();
$product->get_name();
// etc.

Access the $product Object from the $order_id

$order = wc_get_order( $order_id );
$items = $order->get_items();
  
foreach ( $items as $item ) {
  
    $product = $item->get_product();
    
    $product->get_type();
    $product->get_name();
    // etc.
  
}

Access the $product Object from the Cart Object

$cart = WC()->cart->get_cart();
  
foreach( $cart as $cart_item_key => $cart_item ){
  
    $product = $cart_item['data'];
    
    $product->get_type();
    $product->get_name();
    // etc.
  
}

Access the $product Object from the $post Object

$product = wc_get_product( $post );
  
$product->get_type();
$product->get_name();
// etc.

Once you get into the $product object, you can use any of its methods from the first section.

Related Articles

  1. How to set a default variation in WooCommerce
  2. How to reorder products in WooCommerce
  3. How to hide the WooCommerce additional information tab
  4. WooCommerce: add back in stock notifications
  5. Best name your price plugins for WooCommerce
  6. How to change store currency in WooCommerce
  7. Add additional variation images in WooCommerce
  8. How to change the sale badge in WooCommerce

Conclusion

This article showed you how to access the WooCommerce $product object and use its data to expand the functionality of the WooCommerce plugin.

You can use it to develop a new plugin, theme, extension, or simple function.

Leave a comment and tell us what you use the $product object for or if you need further help.

The post How to Get Product Info (Price, ID, Name, Etc) from WooCommerce $product Object appeared first on PluginsForWP.

]]>
https://plugins-for-wp.world/blog/woocommerce-product-object-tutorial/feed/ 0
How to Easily Check If a User Is Logged In to WordPress https://plugins-for-wp.world/blog/check-if-user-logged-in-wordpress/ https://plugins-for-wp.world/blog/check-if-user-logged-in-wordpress/#respond Fri, 04 Nov 2022 17:05:49 +0000 https://plugins-for-wp.world/?p=429875 If you are a full-stack WordPress developer or just a website owner using code snippets, checking whether a user is logged in is an essential function you will need to use sooner or later. Checking the condition of the user and triggering relevant actions is a common practice and is used by many functions and […]

The post How to Easily Check If a User Is Logged In to WordPress appeared first on PluginsForWP.

]]>
If you are a full-stack WordPress developer or just a website owner using code snippets, checking whether a user is logged in is an essential function you will need to use sooner or later.

Checking the condition of the user and triggering relevant actions is a common practice and is used by many functions and plugins.

This article will show you how to check if a user is logged in to WordPress and how to use it in the functions.php and template files.

Why Check if a User is Logged In to WordPress

As mentioned above, validating if a user is logged in is used in many scenarios. Moreover, it is one of the most used WordPress functions, and for a good reason.

There are thousands of reasons why you’ll need to check the user’s status, and here are only some of them:

  • Conditionally display login/logout links in your website’s header.
  • Use the logged-in users’ names to greet and welcome them.
  • Show WooCommerce prices for logged-in users only.
  • Display certain pages, like my account page, for logged-in users.

You probably got the point and understand by now why it is beneficial to check if a WordPress user is logged in.

Whether you want to use it for one of the reasons above or for a different one, we will show you how to do it.

How to Check if a User is Logged In

WordPress has a built-in function that we can use to determine if a user is logged in or not.

is_user_logged_in()

You can also use PHP logical operator to check if a user is NOT logged in (logged out) by adding an exclamation point (!) to the left of the function, like so:

!is_user_logged_in()

It is a simple function because it doesn’t take any variables and returns true if a user is logged in and false if not logged in.

We can then execute different kinds of actions based on the returned value.

For example, let’s greet all logged-in users with a Hello fan message and just Hello to all logged out users. To do that, we can use the is_user_logged_in() function in our functions.php or template files.

Use the is_user_logged_in() Function in the functions.php File

WordPress uses hooks (like anchors) to simplify adding content to certain page parts.

Therefore, we will need to add the message to the desired hook based on where we want it to appear.

If we want to display it above the header, we can use the init hook.

Using an FTP or from your WordPress dashboard, navigate to Appearance -> Theme File Editor and open the functions.php file of your child’s theme.

Note: please back up your website before editing core files.

Then, scroll to the bottom of the file and paste this function:

add_action('init', 'greet_logged_in_users');
function greet_logged_in_users() {
	if ( is_user_logged_in() ) {
		echo '<p>Hello fan!</p>';
	} else {
		echo '<p>Hello</p>';
  }
}
Check if WordPress user logged in PHP function

Once saved, visit your website and ensure you can see the message for the logged-in users. Then, log out and verify that the alternative message is displayed.

If you prefer to check the user status within a template file, continue to the next section.

Use the is_user_logged_in() Function in a PHP Template File

The second way to use the is_user_logged_in() function to check if the user is logged-in is by executing it in a template file instead of the functions.php file.

The advantage of using a template file is the option to position the function anywhere on the page, regardless if there is a hook to which we can attach it.

Let’s take the example above and display a greeting message to logged in users using one of our theme’s template files.

Because we want to display the message above the header, we will need to modify the header.php file.

Therefore, navigate to Appearance -> Theme File Editor and click on the header.php file from the right sidebar.

Then, place the is_user_logged_in() function in your desired position, and save the file.

<?php
  if ( is_user_logged_in() ) {
    echo '<p>Hello fan!</p>';
  } else {
    echo '<p>Hello</p>';
  }
?>
Check if WordPress user logged in template file

Once saved, visit your website and ensure that the correct message is displayed based on the user status.

Conclusion

The is_user_logged_in() is a default WordPress function to check if a user is logged in.

This article taught you to check if a user is logged in using the is_user_logged_in() function in different scenarios and file types.

Leave us a comment and tell us your preferred method to achieve this task.

The post How to Easily Check If a User Is Logged In to WordPress appeared first on PluginsForWP.

]]>
https://plugins-for-wp.world/blog/check-if-user-logged-in-wordpress/feed/ 0
How to Get Current User Role and Name in WordPress https://plugins-for-wp.world/blog/get-current-user-role-wordpress/ https://plugins-for-wp.world/blog/get-current-user-role-wordpress/#respond Mon, 28 Feb 2022 18:13:22 +0000 https://plugins-for-wp.world/?p=407826 When adding a custom code or creating a plugin in WordPress, you may need to use the information of the specific current user. Getting the current user values, such as role or ID, will enable you to segment and display unique content to different users. In this article, you’ll learn how to get the current […]

The post How to Get Current User Role and Name in WordPress appeared first on PluginsForWP.

]]>
When adding a custom code or creating a plugin in WordPress, you may need to use the information of the specific current user.

Getting the current user values, such as role or ID, will enable you to segment and display unique content to different users.

In this article, you’ll learn how to get the current user role and ID in WordPress.

Why Get Current User Data in WordPress

There are many reasons why to get the current user data in WordPress:

  • Display different content to each user based on his role. For example, an active customer can view content others can’t.
  • Add a login and logout link to the header based on the user’s status.
  • Special discounts for logged-in users.
  • Remove the admin bar for all non-admin users.
  • Congrats to logged-in users by their first names on their account page.

These were just a few examples of the unlimited possibilities you can achieve when working with the WordPress user’s object and getting data such as role, ID, and name.

In one of our blog posts, we used a function to get the current user role to create a registration form with Elementor.

You can see many more examples when getting the current user object comes in handy in some of WordPress’s most common code snippets.

Some of the most often uses of the get current user object in WordPress will require us to retrieve the user role, ID, and name, and in the following few sections, we will learn exactly how to do it.

Get Current User Role in WordPress

Getting the current user role in WordPress is a two steps process. We will first need to check if the visitor is logged in and, if so, what’s its role.

To check if the visitor is logged in and an actual user, use this function:

is_user_logged_in()

Once we verify that the visitor is logged in, we can use the wp_get_current_user() function and get the user’s object along with all the data that comes with it.

WordPress user’s object includes relevant and valuable information regarding the logged-in user. The -> is used in object scope to access methods and properties of an object. Knowing that, wp_get_current_user()->roles will get us the current user role.

The complete code will look like that:

 if( is_user_logged_in() ) {
 $user = wp_get_current_user();
 $roles = ( array ) $user->roles;
 return $roles; // This returns an array
 // Use this to return a single value
 } else {
 return array();
 }

You can test the function by passing it inside the functions.php file of your child theme, hooking it to the header, and print the result:

add_action( 'wp_head', 'pfwp_get_current_user_role'); 

function pfwp_get_current_user_role() {
	
    if( is_user_logged_in() ) {
        $user = wp_get_current_user();
        $roles = ( array ) $user->roles;
        print_r($roles); // This will print the array of the current user roles
    } else {
    return array();
    }

}
Get current user role with a function

Once saved, visit your website and check the returned role values of the current user.

Array current user role

You can choose a specific role from that array if the user has multiple roles, such as admin and subscriber. Replace print_r($roles) with the desired value of the array, for example print_r($roles[0]).

Once you modify the code, please remember to save the changes and verify that it’s working as expected.

Get Current User ID in WordPress

Getting the current user ID in WordPress is a simple process because there is no need to invoke a new WP_User_object as we did above when getting the user role.

The code below is very similar but with less overhead. It will retrieve the current user’s ID, or 0 if no user is logged in.

get_current_user_id()

To display the user ID or congrats to a visitor with no ID, use a function like so:

if ( is_user_logged_in() ) {
echo 'User ID: ' . get_current_user_id();
} else {
echo 'Hello visitor!';
}

You can trigger it to the website header or any other part of your website using WordPress hooks.

Get Current User Name in WordPress

As explained above, the wp_get_current_user() function returns the WP_User object.

The WP user object is full of data regarding the current user.

Some attributes we can scope from that object are username, name, display name, etc.

Here are some examples of how to get that data:

Get current user first name:

$current_user->user_firstname

You can use it in a function to display the username first name like so:

if ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
echo 'Hello: ' . $current_user->user_firstname;
} else {
echo 'Hello visitor!';
}

Get current user last name:

$current_user->user_lastname

Get current user display name:

$current_user->display_name

Those were only examples of explicit content you could use with the user object.

Regardless of the function, I recommend using a backup plugin before modifying core files if something goes wrong.

Conclusion

In this article, you learned how to get WordPress’s current user data, such as role and ID.

Leave us a comment and tell us the functions and data you used or if you have any further questions regarding the process.

The post How to Get Current User Role and Name in WordPress appeared first on PluginsForWP.

]]>
https://plugins-for-wp.world/blog/get-current-user-role-wordpress/feed/ 0
How to Add ‘Continue Shopping’ Button to WooCommerce Cart Page https://plugins-for-wp.world/blog/add-continue-shopping-button-to-woocommerce-cart/ https://plugins-for-wp.world/blog/add-continue-shopping-button-to-woocommerce-cart/#respond Thu, 04 Nov 2021 17:13:38 +0000 https://plugins-for-wp.world/?p=392850 The WooCommerce cart page will only display a return to shop button when the cart is empty. When products are in the cart, the button will disappear, and you won’t see it. In this article, you’ll learn how to add a continue shopping button to the WooCommerce cart page. Why Add the Continue Shopping Button […]

The post How to Add ‘Continue Shopping’ Button to WooCommerce Cart Page appeared first on PluginsForWP.

]]>
The WooCommerce cart page will only display a return to shop button when the cart is empty.

When products are in the cart, the button will disappear, and you won’t see it.

In this article, you’ll learn how to add a continue shopping button to the WooCommerce cart page.

Why Add the Continue Shopping Button

A continue shopping button will help you to increase your store revenue.

It’s a good practice to add a call to action button to the cart and encourage your customers to add more products.

In most cases, the cart and checkout pages will act like landing pages without a header or footer.

If a customer would like to navigate back to the store, he’ll initially need to enter the home URL in the address bar and navigate to the store from there.

This extra step will slow down the checkout process and eventually affect your business’ revenue.

We need to add it because the WooCommerce cart page does not have a ‘continue shopping’ button.

Default WooCommerce cart page

The following section will show you how to add the continue shopping / return to shop button using a PHP function.

Adding the Continue Shopping Button

Adding the return to shop button is easy to accomplish by entering a PHP function into our child theme.

If you don’t already have one, read our article on how to create a child theme.

Step #1: Open the functions.php file

The functions.php file can be found inside your theme’s folder.

First, navigate to Appearance -> Theme Editor and click on the functions.php file from the list on the right.

Edit theme functions php file

Once opened, scroll to the bottom of the file.

Step #2: Paste the function

Now, copy the function below and paste it at the bottom of the PHP file.

// Add continue shopping button to WooCommerce cart
add_action('woocommerce_cart_actions', function() {
  ?>
  <a class="button wc-backward" href="<?php echo esc_url( apply_filters( 'woocommerce_return_to_shop_redirect', wc_get_page_permalink( 'shop' ) ) ); ?>"> <?php _e( 'Return to shop', 'woocommerce' ) ?> </a>
  <?php
});
Add continue shopping button function

Once pasted, save the changes and move on to the next step.

Step #3: Test the button

After you have saved the changes, let’s run a test and verify that we’ve successfully added the button.

First, add any product to the cart and then click on view cart.

Add products to cart

If the code is working correctly, you should see the return to shop button on the left just below the products list.

Return to shop button was added to cart

Click on the button and verify that you’ve been redirected to the shop page.

Conclusion

In this article, you learned to add a continue shopping button to the WooCommerce cart page.

Leave us a comment and let us know if you have any questions about the process.

The post How to Add ‘Continue Shopping’ Button to WooCommerce Cart Page appeared first on PluginsForWP.

]]>
https://plugins-for-wp.world/blog/add-continue-shopping-button-to-woocommerce-cart/feed/ 0
How to Get URL of Current Page in WordPress https://plugins-for-wp.world/blog/how-to-get-url-of-current-page-in-wordpress/ https://plugins-for-wp.world/blog/how-to-get-url-of-current-page-in-wordpress/#respond Mon, 01 Feb 2021 22:41:47 +0000 https://plugins-for-wp.world/?p=272096 When using functions with WordPress, you’ll sometimes need to get the URL of the page you’re currently on. Whether it is for a custom PHP code, snippet, or script, knowing how to get the current page URL is handy. In this article, you’ll learn how to get the URL of the current page in WordPress. […]

The post How to Get URL of Current Page in WordPress appeared first on PluginsForWP.

]]>
When using functions with WordPress, you’ll sometimes need to get the URL of the page you’re currently on.

Whether it is for a custom PHP code, snippet, or script, knowing how to get the current page URL is handy.

In this article, you’ll learn how to get the URL of the current page in WordPress.

Why Getting Page’s URL

There are many reasons to get a page’s link, depending on what the function tries to achieve.

For example, you can display the page’s URL and create a copy to clipboard button.

Other popular functions will need the current URL to display related posts at the bottom of every blog post.

Knowing how to get the current page URL is necessary and will become handy at some point or another.

Whatever the reason, getting the current page URL is a simple task, and the next section will teach you exactly how.

Get the Current Page’s URL in WordPress

The first couple of snippets in this article will work with any WordPress template file. The second part will be template-specific.

The codes will get the URL for any page type like single post, single page, the home page, taxonomies templates, search templates, custom post types, etc.

Using a child theme when working with WordPress core files is highly recommended. Please create a child theme if you don’t already have one before moving forward.

Use the code snippets below inside the functions.php file or within a custom plugin.

Use the code below to get the current page URL:

global $wp;
$current_url = home_url( add_query_arg( array(), $wp->request ) );

To get the last slug only of the current URL without the base part, use this:

global $wp;
$current_url = add_query_arg( array(), $wp->request );

For example, if your website is https://plugins-for-wp.world/post-name the code above will return just the /post-name.

You can also use the add_query_arg function to add multiple queries to the URL, which can be very useful for search and filter components.

Get current URL in specific templates

When working with WordPress templates, you can use the specific code snippets below to utilize the template and get the current URL of the page.

The snippets are very similar to each other. Make sure to replace the second line of the code based on the template you’re using.

$queried_id = get_queried_object_id();
//SECOND LINE GOES HERE

For single.php or page.php, replace the second line of the code with:

$current_url = get_permalink( $queried_id );

If you would like to get the taxonomy URLs like category or tag, replace the second line of the code with:

$current_url = get_term_link( $queried_id );

Last, for the archive page URL, replace the second line of the code with:

$current_url = get_author_posts_url( $queried_id );

To get the home page URL (it doesn’t matter which page you’re on), use the code snippet below (you don’t need the first line above):

$current_url = home_url( '/' );

Conclusion

In this article, you learn how to get the URL of the current page in WordPress.

Leave us a comment and tell us which one of the codes you used above.

The post How to Get URL of Current Page in WordPress appeared first on PluginsForWP.

]]>
https://plugins-for-wp.world/blog/how-to-get-url-of-current-page-in-wordpress/feed/ 0
How to Insert Ads and Content in Any Part Within Your WordPress Post https://plugins-for-wp.world/blog/how-to-insert-ads-and-content-in-any-part-within-your-wordpress-post/ https://plugins-for-wp.world/blog/how-to-insert-ads-and-content-in-any-part-within-your-wordpress-post/#respond Mon, 23 Mar 2020 23:58:09 +0000 https://plugins-for-wp.world/?p=7901 In this tutorial, I’m going to show you how to insert ads, images, text, or any other content to any part of your WordPress blog post without using a plugin. We will focus on three breakpoints, the beginning, middle, and the end of the post. I will provide you with three separate codes, one code […]

The post How to Insert Ads and Content in Any Part Within Your WordPress Post appeared first on PluginsForWP.

]]>
In this tutorial, I’m going to show you how to insert ads, images, text, or any other content to any part of your WordPress blog post without using a plugin.

We will focus on three breakpoints, the beginning, middle, and the end of the post.

I will provide you with three separate codes, one code for each of the post parts, and also one big code at the end to use it all together at the same time.

Also, at the end of this article, I’ll provide you with the template and common code snippets to various locations to insert your content.

How to Insert Ads or Content to WordPress Posts

The codes below need to be pasted into the functions.php file of your child theme or a site-specific plugin.

Let’s start with the first location and insert the ads or other content at the beginning of the post.

Beginning of the Post

To insert ads or any other content to the beginning of the post (before the first paragraph) use the code below:

function pfwp_insert_content_into_post($content){
	if (is_singular('post')) {  
		$beforePostContent = '<p>Content at the beginning of the post</p>';
        $closing_p = '</p>';
        $paragraphs = explode( $closing_p, $content );
        
		foreach ($paragraphs as $index => $paragraph) {
 
			if ( trim( $paragraph ) ) {
				$paragraphs[$index] .= $closing_p;
			}

			if ( $index == 0 ) {
                $paragraphs[$index] = $beforePostContent . $paragraph;
            }
		}
        $content = implode( '', $paragraphs );
	}
    return $content;
}
add_filter( "the_content", "pfwp_insert_content_into_post" );

End of the Post

To insert ads or any other content to the end of the post (after the last paragraph) use the code below:

function pfwp_insert_content_into_post($content){
    if (is_singular('post')) {
        $afterPostContent = '<p>Content at the end of the post</p>';
        $closing_p = '</p>';
        $paragraphs = explode( $closing_p, $content );
		
		foreach ($paragraphs as $index => $paragraph) {
 
			if ( trim( $paragraph ) ) {
				$paragraphs[$index] .= $closing_p;
			}

			if ( count($paragraphs) == $index + 1 ) {
                $paragraphs[$index] .= $afterPostContent;
            }
		}
        $content = implode( '', $paragraphs );
	}
    return $content;
}
add_filter( "the_content", "pfwp_insert_content_into_post" );

Middle of the Post

To insert ads or any other content exactly in the middle of the post use the code below:

function pfwp_insert_content_into_post($content){
	if (is_singular('post')) {  
        
        $closing_p = '</p>';
        $paragraphs = explode( $closing_p, $content );

        // contet to add number 1
        $insertContent_1 = '<p>Content in the middle of the post</p>';
        $position_1 = floor(count($paragraphs) / 2);
        
		foreach ($paragraphs as $index => $paragraph) {
 
			if ( trim( $paragraph ) ) {
				$paragraphs[$index] .= $closing_p;
			}
            if ( $position_1 == $index + 1 ) {
                $paragraphs[$index] .= $insertContent_1;
            }
		}
        $content = implode( '', $paragraphs );
	}
    return $content;
}
add_filter( "the_content", "pfwp_insert_content_into_post" );

More Common Positions

To insert ads or any other content to the below positions, use the mid-post template (the template above) and just replace line 7 ($position_1 = floor(count($paragraphs) / 2)) with the relevant position from the list below.

After the First Third of the Post

$position_1 = floor(count($paragraphs) / 3);

After the Second Third of the Post

$position_1 = floor(count($paragraphs) / 1.5);

After the First Paragraph of the Post

$position_1 = 1;

After the Second Paragraph of the Post

$position_1 = 2;

One Paragraph Before the End of the Post

$position_1 = floor(count($paragraphs) - 2);

Two Paragraphs Before the End of the Post

$position_1 = floor(count($paragraphs) - 3);

Insert into Multiple Areas of the Post

Many of you would like to combine some of the positions above and insert ads or other content in multiple positions of the posts.

For example, ads at the beginning of the post and images in the middle of the post.

For that, I’ve created the template below and tried to keep it as simple and easy as possible for non-developers.

The template below will insert content to the beginning, middle, and end of the post. You can leave $beforePostContent or $afterPostContent empty (like so: $beforePostContent = '';) if you don’t want any content to be added there.

Feel free to play with the mid-post position based on your needs. You can use the code snippets I mentioned above. Also, you can add more positions to the code if you desire. For example, content to the first third and the second third of the post (you can also watch the video for clarification).

function pfwp_insert_content_into_post($content){
	if (is_singular('post')) {  
		$beforePostContent = '<p>Content at the beginning of the post</p>';
        $afterPostContent = '<p>Content at the end of the post</p>';
        $closing_p = '</p>';
        $paragraphs = explode( $closing_p, $content );
        
        // Contet number 1
        $insertContent_1 = '<p>Mid post content goes here</p>';
        $position_1 = floor(count($paragraphs) / 2);
		
		foreach ($paragraphs as $index => $paragraph) {
 
			if ( trim( $paragraph ) ) {
				$paragraphs[$index] .= $closing_p;
			}

			if ( $index == 0 ) {
                $paragraphs[$index] = $beforePostContent . $paragraph;
            }

            // Add content number 1 to anywhere in the post
            if ( $position_1 == $index + 1 ) {
                $paragraphs[$index] .= $insertContent_1;
            }

			if ( count($paragraphs) == $index + 1 ) {
                $paragraphs[$index] .= $afterPostContent;
            }
		}
        $content = implode( '', $paragraphs );
	}
    return $content;
}
add_filter( "the_content", "pfwp_insert_content_into_post" );

Feel free to watch the video to better understand how it’s working. If you need another position that I did not mention in this post please leave a comment down below and I’ll add it.

Conclusion

In this article, you learned how to insert content in various places in your WordPress blog posts. Now, it’s a good time for you to copy some of the codes above and make good use of them.

Leave a comment below and let us know which code you’re using.

The post How to Insert Ads and Content in Any Part Within Your WordPress Post appeared first on PluginsForWP.

]]>
https://plugins-for-wp.world/blog/how-to-insert-ads-and-content-in-any-part-within-your-wordpress-post/feed/ 0