WordPress.org

Forums

[resolved] [Widget Logic] Conditional check parent category help! (19 posts)

  1. musicmasteria
    Member
    Posted 6 years ago #

    Hi I'm trying to have a widget only show up on single posts under the a category with the parent category of 'manga'(5).

    I got to this point then I couldn't figure out how to get the last part.

    is_single() && in_parent_category('5')

    Yes i know 'in_parent_category' doesn't exist but I wish it did.
    I am not very good at coding php so I am unable to write the code needed.

    Can anyone help me?

  2. musicmasteria
    Member
    Posted 6 years ago #

    Update:

    $parentCatList = get_category_parents($cat,false,',');
    $parentCatListArray = split(",",$parentCatList);
    $topParentName = $parentCatListArray[0];
    $sdacReplace = array(" " => "-", "(" => "", ")" => "");
    $topParent = strtolower(strtr($topParentName,$sdacReplace));
    return (is_single() && ($topParent=="manga"));

    Tried the above code in widget-logic,
    I get this error:
    Catchable fatal error: Object of class WP_Error could not be converted to string in /home/animepla/public_html/testing/wp-content/plugins/widget-logic/widget_logic.php(131) : eval()'d code on line 1

    Another failed attempt... :(

  3. musicmasteria
    Member
    Posted 6 years ago #

    Finally a breakthrough!

    Through a little testing I found that that this code works:
    $category = get_the_category(); $parent = get_cat_name($category[0]->category_parent); return (is_single() && ('Manga'==$parent));

    'Manga' just applies to my setting but you could use this code:
    <?php $category = get_the_category(); $parent = get_cat_name($category[0]->category_parent); echo '&raquo; ' . $parent; ?>
    placed in the post you are trying to find the parent code of.

    This will output something like >>(Parent Category)
    replace your (Parent Category) with my "Manga" and there you go.

    I hear this code has limitations and works best of 1 level deep categories (perfect for me but idk about others).

    As far as i know, this code is working but I'll be putting it through a few tests on my site before I mark this as resolved.

  4. musicmasteria
    Member
    Posted 6 years ago #

    Notes: I got the first part of the code from the first half of the code on this page: http://corpocrat.com/2008/10/31/how-to-get-parent-category-name-in-wordpress/

    1. <?php
    2. $category = get_the_category();
    3. $parent = get_cat_name($category[0]->category_parent);
    4. if (!empty($parent)) {
    5. echo '» ' . $parent;
    6. } else {
    7. echo '» ' . $category[0]->cat_name;
    8. }
    9. ?>

    There was an extra empty in the code that has been removed.

    My current code above does have a glitch in it though which is addressed in the code above using an if statement. My idea is that rather than echo'ing the values, save them in a third variable like $topcat and then replace the final $parent in my code above with $topcat.

    I tried this on my own and got this code:

    $category = get_the_category();
    $parent = get_cat_name($category[0]->category_parent);
    if (!empty($parent)) {
    $topcat = $parent;
    } else {
    $topcat = $category[0]->cat_name;
    }
    return (is_single() && ('Manga'==$topcat);

    But that code gives an error and I can't find the problem in it...

    Any ideas?

  5. alanft
    Member
    Posted 6 years ago #

    the codex has this

    http://codex.wordpress.org/Template_Tags/in_category#Testing_if_a_post_is_in_a_descendant_category

    which looks like exactly what you are looking for

  6. musicmasteria
    Member
    Posted 6 years ago #

    I have seen that code before but when I tried it, I don't think it worked.

    If I remember correctly it needed the code below somewhere to make post_is_in_descendant_category(5) work. As I have had very little luck with if's and function's in widget-logic code this code didn't work for me.

    function post_is_in_descendant_category( $cats, $_post = null )
    {
    	foreach ( (array) $cats as $cat ) {
    		// get_term_children() accepts integer ID only
    		$descendants = get_term_children( (int) $cat, 'category');
    		if ( $descendants && in_category( $descendants, $_post ) )
    			return true;
    	}
    	return false;
    }

    Maybe I wasn't doing it right so if this alternative is better than my current code, I welcome a working code that I could put straight into the widget-logic box.

    Update on my code: (1 Edit + 1 Fix)

    $category = get_the_category(); $parent = get_cat_id($category[0]->category_parent); return (is_single() && ('5'==$parent || in_category('5')));

    The 1 Edit is "get_cat_id" to replace "Manga" with its category id "5"

    The 1 Fix added the " || in_category('5') " condition because without it, anything posted IN the top (parent) category returns false when some people might want it to be true. This is because the top (parent) category doesn't have a parent category of itself so the $parent="" instead of "5".

    In my case the top (parent) category is always empty and all my posts are in sub categories so I don't really need the "Fix" but for the sake of others, there is it.

  7. musicmasteria
    Member
    Posted 6 years ago #

    SORRY!
    I should have tested the code first, duh..

    The code should look like this:

    $category = get_the_category(); $parent = $category[0]->category_parent; return (is_single() && (('5'==$parent) || in_category('5')));

    The "1 Fix" above works but the "1 Edit" doesn't work because "get_cat_id" doesn't exists and actually, I already had the id and didn't notice it. "$category[0]->category_parent" already returns the ID so I set it to equal $parent instead of "get_cat_name(____)".

    I should have known better :/ Sorry.

  8. alanft
    Member
    Posted 6 years ago #

    assuming that codex code works (and it sure looks right), then the way to use it is to get the function declared somewhere else - i put useful functions like that in my theme's functions.php

    then you can use that function in your widget logic code with just something like

    is_single() && post_is_in_descendant_category(5)

    try it.

  9. musicmasteria
    Member
    Posted 6 years ago #

    Thanks alanft,

    The code that I ended up using was

    is_single() && (post_is_in_descendant_category(5) || in_category(5))

    With this in my theme's function.php code:

    function post_is_in_descendant_category( $cats, $_post = null )
    {
    	foreach ( (array) $cats as $cat ) {
    		// get_term_children() accepts integer ID only
    		$descendants = get_term_children( (int) $cat, 'category');
    		if ( $descendants && in_category( $descendants, $_post ) )
    			return true;
    	}
    	return false;
    }

    I am curious though, does it use more or less resources reading the function from the function.php file than reading it straight from the code like I had before?

    - - - - -
    - - - - -

    There is one thing I have been leaving out to simplify things though. It is that I'm actually using 2 widgets, 1 widget that appears only in the specific area and other widget that appears in all other places but not the specific area.

    The code I've been using for the second widget is:

    !(is_single() && (post_is_in_descendant_category('5') || in_category('5')))

    (I just did !(----), where ---- is the the entire first widget's code.)

    Is this the right way of doing this or is there an easier way for doing that?

    Thanks again alanft,
    ~Musicmasteria

  10. alanft
    Member
    Posted 6 years ago #

    hurrah. glad it's working.

    and spot on about using !, the !(logic) construction is the right way to reverse the true/false. ! is called logical "NOT" - it turns true to false, and vice versa.

    putting a function in functions.php makes it available to use whenever and wherever you like, so you don't have to redefine it each time. so it makes your widget logic easier to read, and shorter if you need to use the function many times for multiple widgets.

  11. RickA99
    Member
    Posted 6 years ago #

    It's working for me too! Thanks to both of you. I an using it for placing sidebar category menus on certain pages.

    BTW, I found a plugin that makes using sidebar category menus a whole lot easier called Extended Categories. It allows selecting of a category or categories for display instead of getting all of them as with the standard WordPress category widget and you can choose to display empty category items if you want.

    Widget Logic and Extended Categories together are a dynamite combination!

  12. TradingMetro
    Member
    Posted 6 years ago #

    This works well if you're on single posts.
    But what about descendent category pages?

    Maybe modifiying the "post_is_in_descendant_category" function from the codex would be the simplest.

    Any help would be appreciated.

  13. alanft
    Member
    Posted 6 years ago #

    i'll get you started by pointing you at a function used in the codex function

    get_term_children( (int) $topcat, 'category');

    which gives you an array of categories descended from $topcat, which means all you have to do is use PHP's in_array function to tell if your $cat is in that array

    in_array($cat, get_term_children( (int) $topcat, 'category'))

  14. Herbelizer
    Member
    Posted 6 years ago #

    OK, I am sure, the answer to my problem is inside this thread, but I'm really to confused to get it.
    It would be nice if someone can clear the dust and help me to fix the following problem:

    I have widget A that should be visible on the archive sites of category X and all subcategories of category X. It should also be visble on all single posts within category X and the subcategories of category X.

    On all other pages, that means other cats than x (+subs) and the template-based start page widget B should be visible.

    It would be very nice, if you php pros could provide me the code pattern for widget A and B.

    Thank a lot!

  15. alanft
    Member
    Posted 6 years ago #

    re widget A

    "visible on the archive sites of category X and all subcategories of category X"

    is_category() &amp;&amp; in_array($cat, get_term_children( (int) $topcat, 'category'))

    "on all single posts within category X and the subcategories of category X"

    is_single() &amp;&amp; (post_is_in_descendant_category(X) || in_category(X))

    use OR to make this true in one case or the other = A || B

  16. arkitekt
    Member
    Posted 6 years ago #

    I have gone through this thread and some others but still not able to get this working for my issue --- I'm looking to have a widget show up in a main category archive listing, and then all posts within that category.

    I have tried is_category('9') || in_category('9') and is_category('9') || is_single() && in_category('9')

    Not sure what to try next, I have tried a lot of the things here.

    I would appreciate any potential tips in the right direction.

    Thanks!

  17. alanft
    Member
    Posted 6 years ago #

    i recently updated the WL code, with more in the FAQ and "Other Notes" section which should help you

    http://wordpress.org/extend/plugins/widget-logic/faq/

  18. acafourek
    Member
    Posted 6 years ago #

    I am having an issue that I think falls into this thread, though it is using condition descendants outside of widgets.

    I have a parent category called 'Sciences' with ID=33; and a number of sub-categories within it. Here is the end goal: For every post within a child category of 'Sciences', I want to display the child category's description below the post.

    So if I have a post in category 'Biology' (ID=11) which is a child of the category 'Sciences', I want the Biology cat description to display. And if another post is in category 'Geology' (ID=12), also a child of 'Sciences', I want the Geology cat description to display.

    I am just having a bit of trouble understanding how to use post_is_in_descendant_category.

    Right now I have this code in my single.php file:

    <div id=postinfo>
    
     <?php if ( in_category( 'Sciences' ) || post_is_in_descendant_category( 33 ) ) {
    
    }
    ?>   
    
    </div>

    and I also have this code in my functions.php file:

    <?php if ( function_exists('register_sidebar') )
        register_sidebar(array(
            'before_widget' => '<ul class="category-bg widget %2$s">',
            'after_widget' => '</ul>',
            'before_title' => '<h2>',
            'after_title' => '</h2>',
        ));
    ?>
    
    <?php
    /**
     * Tests if any of a post's assigned categories are descendants of target categories
     *
     * @param mixed $cats The target categories. Integer ID or array of integer IDs
     * @param mixed $_post The post
     * @return bool True if at least 1 of the post's categories is a descendant of any of the target categories
     * @see get_term_by() You can get a category by name or slug, then pass ID to this function
     * @uses get_term_children() Gets descendants of target category
     * @uses in_category() Tests against descendant categories
     * @version 2.7
     */
    function post_is_in_descendant_category( $cats, $_post = null )
    {
    	foreach ( (array) $cats as $cat ) {
    		// get_term_children() accepts integer ID only
    		$descendants = get_term_children( (int) $cat, 'category');
    		if ( $descendants && in_category( $descendants, $_post ) )
    			return true;
    	}
    	return false;
    }
    ?>

    As you can see, most of this is just copied from the Codex (I haven't gotten to the description part yet) and Im a bit hung up here.

    Any advice in how to yield the kind of output I'm looking for? Any help is greatly appreciated!

    -Thanks

    -ac

  19. Sam_a
    Member
    Posted 5 years ago #

    It looks like you're using post_is_in_descendant_category correctly. post_is_in_descendant_category( 33 ) means “are any of the current post's assigned categories descendants of category ID 33.”

Topic Closed

This topic has been closed to new replies.

About this Topic