WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How to pass this variable? PHP kung-foo masters please help (3 posts)

  1. blogjunkie
    Member
    Posted 6 years ago #

    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.

  2. Samuel Wood (Otto)
    Tech Ninja
    Posted 6 years ago #

    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.

  3. blogjunkie
    Member
    Posted 6 years ago #

    Thanks Otto, that worked like a charm :o)

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags