在Wordpress中的任何页面上显示特定父项的子页面

时间:2018-03-08 21:57:41

标签: wordpress wordpress-theming

我的网站建立了很多父母和孩子。

我目前正在使用以下功能:click

然而它并没有实现我想要的。我只能在父母下使用它。

我希望能够使用短代码在任何页面(主要是主页)上列出特定父级的子页面

梦想是我可以拥有这样的短代码:

[wpb_childpages_xxx]其中xxx等于父页面

这可能吗?

1 个答案:

答案 0 :(得分:1)

以下是修改后的代码:

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' );

使用短代码 - 使用idslug,但如果您指定slugid将被忽略:

  • 显示当前页面的子页面
    [wpb_childpages /]

  • 显示任意页面的子页面

    1. 使用帖子ID:[wpb_childpages id="{POST_ID} /]
      例如。 [wpb_childpages id="123" /]

    2. 使用post slug:[wpb_childpages slug="{SLUG} /]
      例如。 [wpb_childpages slug="home" /]