WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] can't get this WP_Query to work (8 posts)

  1. richerimage.co.uk
    Member
    Posted 2 years ago #

    Hi, hope someone can help...

    First and foremost php is not my forte but I hope you at least get the gist of where I'm trying to head with this...

    I want to spit out a little loop of post assigned to a category. Rather than code the category ID into a page template I need it so the client can change the category within the admin area.

    So, I would like to add a custom_field named 'category' where one will simply enter the slug of the category they wish the loop to be published from.

    This is what I have (and doesn't work)

    <?php $category = get_post_meta($posts->ID, 'category', true); 
    
    $query = new WP_Query( 'category_name=$category' );
    
    while ( $the_query->have_posts() ) : $the_query->the_post();
    	echo '<li>';
    	the_title();
    	echo '</li>';
    endwhile;
    
    // Reset Post Data
    wp_reset_postdata();
    
    ?>

    My humble thanks in advance :)

    Richard

  2. esmi
    Forum Moderator
    Posted 2 years ago #

    Try using $query = new WP_Query( 'category_name=' . $category );

  3. richerimage.co.uk
    Member
    Posted 2 years ago #

    Hi

    Thanks but still no joy :-/

    Any other ideas?

    Your help is greatly appreciated, thank you :)

  4. esmi
    Forum Moderator
    Posted 2 years ago #

    In what way is your code "not working"?

  5. richerimage.co.uk
    Member
    Posted 2 years ago #

    Hi Esmi

    Thank you for getting back...

    It wasn't working as in it doesn't restrict the loop to the assigned category.

    ?php
    
    $category = get_post_meta($posts->ID, 'category', true); 
    
    // The Query
    $the_query = new WP_Query( 'category_name=' . $category . '&showposts=4' );
    
    // The Loop
    while ( $the_query->have_posts() ) : $the_query->the_post();
    	echo '<li>';
    	the_title();
    	echo '</li>';
    endwhile;
    
    ?>
  6. richerimage.co.uk
    Member
    Posted 2 years ago #

    Just in case - the missing '<' at the opening of that last snippet is a typo - it is there :)

  7. esmi
    Forum Moderator
    Posted 2 years ago #

    Does the category custom field hold the category name or slug? It needs to be the latter if you want to use category_name in WP_Query.

  8. richerimage.co.uk
    Member
    Posted 2 years ago #

    Hi Esmi

    Yes, the custom field holds the slug.

    Good news though - change $posts to $post and hey presto! :)

    $category = get_post_meta($post->ID, 'category', true);

    Thank you for your help!

Topic Closed

This topic has been closed to new replies.

About this Topic