Forums

foreach() Problem (2 posts)

  1. ttpyro
    Member
    Posted 6 months ago #

    Hello! I am using this code to generate a simple list of all of the posts in a certain category (based on its slug) by looking at the data in a custom field called info. Here is the code:

    <?php
     global $post;
     $slug = get_post_meta(get_the_ID(), "info", true);
     $myposts = get_posts('category_name=' . $slug . '&amp;numberposts=-1');
     foreach($myposts as $post) :?>
    <?php the_title(); ?><br />
    <?php endforeach; ?>

    This code works but it has some problems with other plugins. The creator of the plugin told me, "The code you are using is wrong. foreach() is already depreciated. Refer to http://codex.wordpress.org/Template_Tags/query_posts".

    I have searched on that link for some time and I am unable to figure out what is wrong. I am very new to wordpress and even newer to php. Any idea what I should change foreach to?

    Thanks in advance.

  2. mfields
    Member
    Posted 6 months ago #

    To my knowledge "foreach" is not and probably never will be depreciated... The following code worked fine in my development server:

    $slug = 'design';
    $myposts = get_posts('category_name=' . $slug . '&amp;numberposts=-1');
    foreach($myposts as $post) {
    	the_title();
    	print '<br />';
    }

    Which leads me to believe that there is an issue with your call to:

    $slug = get_post_meta( get_the_ID(), "info", true );

    I think that get_the_id() will only work in or after the Loop, Please try intval( $post->ID ) instead. If that doesn't work, try printing out the value of $slug to the screen.

    Best of luck,
    -Mike

Reply

You must log in to post.

About this Topic