How to hide empty content modules in WordPress custom post types using PHP and JavaScript

When managing dynamic content in WordPress—especially with custom post types (CPTs) like “Attorneys” or “Team Members”—you may find yourself needing to conditionally hide modules (e.g., credentials, court admissions, education blocks) if their content is blank. This ensures a cleaner and more professional front-end experience.

Issue background

On a WordPress site built with custom post types, there was a need to hide empty fields or cards—specifically a “Court Admissions” card—from displaying if no data had been entered. Displaying blank modules can lead to poor UX and visual clutter.

Diagnosis

The content modules were structured as .card elements. Each card represented a different type of profile credential and was being rendered regardless of whether its content was populated.

Rather than hardcoding the condition into each card’s PHP template, the development team wanted a flexible solution that would hide any blank .card modules automatically.

Resolution steps

  1. Developed a hybrid PHP + JavaScript snippet:
    A lightweight script was written to run only on the relevant custom post type (e.g., attorney).
  2. PHP conditional wrapper:
    Code was added to enqueue the script only on the CPT page. This minimized unnecessary load across the rest of the site.
  3. JavaScript logic:
    The script loops through all .card modules on the page and hides any whose inner HTML is empty or contains only whitespace.
  4. Scalable for future use:
    Although the task initially targeted the “Court Admissions” section, the solution was built to apply to any .card on the CPT. Additional logic can be added to target specific cards if needed.
document.addEventListener('DOMContentLoaded', function () {
  const cards = document.querySelectorAll('.card');
  cards.forEach(card => {
    if (!card.textContent.trim()) {
      card.style.display = 'none';
    }
  });
});

Final outcome

The implementation successfully removed empty cards from display on attorney profile pages. This approach is now scalable for any custom post type where empty content modules should be excluded from the frontend.

Need help cleaning up conditional content rendering on your WordPress site? Contact Freshy for custom solutions that improve performance and polish.