Show Child-pages of Specific Parent on any page in Wordpress

落爺英雄遲暮 提交于 2019-12-11 07:37:41

问题


My website is build with alot of parents and childs.

I am currently using the follow function: https://gist.github.com/mprahweb/3c94d9c65b32ec9e3b2908305efd77d5

However it doesnt achieve what i want. I can only use it under the parent.

I want to be able to use a shortcode to list a child-pages for a specfic parent on any page (mainly the homepage)

The dream would be that i could have a shortcode like this:

[wpb_childpages_xxx] where xxx equals the parent page

is this possible?


回答1:


Here is the modified code:

function wpb_list_child_pages( $atts = array() ) {
    $atts = shortcode_atts( array(
        'id'   => 0,
        'slug' => '',
    ), $atts );

    if ( $atts['slug'] ) {
        global $wpdb;

        $q = $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_name = %s", $atts['slug'] );
        $post_id = $wpdb->get_var( $q );

        if ( ! $post_id ) {
            return '';
        }
    } else {
        $post_id = absint( $atts['id'] );
    }

    $post = get_post( $post_id ); // WP_Post on success.
    $childpages = '';

    if ( $post && is_post_type_hierarchical( $post->post_type ) ) {
        $childpages = wp_list_pages( array(
            'child_of' => $post->ID,
            'title_li' => '',
            'echo'     => 0,
        ) );
    }

    if ( $childpages ) {
        $childpages = '<ul>' . $childpages . '</ul>';
    }

    return $childpages;
}
add_shortcode( 'wpb_childpages', 'wpb_list_child_pages' );

Using the Shortcode — use either id or slug, but if you specify a slug, the id will be ignored:

  • To show child pages of the current page:
    [wpb_childpages /]

  • To show child pages of any pages:

    1. With the post ID: [wpb_childpages id="{POST_ID} /]
      E.g. [wpb_childpages id="123" /]

    2. With the post slug: [wpb_childpages slug="{SLUG} /]
      E.g. [wpb_childpages slug="home" /]



来源:https://stackoverflow.com/questions/49183161/show-child-pages-of-specific-parent-on-any-page-in-wordpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!