开发者

display tagged posts AND custom posts in featured section

In a homepage featured section I would like to display the 7 latest posts that are either re开发者_运维技巧gular posts tagged with tag id#50 OR custom type posts with post-type sp_events.

This isn't working. Presumably because tag__in is filtering out the untagged custom type posts. My php is so bad I can't see how to correct this.

    query_posts(
        array(
            'tag__in' => array(50),
            'showposts' => '7',
            'post_type' => array('post', 'sp_events')
        )
    );

Thanks.


If I'm not mistaken (which I most certainly may be), you can't do a query like you're trying to do with Wordpress's built in functions.

What you can do is in your functions.php file (where one stores the theme's custom functions) having a function which takes an array of argument arrays and loops through them with every pass adding the returned posts to an array. I think get_posts() would be the best function to use for this since it returns the posts in an array instead of needing the Loop.

function query_posts_multiple($arrArgs)
{
  if (!is_array($arrArgs)) return false; // Prevents warnings and fatal errors.
  $posts = array();

  foreach ($arrArgs as $args)
  {
    $posts = array_merge($posts, get_posts($args));
  }

  return $posts;
}

For the args array, here's an example:

$args = array();
$args[] = array(
  'numberposts'     => 7,
  'tag'             => "50",
);

You would just use a foreach() loop in your theme. You would access the data using a $post->column fashion.

$posts = get_posts_multiple($args);
foreach ($posts as $post)
{
  // call all the $post->COLUMNs your heart desires
}
unset($posts); // Delete that variable just to be safe.

To limit the number of posts, just keep count and stop the loop when you reach a certain number. To randomize your array, you can use shuffle().

This is probably a very, very dirty way of doing this, blame it on my extreme tiredness...

Logan


I've worked it out. And the solution is dead simple: instead of trying to make the filter apply only to the 'regular' posts, let the tag apply to the custom post type posts as well. I didn't realize the tags would share across post types.

I just added the following to functions.php and tagged the custom post type posts:

add_action('init', 'add_taxonomy_objects');

function add_taxonomy_objects() {
register_taxonomy_for_object_type('post_tag', 'sp_events');
}'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜