1

I have created a plugin to diplay a list of posts (cpt) in a tree on the sidebar. It adds an icon [+] when posts have children. However when I click on a post the tree colapses. How can I keep the tree open with the post highlihged?

    function custom_post_tree_shortcode($atts) {

       $args = shortcode_atts(array(
        'post_type' => 'animal',
    ), $atts);

    $entries = get_posts(array(
        'post_type' => $args['post_type'],
        'posts_per_page' => -1,
    ));

    $output = '<ul class="custom-post-tree">';

    $parents = array();
    $children = array();

    foreach ($entries as $entry) {
        if ($entry->post_parent === 0) {
            $parents[$entry->ID] = $entry;
        } else {
            if (!isset($children[$entry->post_parent])) {
                $children[$entry->post_parent] = array();
            }
            $children[$entry->post_parent][] = $entry;
        }
    }
    foreach ($parents as $parent) {
        $output .= '<li class="parent">';
        if (isset($children[$parent->ID])) {
            $output .= '<a href="#" class="toggle"><i class="fas fa-folder"></i> [+] </a>';
        }
        $output .= '<a href="' . get_permalink($parent->ID) . '">' . $parent->post_title . '</a>';
        if (isset($children[$parent->ID])) {
            $output .= '<ul class="children" style="display: none;">';
            foreach ($children[$parent->ID] as $child) {
                $output .= '<li><i class="fas fa-file"></i> <a href="' . get_permalink($child->ID) . '">' . $child->post_title . '</a></li>';
            }
            $output .= '</ul>';
        }
        $output .= '</li>';
    }
    $output .= '</ul>';
    return $output;
}
add_shortcode('custom_post_tree', 'custom_post_tree_shortcode');

This is the JS

jQuery(document).ready(function($) {
    $(".parent > a.toggle").click(function(e) {
        e.preventDefault();
        var $toggle = $(this);
        var $ul = $toggle.nextAll("ul.children:first");

        if ($ul.is(":visible")) {
            $toggle.html('<i class="fas fa-folder"></i> [+] ');
            $ul.slideUp();
        } else {
            $toggle.html('<i class="fas fa-folder-open"></i> [-] ');
            $ul.slideDown();
        }
    });
});
// Add an icon to posts without children
jQuery(".parent:not(:has(ul.children))").prepend(' <i class="fas fa-file"></i> ');

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.