I’m testing for a certain fixed post on an about page, I guessed that the best way is to test for post title (?).
Here’s my code, what’s going wrong?
<?php
if (is_page()) {
$cat=get_cat_ID($post->post_title);
$posts = get_posts ("cat=$cat&showposts=35");
if ($posts) {
foreach ($posts as $post):
setup_postdata($post); ?>
<div class="clear"></div>
<h3><?php the_title(); ?></h3>
<div class="clear"></div>
<?php if ($post->post_title('skillset')) {
echo '<div class="content">';
the_content('');
echo '</div>';
}
else{
the_content('');
}
endforeach;
}
}
?>
First off all,
$post
is one of the WordPress core global variables and as such should either not be touched or reset after yourforeach
loop.Using
setup_postdata()
allows you to make use of template tags such as you are doing in the above snippet withthe_title()
. It, or the loop it is used in, should however always be followed by its companionwp_reset_postdata()
.Also
$post
is an object. Objects are instances of classes that contain properties and/or methods, the OOP equivalents of variables and functions.By attempting to test for the post title in the way that you did,
you treated
post_title
as if it was a method and could be fed the title in question as an argument as well as would return a boolean. It however is a property and as such contains a value that you can access – and that is it.This value then needs to be tested against another value. Hence
would be a working test for the title.
Essentially that line is the answer to the question in your title. Since you however asked what might be wrong with your code, also the
showposts
argument has been deprecated for a while. Usenumberposts
instead.Also let’s revisit the initial point on using
$post
. If instead of the template tags you’d reference the properties directly, it would not be necessary to overwrite the global$post
.Would work just as well without touching the global. That just for the sake of completeness.
And as a side note, why would you use that many php opening and closing tags in such little space? Pretty much a rhetorical question: It just doesn’t make sense.
At last, are you sure, you want to do this:
? This only makes sense if you want to fetch posts of a category named exactly the same as the title of the page the visitor is on. Assuming the answer is positive, here’s the complete correction of your above snippet:
The best way would be to search for ID, not title! So then your if would be:
where 123 is the ID of the post you want to “filter”.