0

Is there a way to doing this easily like

  1. There are three or may be more
  2. I want to display the posts of above categories like

    Bring posts from categories 
    From Category A: 20%  OR 2
    From Category B: 50%  OR 5
    From Category C: 30%  OR 3
    
  3. The categories may be odd or even as well as the ratio (percentage) etc.

If there is a proper way around?

5
  • Nothing, I am just googling around and didn't find any good! Oct 10, 2017 at 13:18
  • Is it not simple? Count all posts in each category. Then, output you're desired number of posts per category in a loop... You can use a percentage based value by turning the number of posts in category X into a percentage
    – Ashtmdu
    Oct 10, 2017 at 13:25
  • Yes, I know this method and thank you explaining me. I want a better solution, actually I want to avoid much looping and querying in database as well. Oct 10, 2017 at 13:27
  • This is the only way. Even if there were built in Wordpress functions to do this, under hood they would be looping too. Loop and query to database isn't an issue for this simple request...
    – Ashtmdu
    Oct 10, 2017 at 13:43
  • Why do you think that this is a 'bad' solution and what is your idea of a 'better' solution?
    – Ashtmdu
    Oct 10, 2017 at 13:44

2 Answers 2

0

It appears to me to be fairly easy. You just reference https://codex.wordpress.org/The_Loop

You could create two loops, the first to identify how many posts there are in Category A, Category B, and Category C.

Then you take from category A 20% of the total number of posts (converted to an integer), then from category B a total of 50% of the total number of posts minus those to A (again integer conversion) and the remainder go to category C.

Once you know how many to take from each, then you can run the loop again.

There are probably more elegant ways to do this, but I suspect this just gets the job done and gets you on to other issues more quickly.

Please let me know if you need more detail. (WP_query might be another approach from https://developer.wordpress.org/reference/classes/wp_query/ )

0

Finally its been achieved, here is the link: https://gist.github.com/vpadhariya/fcd1c3758d7bbf0fc26ee52959d73e42

Your Answer

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

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