PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, February 17, 2022

[FIXED] wordpress php query by category name

 February 17, 2022     php, wordpress     No comments   

Issue

I was wondering to do separate blog pages for separate category posts. What I was able to find was running query by category number, but this is not dynamic enough for me as I would like to run query on page title which is = category name.

Basically on page "events" I would like to display blog posts that are under category named "events"(category name == page title), and so on.

Any insights on how to achieve this would be great. What I tried to do and failed, was:

<?php query_posts('category_name='.get_the_title()); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <div>
        <h1><?php the_title(); ?></h1>
        <p><?php the_content(); ?></p>
    </div>
<?php endwhile; else: ?>no match<?php endif; ?>

Thanks in forward for any insights, links or notices.


Solution

First of all, never ever use query_posts. It breaks the main query, reruns queries that slows your page, incorrectly sets vital functions used by plugins, functions like get_queried_object() and it messes up pagination.

If you need to run custom queries, make use of WP_Query.

To come to your original issue, the default category parameters don't make use of category names, only slugs and ID's. The slugs are controllable, so you might want to use slugs with the category_name parameter.

If you do need to pass category names, then you should use a tax_query which do accept names passed to the terms parameter

You can pass the following with your parameters

'tax_query' => array(
    array(
        'taxonomy' => 'category',
        'field' => 'name',
        'terms' => 'name of your category',
        'include_children' => false,
    ) ,
);


Answered By - Pieter Goosen
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing