Adding CSS based on a PHP boolean value in WordPress

In the Bricks Facebook group a user asked:

How do I display a pseudo element depending on the presence of data in an ACF field

This Pro tutorial shows one method in which we can add CSS based on the value of a custom field.

We shall add a is_game_featured custom field of type Checkbox for posts of a game Custom Post Type.

and for posts where it is ticked,

set a label called “Featured” to be output next to the title using CSS on the front end:

In this example, we used Meta Box, although any custom fields plugin, including ACF, can be used as easily as long as the field returns true (1) or false (0). With ACF, a True / False type of field is a good choice.

Note: The end result is not the main objective of this tutorial. It could be accomplished in a quicker and easier way by adding the Featured label in the Bricks editor and conditionally rendering it based on the custom field value.

Here’s how

Add the following in child theme‘s functions.php (do not include the opening PHP tag if adding at the end) or a code snippets plugin:

<?php 

add_action( 'wp_enqueue_scripts', 'bl_styles_method_20241701' );
function bl_styles_method_20241701() {
    if ( ! is_singular( 'game' ) ) return;

    wp_register_style( 'custom-style', false );
    wp_enqueue_style( 'custom-style' );

    $css = "
        .brxe-post-title::after {
            content: 'FEATURED';
            font-size: calc(var(--text-xs) * 0.8);
            position: absolute;
            margin-inline-start: var(--space-xs);
            letter-spacing: 1px;
            background-color: var(--action);
            color: var(--action-ultra-light);
            border-radius: var(--radius-l);
            padding: calc(var(--space-xs) * 0.5) calc(var(--space-s) * 0.6);
        }
    ";

    if ( rwmb_meta( 'is_game_featured' ) ) wp_add_inline_style( 'custom-style', $css );
}

Replace is_singular( 'game' ) with the condition as appropriate for your use case. Refer to this page.

If you use ACF, replace rwmb_meta( 'is_game_featured' ) with get_field( 'is_featured' ).

If you are not using ACSS, replace the variables with those from Core Framework if using CF or another framework or px/rem/em values.