首页 > 解决方案 > 在孩子中列出来自父母的所有孩子自定义帖子

问题描述

我需要一种方法来引用当前子帖子的父母,以将该短代码添加到孩子的帖子模板中,以便在孩子的帖子中显示所有父母的孩子。

我认为举个例子更容易理解:)

如果我在:“/Season-1/Episode-1”。我想在“第 1 季”中列出“第 1 季”的所有剧集,

但是如果我在“/Season-2/Episode-19”中,我想在“Episode-19”中列出“Season-2”中的所有剧集。

目前,我正在使用此代码在任何页面上显示特定父级的子帖子列表,问题是我不知道如何自动化短代码(或者如果需要更改 php 代码以在没有 slug 的情况下自动工作)。

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' => '',
        'post_type' => 'season',
        'echo'     => 0,
    ) );
}

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

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

然后我在我想显示特定子列表的地方使用这个简码:

带有帖子ID: [wpb_childpages id="{POST_ID} /] 例如[wpb_childpages id="123" /]

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

标签: wordpresswordpress-theming

解决方案


推荐阅读