如何让自定义WordPress页面加载自定义CSS样式?
Hey there! Let's break down why your custom pages aren't loading CSS for the content area and fix it step by step:
1. Your empty content.php is the core issue
Right now, you're calling get_template_part( 'content', get_post_format() ) in page.php, but since content.php has no code, WordPress isn't outputting any HTML structure for your page content. Without proper container elements with classes, your CSS has nothing to target.
Update your content.php with a semantic, WordPress-standard structure:
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <h1 class="entry-title"><?php the_title(); ?></h1> </header> <div class="entry-content"> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'mytheme' ), 'after' => '</div>', ) ); ?> </div> </article>
post_class()adds dynamic classes (likepagefor static pages) that let you style pages specifically.entry-contentis a universal class for main content, making it easy to apply consistent styles.
2. Ensure your CSS loads on all pages
Double-check your functions.php to confirm your stylesheet is enqueued for every front-end page (not just the homepage). Add this standard code if it's missing:
function mytheme_enqueue_styles() { // Load the main theme stylesheet wp_enqueue_style( 'mytheme-main-style', get_stylesheet_uri() ); } add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_styles' );
The wp_enqueue_scripts hook triggers on all front-end pages, so this guarantees your CSS loads everywhere—including custom pages.
3. Write CSS targeting your content elements
Now you can add styles to your style.css that target the classes we added in content.php. For example:
/* Style the main page content container */ .entry-content { max-width: 900px; margin: 3rem auto; padding: 0 1.5rem; color: #333; line-height: 1.7; } /* Style the page title */ .entry-title { font-size: 2.2rem; font-weight: 700; text-align: center; margin-bottom: 2rem; color: #2d3748; }
4. Verify your page.php has a complete structure
Make sure your page.php includes calls to the header and footer (which load your CSS and site layout). A full, proper page.php should look like this:
<?php get_header(); ?> <div class="container"> <div class="row"> <div class="col"> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); get_template_part( 'content', get_post_format() ); endwhile; endif; ?> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.container --> <?php get_footer(); ?>
Once you implement these changes, your custom pages should display styled content just like your homepage. The key was giving your content proper HTML containers with targetable classes, and ensuring your stylesheet loads consistently across all pages.
内容的提问来源于stack exchange,提问作者retinanets

