WordPress get category ID from URL - wordpress

I have hard time trying to find the solution, does somebody know how to get this:
I have one WordPress post in more than one category, but only one is permalink category. I need to get the ID only of that permalink category (I need this info so I can take few latest posts from permalink category via custom query).
url looks like this http://domain.com/category-name/post-title
I need that "category-name" ID.

A Good one to use is:
<?php $page_object = get_queried_object(); ?>
<h1><?php echo $page_object->cat_name; ?></h1>

global $wp;
$current_url = home_url( add_query_arg( array(), $wp->request ) ); get url
$url_array = explode('/',$current_url);
$retVal = !empty($url_array[5]) ? $url_array[5] : $url_array[4] ;
$idObj = get_category_by_slug($retVal);
echo $idObj->name

My answer is:
function get_category_by_url($url) {
foreach( (get_the_category()) as $category) {
if ( get_category_link($category->cat_ID) == $url )
return $category->slug;
}
return false;
}

$category = end(get_the_category());
$current = $category->cat_ID;
echo 'id='.$current . ' - name=' . $category->cat_name;

If the post belongs to many categories, what if you're viewing the post from a second category. In that case retrieving the category ID of the permalink category may not help, since you would need the related posts of the current category in action.
For that, you can get the ID by passing the category name as follows:
<?php get_cat_ID($cat_name)?>
Does this help?

Wordpress chooses the oldest category as the permalink category. There's no way to change that behavior unless you use some plugin. If you choose to use a plugin you make take the category ID from plugin settings.
You can list all categories of this post and choose most relevant category.
Use the following code inside The Loop:
foreach((get_the_category()) as $category)
{
if ( $category->cat_ID == 1000 )
; // DO SOMETHING
}

Related

Show actual thumbnail of the category page with the ID with wordpress

i need some help on wordpress
I have to show the thumbnail of my category product of my current category page
So for that i use :
[product_categories ids='116']
It's display the cat id 116.
But i'm blocked for the next thing. Get the id of the current page instead of writing it manually.
Thanks for the help
You can get the category ID using the below code
$category = get_queried_object();
$cat_id = $category->term_id;
echo $cat_id;
You can use this ID and do the rest of things.
So with the help of full stop i write this to solve my problem
function wpc_elementor_shortcode2( $atts ) {
$category = get_queried_object();
$cat_id = $category->term_id;
echo do_shortcode('[product_categories ids="$cat_id"][/product_categories]');
}
add_shortcode( 'my_elementor_php_output2', 'wpc_elementor_shortcode2');

Get a sidebar widget that show products of the same categories in Woocommerce

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.

Can't retrieve custom taxonomy within multisite

I'm currently working on a Wordpress multisite. While I can retrieve custom post types from within child blogs by using switch_to_blog(1) I cannot retrieve any custom taxonomies this way.
For instance, this page on the main blog lists posts from the "employment" post type and shows the custom "location" category associated with it.
http://209.59.177.85/employment-opportunities/
This one is within a child blog, and the template code is after a call to switch_to_blog(1):
http://209.59.177.85/waterloo/careers/
Same code, but the custom post type shows, and the custom taxonomy does not. The page does not generate any errors. I can't even get a basic term list printed on the page for the taxonomy.
Has anyone done this before?
Thanks!
Here's the solution, in case anyone is looking. The terms can, of course, be accessed directly from the db:
<span class="date">Location: <?php
$jobid = get_the_ID();
$queryterms = "
SELECT *
FROM ".$table_prefix."terms terms, ".$table_prefix."term_taxonomy term_taxonomy, ".$table_prefix."term_relationships term_relationships
WHERE (terms.term_id = term_taxonomy.term_id AND term_taxonomy.term_taxonomy_id = term_relationships.term_taxonomy_id)
AND term_relationships.object_id = ".get_the_ID()."
";
$terms = $wpdb->get_results($queryterms, OBJECT);
if ( $terms != null ) {
foreach( $terms as $term ) {
echo "<a href='/location/";
print $term -> slug ;
echo "/'>";
print $term -> name ;
echo "</a>";
unset($term);
} } ?> | Posted on: <?php the_time('F j, Y'); ?></span>

link to custom taxonomy by id

Through a series of specific requirements, I find myself needing to link to a custom taxonomy category using its term id...
I've got this - which displays a link to all taxonomies - I wish to change it so it only displays a link to the taxonomy with the term id dynamically pulled from a custom field I'm using.
$taxonomy = 'event-categories';
$terms = get_terms($taxonomy);
if ($terms) {
foreach($terms as $term) {
echo '<li>' . $term->name .'</li>';
}
};
essentiall I need "link_to_taxonomy_category(x)" where x = term_id
Thanks
The function you are looking for is get_term_link. It takes either a term object, ID or slug and a taxonomy name and returns a URL to the term landing page.
As a side note hard coding the link as you have in the example above is fragile -- always keep your code as portable as possible. If the site is moved to a different domain, that link will break. WordPress has several functions that generate links dynamically based on the current installation environment. get_term_link is one example.
From the Codex:
$terms = get_terms('species');
echo '<ul>';
foreach ($terms as $term) {
echo '<li>'.$term->name.'</li>';
}
echo '</ul>';
If you have single term_id e.g: 10, custom taxonomy series then you can use the following code to get the taxonomy term link.
note : change 10 to your variable for term_id and 'series' to your taxonomy.
$term = get_term( 10, 'series' );
$term_link = get_term_link( $term );
echo 'View All';

WordPress how to pull category specific sidebars into theme

I'm trying to have our WP theme call in a specific sidebar when the user lands on a dedicated article/permalink page. The post category will determine which sidebar is pulled in.
Example: If the user arrives on a permalink/dedicated article page for a post categorized as "red", then the theme would look for the post category, acknowledged that the category is red, and then find and pull in the sidebar that I have defined as "red".
Just getting started with this project and would appreciate any thoughts on what I describe below.
This is what I think the code should look like to achieve that:
<?php
if (is_category()){
$current_cat = intval( get_query_var('cat') );
get_sidebar($current_cat); //for category red get sidebar-red.php
}
?>
One more piece to the puzzle:
I want to add in an addition argument so that if the post is uncategorized (i.e. we did not categorize the post for whatever reason) that it will pull in a default sidebar. I think that code should like something like this, but I don't know how to define "non-existent category". Basically I want to tell wordpress to look for the post category. If it finds that one does not exist, then I want it to pull in sidebar-default.php
<?php
if (is_category()){
$current_cat = intval( get_query_var('cat') );
get_sidebar($current_cat); }
elseif (is_category(**argument for nonexistent category**))
$current_cat = intval( get_query_var('cat') );
get_sidebar-default.php; }
?>
You should be using in_category not is.
For example:
<?php
if ( in_category('fruit') ) {
get_sidebar('1');
} elseif ( in_category('vegetables') ) {
get_sidebar('2');
} else {
// do nothing or something
// ...
}
?>
http://codex.wordpress.org/Function_Reference/in_category
<?php in_category( $category, $_post ) ?>
$category
(mixed) (required) One or more categories specified by ID
(integer), name or slug (string), or an array of these
Default: None
You can have the different sidebar classes defined in your CSS.
Give the category that you want to match up with the style the same name as that category's slug. In your template, define the sidebar div's class using the post's category-slug.
Here's a bit on how to get the slug:
<?php
if (is_category( )) {
$cat = get_query_var('cat');
$yourcat = get_category ($cat);
echo 'the slug is '. $yourcat->slug;
}
?>
So your sidebar div would be something like:
<div class="<?php echo yourcat->slug; ?> sidebar"></div>
So you've given your sidebar two classes, one called sidebar and one to be determined by whatever the category is!
Hopefully this made sense.
You can even use Category Templates, so you create category-red.php and category-blue.php files

Resources