WordPress.org

Ready to get started?Download WordPress

Forums

turn a posts-in-category code into a function (2 posts)

  1. zandercent
    Member
    Posted 3 years ago #

    Hi

    I found this very useful piece of code in this thread - It tests whether a category has posts in.

    $test=get_posts('category_name=test');
    if ($test) {
    //found posts
    }

    How could I turn this into a function, so I can use it anywhere?
    Would it be something like this in functions.php..

    function test_category($cat) {
    $test=get_posts('category_name=$cat');
    }

    ... so then I could use it like this in the template...

    <?php if (test_category('category to be tested')) {
    ?>

    Its so I can test any category on the fly, rather than putting in the whole code. Please bear in mind that I have no idea how to write functions, but I'm trying to learn so I thought I'd give it a go! this is as much to learn how to writ a function as it is to get the answer...

  2. alchymyth
    The Sweeper & Moderator
    Posted 3 years ago #

    example:

    function test_category($cat_name='') {
    if( $cat_name && get_posts('category_name=' . $cat_name) ) return true;
    else return false;
    }

    http://www.php.net/manual/en/language.functions.php

Topic Closed

This topic has been closed to new replies.

About this Topic