Last active
April 24, 2023 09:53
-
-
Save damiencarbery/91dc7c95255162b5b462cae65d7459dd to your computer and use it in GitHub Desktop.
Conditionally show an Elementor section - A demo of how to conditionally show an Elementor section using the section ID and class. https://www.damiencarbery.com/2022/05/conditionally-show-an-elementor-section/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: Conditionally show an Elementor section | |
Plugin URI: https://www.damiencarbery.com/2022/05/conditionally-show-an-elementor-section/ | |
Description: A demo of how to conditionally show an Elementor section using the section ID and class. | |
Author: Damien Carbery | |
Author URI: https://www.damiencarbery.com | |
Version: 0.2 | |
*/ | |
defined( 'ABSPATH' ) || exit; | |
class ConditionallyDisplayElementorSection { | |
private static $instance; | |
private $conditional_section; // CSS class of sections that will be examined. | |
private $today; // Full text for day of week - will be section ID. | |
// Returns an instance of this class. | |
public static function get_instance() { | |
if ( null == self::$instance ) { | |
self::$instance = new ConditionallyDisplayElementorSection(); | |
} | |
return self::$instance; | |
} | |
// Initialize the plugin variables. | |
public function __construct() { | |
// CSS class of sections that will be examined. | |
$this->conditional_section = 'day_of_week'; | |
// Full text for day of week - Sunday through Saturday. | |
$this->today = date( 'l' ); | |
$this->init(); | |
} | |
// Set up WordPress specfic actions. | |
public function init() { | |
// Examine user meta to determine whether to display sections that have the $conditional_section class. | |
add_filter( 'elementor/frontend/section/should_render', array( $this, 'whether_to_display_section' ), 10, 2 ); | |
} | |
function whether_to_display_section( $should_render, $section ) { | |
if ( is_admin() ) { return $should_render; } // Display when in Dashboard (when editing the page). | |
$settings = $section->get_settings_for_display(); | |
// Check if the section's CSS classes contains $conditional_section class before comparing | |
// the ID against the current day of the week. | |
if ( false !== strpos( $settings['css_classes'], $this->conditional_section ) ) { | |
if ( $this->today != $settings['_element_id'] ) { | |
return false; | |
} | |
// Note: You can add different tests here e.g. whether user is logged in or has certain privileges etc | |
} | |
return $should_render; | |
} | |
} | |
$ConditionallyDisplayElementorSection = new ConditionallyDisplayElementorSection(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment