Exclude specific category from Related Posts - php

Looking to exclude specific category (ID = 100) from "Related Posts" feed at bottom of Blog pages. Extra bonus if it can also exclude from the sidebar archive (not sure if they are connected??)
I'm using WP Theme "TheFox", have asked them - not part of their theme.
I "think" it has to do in the functions.php. I have found some similar questions, and code, but have not had any luck.
I'm a complete noob for .php, so be gentle :)
I've found some other attempts, no luck. Not registering or effecting the feed.
$categories_to_exclude [ 100 ];
$first_cat = false;
$categories = get_the_category( $post->ID );
while ( ! empty( $categories ) && false === $first_cat ) {
if ( in_array($categories[0]->cat_ID, $categories_to_exclude) ) {
array_shift($categories);
}
else {
$first_cat = $categories[0]->cat_ID;
}
}

What I could gather from your question is that You want to ignore one category (may be more) in the related post query?
use the following CODE (some explanation is given within the CODE in comments):
// set the category ID (or multiple category IDs)
// you want to ignore in the following array
$cats_to_ignore = array( 2 );
$categories = wp_get_post_categories( get_the_ID() );
$category_in = array_diff( $categories, $cats_to_ignore );
// ignore only if we have any category left after ignoring
if( count( $category_in ) == 0 ) {
$category_in = $categories;
}
$cat_args = array(
'category__in' => $category_in,
'posts_per_page' => 4,
'orderby' => 'date',
'post__not_in' => array( get_the_ID() )
);
$cat_query = new WP_Query( $cat_args );
while ( $cat_query->have_posts() ) : $cat_query->the_post();
/* just example markup for related posts */
echo '<h2>' . get_the_title() . '</h2>';
endwhile;
// reset $post after custom loop ends (if you need the main loop after this point)
wp_reset_postdata();

Use the below code, it must work
$categories_to_exclude [ 81, 11, 21 ];
$first_cat = false;
$categories = get_the_category( $post->ID );
while ( ! empty( $categories ) && false === $first_cat ) {
if ( in_array($categories[0]->cat_ID, $categories_to_exclude) ) {
array_shift($categories);
}
else {
$first_cat = $categories[0]->cat_ID;
}
}
You get the categories with get_the_category. Then in the while loop you skip the first category if it's 81, and look again. If it's not 81 (and you still have categories available), you asign it to $first_cat and carry on.

Related

Displaying parent page on child page list

I have a script that is displaying child page list on parent page and a list o child pages without the current child page.
I would like to add the parent page on child pages, but I don't know how to achieve it. Could you please help me out?
This is my code:
if ('page-parent') {
echo '<h3>See also</h3>';
// if we are on a parent page set the $parent variable to current post id
// otherwise set $parent variable to current post parent
$parent = $post->post_parent == 0 ? $post->ID : $post->post_parent;
// if we use current post parent as $parent, exclude the current page
$exclude = $parent == $post->post_parent ? $post->ID : false;
// get all the children
$args = array( 'parent' => $parent, 'sort_column' => 'menu_order' );
if ( $exclude ) $args['exclude'] = $exclude;
$child_pages = get_pages($args);
// show only if there are children
if ( ! empty($child_pages) ) {
global $post;
foreach ( $child_pages as $post ) { setup_postdata( $post );
?>
<div class="child-thumb">
<?php the_title(); ?>
</div>
<?php
}
wp_reset_postdata();
}
}
You need to use 'child_of' argument instead of 'parent'. 'parent' in get_pages means to fetch or not to fetch parental pages.
But your case needs to fetch children of given page.
So you must use
$args = array( 'child_of' => $parent,
'sort_column' => 'menu_order' );
To display one single parent page above children, you can use get_post function:
if ($post->post_parent>0){
$parent_page=get_post($post->post_parent);
echo '<div>'.$parent_page->post_title.'</div>';
}
if ( ! empty($child_pages) ) {
///and so on...
For more information: https://codex.wordpress.org/Function_Reference/get_pages

How to Assign Category to a Post Automatically using Postmeta

I've read other answers about assigning category based on post tags. But can this be done based on postmeta?
I'm assuming it can be and I've been trying to change the following snippet (quoted in another answer) to achieve this. But I've had no luck tweaking it to reference postmeta meta_key (delivery_option) and meta_value (pick-up, postal, post & parcel), to then auto assign a category (pick-up, postal or post & parcel).
In case it's relevant, the above postmeta key and value have been added by another plugin.
function auto_add_category ($product_id = 0) {
if (!$product_id) return;
// because we use save_post action, let's check post type here
$post_type = get_post_type($post_id);
if ( "product" != $post_type ) return;
$tag_categories = array (
'ring' => 'Jewellery'
'necklace' => 'Jewellery',
'dress' => 'Clothing',
);
// get_terms returns ALL terms, so we have to add object_ids param to get terms to a specific product
$product_tags = get_terms( array( 'taxonomy' => 'product_tag', 'object_ids' => $product_id ) );
foreach ($product_tags as $term) {
if ($tag_categories[$term->slug] ) {
$cat = get_term_by( 'name', $tag_categories[$term->slug], 'product_cat' );
$cat_id = $cat->term_id;
if ($cat_id) {
$result = wp_set_post_terms( $product_id, $cat_id, 'product_cat', true );
}
}
}
}
add_action('save_post','auto_add_category');
Disclosure: I'm building a WordPress website and learning as I go. This may be an obvious question, but be assured that its being asked after hours of research to try and answer myself (it's all good I've learnt other stuff while researching... just not the right stuff!). HUGE thanks in advance for any mastery insights.
This code when placed in your functions.php file will check the product's delivery option and then assign the corresponding category to the product. If any product categories for that product already exist it will append them to the list. The product category would need to exist in the first place and if it does then it assigns that category with the same slug as the delivery option. I use the hook save_post_product so that it fires only on updating products.
add_action('save_post_product', 'update_product_category', 20, 3);
function update_product_category( $post_id, $post, $update ) {
$product = wc_get_product( $post_id );
$delivery_methods = array( 'pick-up', 'postal', 'post', 'parcel' );
$delivery_option = get_post_meta($post_id, 'delivery_option', true);
if( ! empty( $delivery_option ) ) {
$product_cats = $product->get_category_ids();
foreach( $delivery_methods as $delivery_method) {
if( $delivery_option === $delivery_method ) {
$pickup_cat_id = get_term_by('slug', $delivery_method, 'product_cat')->term_id;
if( $pickup_cat_id && ! in_array( $pickup_cat_id, $product_cats) ) {
$product_cats[] = $pickup_cat_id;
$product->set_category_ids($product_cats);
$product->save();
}
}
}
}
}

Custom Fields not showing in custom post type post

I have a custom post type named "Designer" Each posts will be using different unique Advanced Custom Fields as each posts has unique templates.With the below code I am able to give rules for each posts in Designer post type and save but the custom fields are not displaying on post edit pages on backend.
Normally this code should ork but no idea what happend to the code
Please Help.
add_filter('acf/location/rule_types', 'acf_location_rules_types');
function acf_location_rules_types( $choices )
{
$choices['Custom Post types']['cpt_parent'] = 'Custom post type parent';
return $choices;
}
add_filter('acf/location/rule_values/cpt_parent', 'acf_location_rules_values_cpt_parent');
function acf_location_rules_values_cpt_parent( $choices )
{
$args = array(
'hierarchical' => true,
'_builtin' => false
);
$posttypes = get_post_types( $args );
if( $posttypes )
{
foreach( $posttypes as $posttype ):
if( $posttype != 'acf' ):
$args = array(
'post_type' => 'designer',
'posts_per_page' => -1,
'post_status' => 'publish'
);
$customposts = get_posts( $args );
if ( $customposts ) {
foreach( $customposts as $custompost ){
$choices[ $custompost->ID] = $custompost->post_title;
}
}
endif;
endforeach;
}
return $choices;
}
//MATCH THE RULE
add_filter('acf/location/rule_match/cpt_parent', 'acf_location_rules_match_cpt_parent', 10, 3);
function acf_location_rules_match_cpt_parent( $match, $rule, $options )
{
global $post;
$selected_post = (int) $rule['value'];
// post parent
$post_parent = $post->post_parent;
if( $options['page_parent'] ) {
$post_parent = $options['page_parent'];
}
if ($rule['operator'] == "=="){
$match = ( $post_parent == $selected_post );
}
elseif ($rule['operator'] != "!="){
$match = ( $post_parent != $selected_post );
}
return $match;
}
Your Artist Collection field group is set to only appear on one post, the post Designer Post 1 which is a Designer Post type.
I don't understand what all the code is for? Just create a different field group for each post that needs a different field group and a separate rule for each.
Ok sorry I understand the issue now and I have recreated the issue on my local install.
On the line of code below you are looking for the post_parent but I think you should be looking for the ID.
I changed this:
$post_parent = $post->post_parent;
to this:
$post_parent = $post->ID;
and it's working for me.
If I understand your problem correctly, in wp-admin post edit page click on screen options on the upper right corner. In the menu that appears make sure the Custom fields is selected. This will make the custom fields appear for edit.

Can't get WordPress to display all categories in Multisite

I'm using WordPress Multisite and I'm trying to display all the categories in every site on one page. When I'm on my admin account, the following code works. However, when I switch to any other account, no categories are shown.
$t=get_current_blog_id();
foreach(function_that_gets_blogs() as $k=>$blog){
switch_to_blog($blog['blog_id']);
print_r(get_categories(array('hide_empty'=>true))); // prints "array()"
foreach(get_categories(array('hide_empty'=>true)) as $cat){
...
}
}
switch_to_blog($t);
Why aren't the categories showing?
Like b__ said you should check for:
Where are you using this code? (functions.php, plugin)
You should disable plugins 1 by 1, to check if some are interfering
and in the last case change theme
I've done something like you, and here is the code, in case you wanna try it:
// Current Site
$current = get_current_site();
// All Sites
$blogs = get_blog_list( 0, 'all' );
foreach ( $blogs as $blog ) {
// switch to the blog
switch_to_blog( $blog['blog_id'] );
// get_categories args
$args = array(
'hide_empty' => true
);
$categories = get_categories( $args );
foreach ( $categories as $category ) {
$link = get_category_link( $category->term_id );
$name = $category->name;
printf( '%s ', $link, $name, $name );
}
}
// return to the current site
switch_to_blog( $current->id );
Update 2014/06/01
the function get_blog_list(); is deprecated since version 3.0, with that you should change that function within wp_get_sites();
// Current Site
$current = get_current_site();
// All Sites
$blogs = wp_get_sites();
foreach ( $blogs as $blog ) {
// switch to the blog
switch_to_blog( $blog['blog_id'] );
// get_categories args
$args = array(
'hide_empty' => true
);
$categories = get_categories( $args );
foreach ( $categories as $category ) {
$link = get_category_link( $category->term_id );
$name = $category->name;
printf( '%s ', $link, $name, $name );
}
}
// return to the current site
switch_to_blog( $current->id );
Simple as that...
Did you try:
<?php wp_list_categories("title_li=");?>

List only child categories a post is in, of a specific parent category

Either this is harder than it needs to be or I am just not understanding WordPress/PHP very well :( All I want to do is show the child/sub categories of a specific parent category...but only if the post is in those subcategories. Specific example:
I am building a wine reviews website and these are the categories:
BrandSubcategory 1Subcategory 2etc.
RegionSubcategory 1Subcategory 2etc.
GrapeSubcategory 1Subcategory 2etc.
The parent categories will never change, and every post will have at least 1 subcategory selected under each parent, so in the LOOP I can just list the parents by name. But I am needing to dynamically output the subcategories, something like this:
Brand: <?php list_post_subcategories('brand'); ?>
Region: <?php list_post_subcategories('region'); ?>
Grape: <?php list_post_subcategories('grape'); ?>
Is there any easy way like this? It seems like this should be a basic function in Wordpress? I've looked at the functions 'get_categories' and 'in_category' but they don't seem to be able to do this.
<?php $post_child_cat = array();
foreach((get_the_category()) as $cats) {
$args = array( 'child_of' => $cats->cat_ID );
$categories = get_categories( $args );
if( $categories ) foreach( $categories as $category ) {
echo $category->cat_name; }
} ?>
try this
I posted to Wordpress Answers to get more help and #Milo gave a great code solution:
// get top level terms
$parents = get_terms( 'category', array( 'parent' => 0 ) );
// get post categories
$categories = get_the_terms( $post->ID, 'category' );
// output top level cats and their children
foreach( $parents as $parent ):
// output parent name and link
echo '' . $parent->name . ': ';
// initialize array to hold child links
$links = array();
foreach( $categories as $category ):
if( $parent->term_id == $category->parent ):
// put link in array
$links[] = '' . $category->name . '';
endif;
endforeach;
// join and output links with separator
echo join( ', ', $links );
endforeach;
You can use array_map so you can return only the categories that you want. For example:
array_map( function( $cat ) {
if ( $cat->parent != 0 ) {
return $cat;
}
},
get_the_category()
);

Categories