• Resolved onewayticket

    (@onewayticket)


    Hi,

    I’m using these four lines on my home page template to set a category and then display only posts from that category, organized according to a custom field:

    $ctheory_category = 'Theorizing 21c';
    query_posts('meta_key=Filename&orderby=meta_value&order=DESC&posts_per_page=-1&category_name='.$ctheory_category);
    echo "<h1 id=\"category-header\">" . $ctheory_category . "</h1>";
    get_template_part('content', 'home');

    I’ve then copied and pasted this for each category I wish to display on the home page. The result can be seen here:

    https://ctheory.net/wordpress_test/

    I’m a PHP novice and have worked with WordPress a bit, and it seems like their must be a better way to do this. It works, but as I’m trying to set up a page that displays all of the categories, I realize there must be a way, and it would be useful for the future, to do this without resorting to cut and paste. I tried using pre_get_posts() but it didn’t work or broke the site. I don’t mind reading/learning more about the WordPress functions, I’m just searching for the best way to do what I need to do so I don’t waste a bunch of time trying things that don’t work. Thanks in advance for any help!

Viewing 4 replies - 1 through 4 (of 4 total)
  • If you want to display all categories, try using a foreach loop and display them all.
    Something like

    foreach ($category as $cat){
       echo $cat['name'];
    }

    Thread Starter onewayticket

    (@onewayticket)

    Ok, I think I’ve figured out a way to use that on my site:

    $args = array(
    	'orderby' => 'name',
    	'order' => 'ASC',
    	'exclude'  => '3');
    
    	$categories = get_categories($args);
            //var_dump($categories)
    
    	foreach ($categories as $cat) {
    	echo "<h1 id=\"category-header\">" . $cat->name . "</h1>";
         query_posts('meta_key=Filename&orderby=meta_value&order=DESC&posts_per_page=-1&category_name='.$cat->name);
    	get_template_part('content', 'home');
    				}

    But is there a way to choose the order that the categories sort by, preferably a user-defined order? I found a blog post on this:

    https://www.wphub.com/sorting-categories-custom-sort-order/

    But just wondering if there is a simple way not involving plugins & etc?

    Thread Starter onewayticket

    (@onewayticket)

    Thread Starter onewayticket

    (@onewayticket)

    OK sorry I figured it out there’s a plugin that adds the ability for the user to organize categories and seems to work well. Thanks for the foreach tip!

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Better way to do a custom loop?’ is closed to new replies.