0815

Du musst dich anmelden um Beiträge und Themen zu erstellen. Einloggen · Registrieren

Display Posts with Specific Custom Fields

Displaying posts that are associated with a certain custom field is as easy as adding an “if” condition to your loop. Here is an example that checks for the presence of a custom field called “name-of-custom-field”. If such a custom field is associated with the post, the entire post is displayed; otherwise, only the excerpt is displayed.

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php $custom_field = get_post_custom_values("name-of-custom-field"); ?>

	<?php if (isset($custom_field[0])) { ?>

		<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
		<?php the_content(); ?>

	<?php } else { ?>

		<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
		<?php the_excerpt(); ?>

	<?php } ?>

<?php endwhile; endif; ?>

To get more specific and display only posts associated with a custom-field that is set to a certain value, we simply add an additional parameter to the “if” condition:

<?php if ((isset($custom_field[0])) && ($custom_field[0] == "name-of-value")) { ?>

Using that line of code, we modify our previous loop as follows:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php $custom_field = get_post_custom_values("name-of-custom-field"); ?>

	<?php if ((isset($custom_field[0])) && ($custom_field[0] == "name-of-value")) { ?>

		<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
		<?php the_content(); ?>

	<?php } else { ?>

		<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
		<?php the_excerpt(); ?>

	<?php } ?>

<?php endwhile; endif; ?>

With this code, any post with a custom-field of “name-of-custom-field” that has a specific value of “name-of-value” will be displayed in its entirety. All other posts will be displayed as an excerpt.

Source: Perishable Press




0