Support » Fixing WordPress » How to pass this variable? PHP kung-foo masters please help

  • Resolved blogjunkie

    (@blogjunkie)


    Hi, I’ve hacked my WordPress template lots. I want to pass a variable from the custom field to a WP_Query.

    First I get the variable from the custom field my_cat


    <?php
    $my_cat = get_post_meta($post->ID, 'my_cat', true);
    ?>

    Then I want to pass $my_cat to this query below


    <?php
    $archive_query = new WP_Query('showposts=9999&cat=&my_cat'); // this isn't working
    while ($archive_query->have_posts()) : $archive_query->the_post();
    ?>

    .. do stuff ..

    <?php endwhile; ?>

    Basically what i’m trying to do is to filter posts by category. I define the category ID in $my_cat through a custom field (call it ‘n’). Then I want to pass it as an argument to WP_Query as cat=n, where n equals $my_cat.

    Thanks in advance.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator Samuel Wood (Otto)

    (@otto42)

    WordPress.org Admin

    There’s two ways to do it. Which you use depends on your specific needs.

    Method 1 (String Concatenation):
    $archive_query = new WP_Query('showposts=9999&cat='.$my_cat);

    The dot operator is how you concatenate strings.

    Method 2 (Double quoted string):
    $archive_query = new WP_Query("showposts=9999&cat=$my_cat");
    When a string is double quoted in PHP (instead of single quoted) variables will be parsed and inserted within it.

    Method 2 looks easier to do, but it uses more memory than method 1. Still, it’s handy in some cases.

    blogjunkie

    (@blogjunkie)

    Thanks Otto, that worked like a charm :o)

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘How to pass this variable? PHP kung-foo masters please help’ is closed to new replies.