Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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/
<?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.1
*/
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 ) {
$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