Looking to do enable or disable shortcode in a function, depending on a value. For instance, if someone says purchases a license key to use some shortcode on their site, I'd like to have the shortcode become disabled if they license expires. Example function I've been working on below:
my_premium_shortcodes(); // Fires early in my php file
function my_premium_shortcodes(){
$status = get_option( 'key_status' );
if( $status !== false && $status == 'valid' ) {
add_shortcode('shortcode_handle_1','shortcode_function_1');
add_shortcode('shortcode_handle_2','shortcode_function_2');
} else {
remove_shortcode('shortcode_handle_1','shortcode_function_1');
remove_shortcode('shortcode_handle_2','shortcode_function_2');
}
}
Any input on my approach or if the function should be handled in a separate way would be appreciated. As it stands, the shortcodes are working when everything is enabled, but stay enabled even after the 'status' changes to 'invalid'.
You should use the code in two different functions instead of one single function. Please review below code and implement into your site.
$status = get_option( 'key_status' );
if( $status !== false && $status == 'valid' ) {
//add a custom shortcode
add_action( 'init', 'my_add_shortcodes' );
function my_add_shortcodes() {
add_shortcode( 'myShortcode', 'my_shortcode_function' );
}
else{
//which can also remove
add_action( 'init', 'remove_my_shortcodes',20 );
function remove_my_shortcodes() {
remove_shortcode( 'myShortcode' );
}
Just wanted to post an update. The value of the status was apparently not properly being read by previous functions I had in my code. Essentially, just having my 'if' statement and removing the 'else' was all I needed to do.
So this works fine FYI:
function my_premium_shortcodes(){
$status = get_option( 'key_status' );
if( $status !== false && $status == 'valid' ) {
add_shortcode('shortcode_handle_1','shortcode_function_1');
add_shortcode('shortcode_handle_2','shortcode_function_2');
}
}
If the 'key_status' is actually being read, otherwise the shortcode was always firing.
Add shortcode function code into the function.php file or in the plugin file.
function my_add_shortcodes() {
// Add your code here
}
add_shortcode( 'myShortcode', 'my_shortcode_function' );
Use the below condition to call the shortcode in any file of your theme.
$status = get_option( 'key_status' );
if( $status !== false && $status == 'valid' ) {
echo do_shortcode('[myShortcode]');
}
I hope it will help you.
Related
I've got a technical question to which I would like to have insights more than a solution.
I hooked a custom function to 'template_include' filter in WordPress functions.php as below to work on a page without it being watchable by anyone else.
function template_redirect( $template ) {
if ( $template === locate_template('single-ressource.php') && get_current_user_id() === 11 ) {
return $new_template = locate_template( array( 'single.php' ) );
}
return $template;
};
add_filter( 'template_include', 'template_redirect', 99 );
So if anyone who's not logged into my account go to a 'ressource' custom post type page, they see it with the standard single.php layout and not with the single-ressource.php layout.
The thing is, it doesn't work as is. I have to change the 11 integer in the strict comparison to '11' string to make it work (see edit), as below.
function template_redirect( $template ) {
if ( $template === locate_template('single-ressource.php') && get_current_user_id() === '11' ) {
return $new_template = locate_template( array( 'single.php' ) );
}
return $template;
};
add_filter( 'template_include', 'template_redirect', 99 );
I went to see the official documentation for the get_current_user_id() function and it seems that they use type casting to return either an integer or 0.
Furthermore, when I do a var_dump(get_current_user_id()) on my front-end, it returns int(11).
Anyone has an idea about why the second code works (see edit) and not the first one?
Edit
As #Bazaim pointed it out, I was just confused about the logic involved.
With the second code, the actual "single-ressource.php" I wanted to hide wasn't hidden to anyone because the logic behind the condition passed was flawed. I was redirecting only users with a user_id equal to a string '11' which is no one because user_id are integers.
The code below works perfectly.
function template_redirect( $template ) {
if ( $template === locate_template('single-ressource.php') && get_current_user_id() !== 11 ) {
return $new_template = locate_template( array( 'single.php' ) );
}
return $template;
};
add_filter( 'template_include', 'template_redirect', 99 );
Your user_id is 11 ?
You require to see single.php :
$template to be 'single-ressource.php' : right
get_current_user_id() to be 11 : wrong, you want the id not to be 11
Im trying to use the code below for my plugin development but there is a caching issue (I think). Please below for the details.
Problem
I created a filter to accept the customized url, and I'm querying the database but it seems like the result value is not changing in the browser but changing in the database. So basically the data passed is not returning the updated value from the database.
Code
add_action( 'init', function() {
add_rewrite_rule('coupon/([a-zA-Z0-9]+)[/]?$', 'index.php?coupon=$matches[1]', 'top');
});
add_filter('query_vars', function( $query_vars ) {
$query_vars[] = 'coupon';
return $query_vars;
});
add_action( 'template_include', function( $template ) {
if ( get_query_var( 'coupon' ) == false || get_query_var( 'coupon' ) == '' ) {
return $template;
}
ob_clean();
ob_start();
// Check if coupon exists
global $wpdb;
$coupon = get_query_var('coupon');
$coupon_query = $wpdb->prepare('SELECT * FROM wp_urls WHERE coupon = %s AND claimed_at IS NULL', $coupon);
$coupon_available = $wpdb->query($coupon_query) ? true : false;
if(!$coupon_available) {
header('Location: /'); // Redirect to landing page
exit();
}
return plugin_dir_path(__FILE__) . 'views/client/index.php';;
} );
Expected Result
The expected result should redirect the user to the header('Location: /'); if the coupon is not available.
Any idea?
You need update the permalinks in the WordPress admin area. For example:
Step 1: In the WordPress admin area, go to `Settings > Permalinks`
Step 2: Click `Save Changes`
Step 3: Permalinks and rewrite rules are flushed.
I want to redirect the user to cart page after he logs in if the cart is not empty. I am trying this:
function woocommerce_custom_redirects() {
if(!WC()->cart->is_empty() )
wp_redirect( "https://edkasa.com/checkout" );
}
add_action('wp_login', 'woocommerce_custom_redirects');
But this is not working, I am using buddypress plugin, any idea where am I going wrong.
With the wp_redirect() Function, it is suggested to follow that up with an explicit call to exit. For further Information on that, see Documentation.
You may thus try adding that to your Code... Something like:
function woocommerce_custom_redirects() {
ob_start(); // COULD BE A GOOD IDEA
if ( WC()->cart->get_cart_contents_count() !== 0 || !WC()->cart->is_empty() ) {
wp_redirect( "https://edkasa.com/checkout" );
exit; // VERY VITAL HERE TO EXPLICITLY CALL exit...
}
}
add_action('wp_login', 'woocommerce_custom_redirects');
I am looking for and can not find anywhere as I can redirect the empty woocommerce cart to the homepage. I only find redirects that go to the store.
This is what I find, but I do not need to redirect to the home:
add_action("template_redirect", 'redirection_function');
function redirection_function(){
global $woocommerce;
if( is_cart() && WC()->cart->cart_contents_count == 0){
wp_safe_redirect( get_permalink( woocommerce_get_page_id( 'shop' ) ) );
}
}
Thanks
just removed static link of previous answer.
function woocommerce_custom_redirects() {
ob_start(); // COULD BE A GOOD IDEA
if ( WC()->cart->get_cart_contents_count() !== 0 || !WC()->cart->is_empty() ) {
global $woocommerce;
$checkout_url = $woocommerce->cart->get_checkout_url();
wp_redirect($checkout_url);
exit; // VERY VITAL HERE TO EXPLICITLY CALL exit...
}
}
add_action('wp_login', 'woocommerce_custom_redirects');
For my website I’m using the plugin Woocommerce Variations to Table Grid, but I would like to restrict this one only for some roles ‘Administrator’ and ‘wholesaler’. (my website is for wholesalers and ‘normal’ customer)
Anyway I was thinking to just desactivate the plugin by checking the user role so I tried the following solution : https://wordpress.stackexchange.com/questions/159085/deactivate-plugin-for-a-specific-user-group
Doesn’t work.
I’ve got a variable in my plugin called $vartable_disabled which is a boolean which “Disable globally” the plugin.
So I am thinking to do something in my functions.php like:
add_action('admin_init', 'my_option_change_plugins');
function my_option_change_plugins()
{
global $current_user;
if (!in_array('administrator' || 'wholesaler', $current_user->roles)) {
deactivate_plugins( // activate for variation-table
$vartable_disabled == 0
$vartable_position == 'under'
);
} else { // desactivate for those than can't use it
activate_plugins(
$vartable_disabled == 1
$vartable_position == 'side'
);
}
But for sure I’m doing something wrong, I tried plenty of different thing the whole day, impossible to figure it out.
Anyone can help?
Cheers 🙂
deactivate_plugins is need. base plugin name. But you are passing variables.
https://codex.wordpress.org/Function_Reference/deactivate_plugins
I found a partial solution with the function "update_option()"
add_action('admin_init', 'my_filter_the_plugins');
function my_filter_the_plugins()
{
global $current_user;
if (in_array('administrator', $current_user->roles)) {
update_option( 'vartable_disabled', 0 );
} else { // activate for those than can use it
update_option( 'vartable_disabled', 1 );
}
}
With that my plugin option switch to '1' (disabled).. but the thing is, it doesn't matter the role as it always go only for the first line..
I'm a bit lost, I don't understand why it works in one way but not the other.
My plugin fonction is:
if ( ((get_post_meta($product->id, 'disable_variations_table', true) == 1 || !empty($checkcat)) || $vartable_disabled == 1) && $vartable_shortcd != 1) {
// Enqueue variation scripts
wp_enqueue_script( 'wc-add-to-cart-variation' );
// Load the template
wc_get_template( 'single-product/add-to-cart/variable.php', array(
'available_variations' => $product->get_available_variations(),
'attributes' => $product->get_variation_attributes(),
'selected_attributes' => $product->get_variation_default_attributes()
) );
return;
}
I think there's a little misunderstanding of a point. A plugin can't be activated for an user and deactivated for another one (in the pure concept of Plugin Activation/Deactivation). It is globally activated or globally deactivated.
Said this, depending on the way that your plugin is programmed, its functions could be disabled to certain users or groups. Instead keeping trying the deactivation method you can, for example, find the parts where your plugin admits to be filtered and take advantage of that. If there is not filters, you can try:
$current_user = wp_get_current_user();
if ( !in_array( array( 'administrator' , 'wholesaler' ) , (array) $current_user->roles ) ) {
update_option( 'vartable_disabled' , 1 ); // Assuming 'vartable_disabled' parameter really disables the plugin for the current user
}
In addition, alike you can hide all the html related to that option (checkboxes, menu elements and others).
It finally didn't work as expected because to change an option you need kind of "administrator" rights, so for the other roles like "customer" it didn't change the option as expected.
Anyway, instead I worked with the plugin developer (thanks Spyros) and the solution has been to hook directly in the plugin (functionnality now added to the new plugin version ;))
The following code has been added:
// if the table is disabled for this product display the default select menus
$checkcat = array();
if (is_array($vartable_categories_exc) && is_array($pcids)) {
$checkcat = array_intersect($pcids, $vartable_categories_exc);
}
$checkrole = array();
if (is_array($vartable_roles_exc) && is_user_logged_in()) {
$user_info = get_userdata(get_current_user_id());
$checkrole = array_intersect($user_info->roles, $vartable_roles_exc);
}
if (!is_user_logged_in() && is_array($vartable_roles_exc) && in_array('guest', $vartable_roles_exc)) {
$checkrole['guest'] = 'guest';
}
if (
((get_post_meta($product->id, 'disable_variations_table', true) == 1 || !empty($checkcat)) || $vartable_disabled == 1 || !empty($checkrole))
&& get_post_meta($product->id, 'disable_variations_table', true) != 2
&& $vartable_shortcd != 1) {
// Enqueue variation scripts
wp_enqueue_script( 'wc-add-to-cart-variation' );
// Load the template
wc_get_template( 'single-product/add-to-cart/variable.php', array(
'available_variations' => $product->get_available_variations(),
'attributes' => $product->get_variation_attributes(),
'selected_attributes' => $product->get_variation_default_attributes()
) );
return;
}
Thanks everyone for your time/help.
When I attempt the following I get Warning: Cannot modify header information - headers already sent by......
I'm trying to require a user to be logged in before they access my page with the shortcode on it.
What am I missing? Thanks a million for any help you can offer.
add_shortcode( 'guest-posts', 'guestposts_shortcode' );
function guestposts_shortcode( $atts ) {
auth_redirect();
}
It may work if you parse the post content before to render it. Then you should check if you find the shortcode inside the content.
Here is a small generic function to check it :
function has_shortcode($shortcode = '') {
global $post;
if (!$shortcode || $post == null) {
return false;
}
if ( stripos($post->post_content, '[' . $shortcode) !== false ) {
return true;
}
return false;
}
Now we have to create a function that will check for our specific shortcode :
function unlogged_guest_posts_redirect() {
if(has_shortcode('guest-posts') && !is_user_logged_in()) {
auth_redirect();
}
}
Then we have to hook our function (I think this can work in "wp" hook, but you can try anohter if it does not) :
add_action('wp', 'unlogged_guest_posts_redirect');
To finish, we have to ensure that the shortcode won't echo anything :
add_shortcode( 'guest-posts', 'guestposts_shortcode' );
function guestposts_shortcode( $atts ) {
return false;
}
Actually we are dealing with shortcodes but we're not using the WordPress shortcode API. This functionnality should be done using a custom field, it would be simpler !
You could instead create a special category, and hook into template_redirect:
add_filter('template_redirect', function() {
if (is_single() && in_category('special') && !is_user_logged_in())
wp_redirect(site_url('/wp-login.php'));
});