WordPress.org

Support

Support » How-To and Troubleshooting » [Resolved] can't get this WP_Query to work

[Resolved] can't get this WP_Query to work

  • 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

Viewing 7 replies - 1 through 7 (of 7 total)
  • esmi

    @esmi

    Forum Moderator

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

    Hi

    Thanks but still no joy :-/

    Any other ideas?

    Your help is greatly appreciated, thank you 🙂

    esmi

    @esmi

    Forum Moderator

    In what way is your code “not working”?

    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;
    
    ?>

    Just in case – the missing ‘<‘ at the opening of that last snippet is a typo – it is there 🙂

    esmi

    @esmi

    Forum Moderator

    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.

    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!

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘[Resolved] can't get this WP_Query to work’ is closed to new replies.