0

O.K. slightly strange request but I want to loop out my Custom Post type in a random order... BUT have my 'Favourite' posts stay above the rest. I would guess this is what 'Sticky' posts were meant for but I have read they dont play well with custom posts so I am wondering what is the best solution to this problem?

1 Answer 1

0

1 - I'd create a custom field for marking a post as 'favourite'.

2- Then you would add a meta_query bit to the code in which you are querying the DB.

There are several ways to do (1) and several ways to do part (2).

How familiar are you with WordPress development?

If your theme isn't being built on a framework, then the quickest way to do point (1) will probably be to use at Advanced Custom Fields Plugin.

Read the docs on their website, to create a custom field.

For this task, a checkbox type field will be relevant.

Then, on the website, you'll need to search for posts that have that custom field be whatever value indicates that is a 'favourite' (with a checkbox, the value would be 1).

There several ways, depending on how you're doing things:

(1) - WP_Query

(2) - pre_get_posts filter

(3) get_posts() function

.... several other methods.

Here's how you can do it using WP_Query, assuming your custom field is called 'is_favourite':

$args = array(
    'meta_query' => array(
        array(
            'key' => 'is_favourite',
            'value' => 1
        )
    ),
'orderby' => 'meta_value_num rand',
'posts_per_page'=>-1
);

$the_query = new WP_Query( $args );

For a full explanation of how to use WP_Query - https://codex.wordpress.org/Class_Reference/WP_Query

1
  • Thanks Dan, for those interested I used this to solve my question with one slight change to remove the value from the 'meta_query' argument as it was only selecting the favourites. Nov 25, 2016 at 14:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.