I need to find out how to list my content data on a page/ section when I click on a specific category link.
After a few hours I realise that help from stackoverflow is what i need!
The function remind a little of: http://www.hashbangcode.com/blog/wordpress-category-post-list-493.html
I need to list my data (title, the_content etc) from the specific category and not all categories with the titles.
While that post gives you a good start, here is the code that I would use
// Set the desired category
$category = 1;
// Make query for posts in the category
$my_query = new WP_Query();
$my_query->query(
array(
'cat' => $category,
// Does not show sticky posts; use 'caller_get_posts' if using < WP 3.1
'ignore_sticky_posts' => 1
)
);
// Make sure some posts were found.
if($my_query->have_posts())
{
// Loop through each post found.
while($my_query->have_posts())
{
// Setup the post data to use
$my_query->the_post();
global $post;
// Echo out the title; Note that no formatting has been done
the_title();
the_content();
}
}
Now, you can also get the title with either:
$title = get_the_title($post->ID);
$title = $post->post_title;
Additionally, you can get the post content with:
$content = $post->post_content;
Also, you can get the category using any of these parameters:
cat (int) - use category id.
category_name (string) - use category slug (NOT name).
category__and (array) - use category id.
category__in (array) - use category id.
category__not_in (array) - use category id.
More about the WP_Query class can be found here: http://codex.wordpress.org/Function_Reference/WP_Query
Related
I have a custom post type of 'products' and in single-products.php I want to show all child categories of the current posts' primary category (used for navigation)
How would I do this? Have tried a few options and nothing works thus far.
Any help would be appreciated.
First you will get the category of the post using: $cat = get_the_category($post->ID);
Then you will get the children of that category using: $cat_children = get_term_children( $cat, 'category' );
Then you will loop through the children like so:
foreach($cat_children as $child) {
$term = get_term_by('id', $child, 'category');
// Display children here
}
Here are links to each of the functions referenced here:
get_the_category()
get_term_children()
get_term_by()
EDIT: You can swap out the category term in each of these functions to target custom taxonomies.
I'm using WordPress with a template that generates a pretty nice thumbnail for each post depending on Ids, and type of post. (ref:https://blinkdemo.wordpress.com/)
Since I've been asked to create a custom page that could show certain post from a category, I decided to create a query for a template page that checks the page slug and then list the posts containing a certain category + a tag ('comparativas').
The problem that I'm facing is that the list of post presented on the page doesn't show up the corresponding thumbnail on each post.
Thumbnails are generated dynamically basically with these lines:
$post_id = $post->ID;
$thumbnail_id = get_post_thumbnail_id( $post_id );
$thumbnail_image = wp_get_attachment_image_src( $thumbnail_id,$thumbnail_size );
The problem is that I couldn't find the way to send to the specific post ids to the function above, since the main $wp_query->posts; retrieves the page id instead of the post requested by the query_posts method.
The loops present the correct posts but when I echo the post->ID it shows the page id.
My query is:
global $wp_query;
// concatenate the query
$args = 'cat='.$idCategory.'&tag=comparativas';
query_posts( $args );
$posts = $wp_query->posts;
$current_id = get_the_ID(); //-> this returns the page id
If you could please tell me how to overwrite the global $wp_query; so the template can handle the corresponding ids for the list of post It would be great.
Any clue?
Best,
Juan
You could use, setup_postdata($post)
Then get_the_ID() works again :)
It doesn't work just because you aren't looping through them. You can do it many ways.
The 2 more common are the following:
overwrite the query with query_posts
$args = array('cat' => $idCategory,'tag' => 'comparativas');
query_posts($args);
if(have_posts()){
while(have_posts()){
the_post();
$current_id = get_the_ID(); // this return what you want now
the_title(); // this works as expected
}
}
wp_reset_query(); // get previous query back
get an array of WP_Post objects and setup_postdata or simply loop through them
$args = array('cat' => $idCategory,'tag' => 'comparativas');
$posts_i_want = get_posts($args);
foreach( $posts_i_want as $post ){
setup_postdata($post);
$current_id = get_the_ID(); // this return what you want now
the_title(); // this works as expected
}
wp_reset_postdata(); // get previous postdata back
I personally prefer the first in most cases
Cheers
I’m trying to set a sidebar in the single product page that show all products of the same categories as the product displayed.
That's how I proceed:
1) First I’ve created a sidebar called “Products_of_same_Category” to put in there a widget to show what I needed, then in function.php of my child theme I added the following snippet to execute php code in text widget:
// Enable PHP in widgets
add_filter('widget_text','execute_php',100);
function execute_php($html){
if(strpos($html,"<"."?php")!==false){
ob_start();
eval("?".">".$html);
$html=ob_get_contents();
ob_end_clean();
}
return $html;
}
2) Then when I saw that the snippet runs ok I added that code to test it:
<?php
$prod=get_the_term_list( $post->ID, 'product_cat');
echo $prod;
?>
And all worked fine, it gave me the exact name of the current category of the product displayed in the single product page.
3) So I've tried another test, deleting the previous code, to view if a shortcode translated in php should works in a widget too (writing at this time the exact category name requested, in this case "towels" - in the code below I substitute it with THE-CATEGORY-I-LIKE):
<?php echo do_shortcode('[product_category category=“THE-CATEGORY-I-LIKE” per_page="20" columns="1" orderby="title" order="desc"]'); ?>`
And all was again well done!
4) Finally I mixed all in this code to show the list of products of same categories but something goes wrong:
<?php $prod=get_the_term_list( $post->ID, 'product_cat', '', '', '' );
echo do_shortcode('[product_category category="'.$prod.'" per_page="20" columns="1" orderby="title" order="desc"]'); ?>
In last case the code doesn't display anything. I don't understand where I made mistakes, the syntax is wrong or the solving approach is illogical?
I really appreciate any help about this.
The problem is how you get the category slug. get_the_term_list will give you a formatted linked list of the categories, so it will display category names, not category slugs, which are different things. "Towels" would be your category name, but the category slug would be "towels". And product_category shortcode expect a slug, not a name.
The correct approach to get the category product slug is the following:
$terms = get_the_terms($post, 'product_cat');
if($terms && ! is_wp_error($terms)) {
foreach($terms as $term) {
echo do_shortcode('[product_category category="'.$term->slug.'" per_page="20" columns="1" orderby="title" order="desc"]');
}
}
This will display the products of all the categories associated to your product. See get_the_terms doc for reference.
In order to remove from the results the current product shown, you can make use of the woocommerce_shortcode_products_query filter. It isn't documented, but you can find it by looking at the product_category shortcode code located in includes/class-wc-shortcodes.php. In the product_category() method you will find the following line:
$return = self::product_loop( $query_args, $atts, 'product_cat' );
Where $query_args is a WP_Query parameters array. In the same class you will find the method product_loop() called here and see the following:
$products = new WP_Query( apply_filters( 'woocommerce_shortcode_products_query', $query_args, $atts ) );
So the query arguments are filtered - you will be able to work with that to add the desirated behavour. What you want to do is to use the post__not_in parameter to the query like this:
function remove_current_product_from_wc_shortcode($args, $atts) {
if(is_product()) { // check if we're on a single product page
$args['post__not_in'] = array(get_queried_object_id());
}
return $args;
}
add_filter('woocommerce_shortcode_products_query', 'remove_current_product_from_wc_shortcode');
This code should go in your theme functions.php - please not this is untested, so if it doesn't work look at the get_queried_object_id() return if it contain the current product ID.
Scenario:
I have 1000 posts that have the "Uncategorized" category, and I want to remove "Uncategorized" from all of those posts and set a different category for those posts.
In other words– take all Uncategorized posts and move them to another category, in one fell swoop.
Can I do this in bulk without going through each post individually?
What you are looking for is the WordPress bulk editor.
Go to Posts > Categories > Uncategorized
Click the "Screen Options" tab in the top right corner, then change "Number of items per page:" to 1000. (If you are on a really slow server you might consider doing less at a time)
Now select all of the items on the page and click the "Bulk Actions" drop-down above the select all and select the "Edit” option.
Hit Apply
In the bulk editor click the “new category” you want to change all of the posts to and hit update.
Once you have added all of the posts to the “new category” you need to remove the “Uncategorized” category. To do this:
Go to Settings > Writing
Now change the “Default Post Category” to something besides “Uncategorized”
Go back to Posts > Categories and delete the “Uncategorized” category
Now you can create the “Uncategorized” category again if you like and change it back to the default.
Once you delete the “Uncategorized” category it will remove it from all of your posts.
If you have some posts that you want to remain in “Uncategorized” then create a new category called “temp” and assign all of the posts you want to remain to that category. Once you delete “Uncategorized” create it again and assign the posts in “temp” back to that category.
As you've discovered, the bulk editor only allows the ADDITION of categories to multiple posts - it's not possible to REMOVE categories from multiple posts. The best option i found was to temporarily install this plug-in https://wordpress.org/plugins/bulk-remove-posts-from-category/ (in the WP repository) which adds the ability to REMOVE categories from multiple posts using the same bulk edit method. it simply adds an additional 'remove' checkbox under the category list.
The uncategorized category has an ID of 1. What our worksflow will be is,
Get all posts which is assigned to the uncategorized category.
We will only get post ID's which will make our query up to 1000 times faster on a site with thousands of posts. This will also help that our query does not time out or hit a maximum memory fatal error.
Use wp_set_object_terms() to remove and set our new tems
NOTE:
The code below requires PHP 5.4+ and any changes will be non reversable, so back up your database first
$args = [
'nopaging' => true, // Gets all posts
'cat' => 1, // Only gets posts assigned to category 1 which is the uncategorized category
'fields' => 'ids', // Only get post ID's, make query up 1000 times faster on huge databases
];
$q = get_posts( $args );
if ( $q ) {
foreach ( $q as $v ) {
// Get all the post categories
$categories = get_the_category( $v );
$category_ids = [];
foreach ( $categories as $category ) {
// Replace all uncategorized category instances with our new category id and build new array
if ( $category->term_id == 1 ) {
$category_ids[] = (int) 21; // REPLACE WITH THE CORRECT NEW CATEGORY ID
} else {
$category_ids[] = (int) $category->term_id;
}
}
// Set our new categories to the post
if ( $category_ids ) // Unnecessary check for categories, but just in case should something fail
wp_set_object_terms( $v, $category_ids, 'category' );
}
}
Note, nowhere have we changed the $post global or setup postdata, so we don't need to call wp_reset_postdata() :-)
Wordpress stores the parent/child relationships between categories and posts in the wp_term_relationships table, which is documented here. As #Pieter Goosen noted, the "Uncategoried" category has a ID of 1. So you can backup your SQL database, then connect to it with a SQL command line client (sudo mysql wordpress works for me), and run this SQL command:
delete from wp_term_relationships where term_taxonomy_id = 1;
If you want to move all uncategorized posts to another category, you can use the Bulk Move plugin.
If you want to remove a category from some posts, Bulk remove posts from category might be a better option.
As Melebius said, it is much, much quicker (and easier) to use https://wordpress.org/plugins/bulk-remove-posts-from-category/ ! It works with products as well as posts. Brilliant!
You can add this to your theme's functions.php file, then refresh any page on your site once, then remove the function.
Use at your own risk and backup the database first! There's no UNDO button on this.
<?php
$args = array(
'posts_per_page' => -1
);
$myposts = get_posts( $args );
foreach ( $myposts as $post ) :
setup_postdata( $post );
$categories = get_the_category();
$catcount = count($categories);
$postid = $post->ID;
$catlist = array();
//Building a list of categories for each post and EXCLUDING "uncategorized"
foreach( $categories as $category ) {
if($category->name == 'Uncategorized') {
continue;
}
$catlist[] = $category->term_id;
}
// If there's just one category, and that category is "Uncategorized", move the category to one of your choosing
if($catcount == 1 && $categories[0]->name == "Uncategorized") {
// This is the category ID that you want to move uncategorized posts to
$catlist = array(189);
}
wp_set_object_terms( $postid, $catlist, 'category' );
endforeach;
wp_reset_postdata();
?>
In wordpress, I have custom pages and inside the pages I'm trying to call the most recent posts for a specific category.
Doing so, I added this to create the variable...
$cat = get_post_meta($post->ID, "mom_cat", true);
And in the custom field of the page, I added mom_cat = (variable #)
In my post, I am trying to show the recent posts based o the variable category # I put in the custom field. I tried this, but it didn't work...
<?php
global $post;
$myposts = get_posts('numberposts=4&category=$cat' );
foreach($myposts as $post) :
?>
Hoever that is not working. How do I add a variable to "category = " in order to display a category based on my custom field setting?
Thanks
You shouldn't be using Custom Fields to define categories when Wordpress has all of the tools for you at your disposal. What you should do is find where your custom post is being registered, and add:
'taxonomies' => array('category')
...to your argument array. This will enable you to check off the categories that your custom posts require. If you can't find where the custom post type is being registered, add this instead to your functions.php file:
add_action('init', 'add_category_to_custom');
function add_category_to_custom()
{
register_taxonomy_for_object_type('category', 'custom_post_name');
}
THEN you can reference your custom post like so:
$posts = get_posts(array('numberposts' => 4, 'category' => $cat_ID, 'post_type' => 'custom_post_name'));
UPDATE: I wouldn't advise using Pages to display Category information, but I'm sure you have your reasons. I would still avoid placing category IDs within Custom Fields, simply because if one of your category IDs change, then it can cause LOTS of problems.
What I would advise in your case is to name those particular Pages exactly the same as their matching categories. Then do something like this:
<?php
/*
IF THE PAGE HAS A MATCHING CATEGORY,
DISPLAY 5 OF THE MOST RECENT POSTS IN THAT CATEGORY
*/
if($catID = get_cat_ID(get_the_title(get_the_ID())))
{
$posts = get_posts(array('numberposts' => 5, 'category' => $catID));
foreach($posts as $post) : setup_postdata($post);
?>
<!-- POST HTML GOES HERE -->
<?php
endforeach;
}
?>