使用PHP添加CSS类


Add CSS-class with PHP

我正在安装一个WordPress,我想把它用于一个单页网站。我正在获取"query_post"数组的所有内容。对于每个页面部分,它都会创建一个id为#content的div。

<?php query_posts('post_type=page&order=ASC'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div id="content">
    <div id="inner-content" class="wrap cf">
            <div id="main" class="m-all">
                <h2><?php the_field('headline') ?></h2>
                <div class="sidebar"><?php the_field('sidebar') ?></div>
                <div class="main-content"><?php the_content(); ?></div>
            </div>
    </div>
</div>
<?php endwhile; endif; ?>

我现在想做的是根据顺序为每个页面部分添加一个特定的ID。类似的东西

<div id="content section-1">...</div>
<div id="content section-2">...</div>
<div id="content section-3">...</div>

等等。我如何修改我的代码来实现这一点?

    <?php query_posts('post_type=page&order=ASC'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div id="content section-<?php the_ID(); ?>">
    <div id="inner-content" class="wrap cf">
            <div id="main" class="m-all">
                <h2><?php the_field('headline') ?></h2>
                <div class="sidebar"><?php the_field('sidebar') ?></div>
                <div class="main-content"><?php the_content(); ?></div>
            </div>
    </div>
</div>
<?php endwhile; endif; ?>

这也是的工作

<?php query_posts('post_type=page&order=ASC'); ?>
<div id="content section-<?php echo $i++; ?>">
    <div id="inner-content" class="wrap cf">
            <div id="main" class="m-all">
                <h2><?php the_field('headline') ?></h2>
                <div class="sidebar"><?php the_field('sidebar') ?></div>
                <div class="main-content"><?php the_content(); ?></div>
            </div>
    </div>
</div>
<?php endwhile; endif; ?>

首先,从逻辑上讲,一个元素应该只有一个id。由于您正在重复整个id="content",我建议您最好添加class,然后可以添加id="content"的包装器。对于获取id,您可以简单地使用_id();这应该行得通。所以代码应该看起来像

<div id="content">
    <?php query_posts('post_type=page&order=ASC'); ?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
        <div id="inner-content<?php the_ID(); ?>" class="wrap cf">
          <div id="main" class="m-all">
                    <h2><?php the_field('headline') ?></h2>
                    <div class="sidebar"><?php the_field('sidebar') ?></div>
                    <div class="main-content"><?php the_content(); ?></div>
                </div>
        </div>
 <?php endwhile; endif; ?>
</div>

所以现在他们所有人都将拥有唯一的id:)干杯!!!