site logo

Bricks Builder: Dynamically create or delete css classes on update page

Published: 17/07/2024|147 Views|Topics: Global Class Manager, Tutorials

How to dynamically add CSS classes on every page creation to Bricks Builder global class manager?

Managing CSS classes for individual pages Bricks Builder site can be a hassle, especially when dealing with numerous pages. Automating this process not only saves time but ensures consistency across your site. In this article, we explore a custom PHP solution that hooks into WordPress’ post-saving and post-trashing processes to dynamically create and manage CSS classes for each page.

Automate CSS Class Creation with “create_class_for_every_pt”
The core of our solution lies in the “create_class_for_every_pt” function, which is designed to generate a unique CSS class for every page whenever it is saved. Here’s how it works:

function create_class_for_every_pt($post_id) {
    // Check if this is an auto-save routine. If it is, our form has not been submitted, so we don't want to do anything.
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return $post_id;
    }

    // Check the post type to ensure it's a page or post
    if (get_post_type($post_id) != 'page') {
        return $post_id;
    }

    if (get_post_status($post_id) === 'trash') {
        // If post is trashed, remove the associated class
        remove_associated_class($post_id);
        return $post_id;
    }

    $post = get_post($post_id); 
    $slug = $post->post_name;
    $global_classes = get_option('bricks_global_classes', array());

    if(!is_array($global_classes)){
        $global_classes = array();
    }

    $className = sanitize_html_class("page-" . $slug);

    // Check if the $slug is not set
    if($className === "page-"){
         return $post_id;
    }

    // Check if the class already exists
    foreach ($global_classes as $class) {
        if ($class['name'] === $className) {
            return $post_id;
        }
    }

    $classId = unique_id();

    $new_class = array(
        'id' => $classId,
        'name' => $className,
        'settings' => array(
            '_width' => '100%',
        ),
    );

    $global_classes[] = $new_class;
    // Save the updated global classes back to the options table
    update_option('bricks_global_classes', $global_classes);

    return $post_id;
}
add_action('save_post', 'create_class_for_every_pt');
  1. Auto-Save Check:
    • The function first checks if the current save operation is an auto-save. If it is, the function returns early to avoid any unintended actions, as the form has not been submitted.
  2. Post Type Verification:
    • It ensures that the post type is a ‘page’. If the post is not a page, the function exits without making any changes.
  3. Handling Trashed Posts:
    • If the post status is ‘trash’, the function calls “remove_associated_class” to remove the CSS class associated with the trashed post and returns immediately.
  4. Generating a Unique Class:
    • The function retrieves the post and its slug, then sanitizes the slug to create a valid CSS class name.
    • If the slug is empty, resulting in an invalid class name (e.g., “page-“), the function exits.
  5. Avoiding Duplicates:
    • It checks if the class already exists in the global classes array to prevent duplicate entries.
  6. Creating and Saving the Class:
    • A unique ID is generated for the new class using the “unique_id” function.
    • The new class is added to the global classes array of the Bricks Builder global class manager, which is then updated in the database.

Generate Unique Identifiers with “unique_id”

The “unique_id” function generates a unique identifier for each CSS class, ensuring there are no conflicts. It creates an 8-character substring from a MD5 hash, which is highly unlikely to produce duplicates.

function unique_id($l = 8) {
    return substr(md5(uniqid(mt_rand(), true)), 0, $l);
}

Clean Up Trashed Posts with “remove_associated_class”

When a post is moved to the trash, the “remove_associated_class” function is triggered. This function:

  1. Retrieves and Sanitizes the Post Slug:
    • It retrieves the post and its slug, sanitizing it to form the class name.
  2. Removes the Associated Class:
    • It iterates through the global classes array to find and remove the class associated with the trashed post.
    • The updated global classes array is then saved back to the database if a class is removed.
function remove_associated_class($post_id) {
    $post = get_post($post_id);
    $slug = $post->post_name;
    $className = sanitize_html_class("page-" . $slug);

    $global_classes = get_option('bricks_global_classes', array());

    if(is_array($global_classes)){
        foreach ($global_classes as $class_key => $class) {
            if ($class['name'] === $className) {
                unset($global_classes[$class_key]);
                update_option('bricks_global_classes', $global_classes);
                break;
            }
        }
    }
}
add_action('wp_trash_post', 'remove_associated_class');

Integrating with WordPress Hooks

To tie everything together, we use WordPress hooks:

  • “save_post”: This action hook triggers “create_class_for_every_pt” whenever a post is saved.
  • “wp_trash_post”: This action hook triggers “remove_associated_class” when a post is moved to the trash.

Conclusion

By implementing these functions, you can automate the creation and management of CSS classes for your Bricks Builder pages, ensuring a consistent and organized approach to page styling. This method not only saves time but keeps your CSS class list clean by removing classes when pages are trashed.

Incorporate these snippets into your theme’s functions.php file, and watch as your WordPress site becomes more manageable and your CSS more streamlined. Happy coding❗🧑‍💻


If you like it, share it with: