如何将不同的CPT连接在一起?


11

我希望这个问题能在这里出现。

我一直认为将不同的“自定义帖子类型”连接在一起是很常见的需求,例如在自定义分类用法(书籍/作者/标题,电影/演员/导演等)的流行教程示例中。我个人使用“帖子2帖子”,但是支持停止了。

在Google上,最相关的结果现在指向此插件。存在哪些长期替代方案?如果P2P插件完成,今天经验丰富的WordPress Web开发人员将使用什么来设计WordPress的书籍/作者/标题管理系统?


您使用什么代码创建自定义帖子类型?您可以使用以下代码添加对创建自定义分类类型的支持:wordpress.stackexchange.com/a/128544/9884
Brad Dalton 2014年

1
我认为仍有许多人仍在使用p2p,所以我看不到它会很快失败,因为有人可以在github上对其进行维护。但是,如果放弃支持,我认为这只是意味着scribu正在开发新产品,或者该功能可能正在成为核心。我不认为这是不使用它的原因。
sanchothefat 2014年

1
我不太确定sancho。P2P在WP插件页面上只有55,000次下载,远没有我想象的那么流行。而且我不明白为什么,再次是因为将CPT连接在一起听起来对我来说是非常基本和普遍的需求。一个仅能解决一些基本问题的插件又怎么可能只有55,000次下载呢?那超出了我。唯一的解释是存在另一种解决该问题的好方法,因此是我的问题。
drake035 2014年

3
您可以继续使用此插件,如果该插件因某种原因失败,则可以分叉存储库并自己维护它:github.com/scribu/wp-posts-to-posts.git存储库中的引用:If you want to help maintain the plugin, fork it on github and open pull requests.
Scuba Kay

4
支持并加注了这个问题,因为我认为WordPress中的HABTM真的很有趣。就是说,我不会为插件淘汰太多,Mark Jaquith自愿帮助使其继续运转。虽然某些WP插件可能有300000次下载或其他下载,但在github上却没有多少人获得472星的支持。为了保持生命,这是至关重要的数字!
2014年

Answers:


13

作为程序员,我将开始编写自己的代码以连接我的帖子类型。这不是一种快速的方法,这并不容易,但是却很有趣。

职位类型

我们通过创建两个简单的文章类型开始,Author并且Books

add_action('init', 'p2p2_register_author');
add_action('init', 'p2p2_register_book');

function p2p2_register_author(){
    $labels = array(
        'name'               => 'Author',
        'singular_name'      => 'Author',
        'add_new'            => 'Add New',
        'add_new_item'       => 'Add New Author',
        'edit_item'          => 'Edit Author',
        'new_item'           => 'New Author',
        'all_items'          => 'All Authors',
        'view_item'          => 'View Authors',
        'search_items'       => 'Search Authors',
        'not_found'          => 'No authors found',
        'not_found_in_trash' => 'No authors found in Trash',
        'parent_item_colon'  => '',
        'menu_name'          => 'Authors'
    );

    register_post_type(
        'Author',
        array (
            'labels'             => $labels,
            'public'             => true,
            'publicly_queryable' => true,
            'show_ui'            => true,
            'show_in_menu'       => true,
            'query_var'          => true,
            'rewrite'            => array( 'slug' => 'author' ),
            'capability_type'    => 'post',
            'has_archive'        => true,
            'hierarchical'       => false,
            'menu_position'      => null,
            'supports'           => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
        )
    );
}
function p2p2_register_book(){
    $labels = array(
        'name'               => 'Books',
        'singular_name'      => 'Book',
        'add_new'            => 'Add New',
        'add_new_item'       => 'Add New Book',
        'edit_item'          => 'Edit Book',
        'new_item'           => 'New Book',
        'all_items'          => 'All Books',
        'view_item'          => 'View Book',
        'search_items'       => 'Search Books',
        'not_found'          => 'No books found',
        'not_found_in_trash' => 'No books found in Trash',
        'parent_item_colon'  => '',
        'menu_name'          => 'Books'
    );

    register_post_type(
        'Book',
        array (
            'labels'             => $labels,
            'public'             => true,
            'publicly_queryable' => true,
            'show_ui'            => true,
            'show_in_menu'       => true,
            'query_var'          => true,
            'rewrite'            => array( 'slug' => 'book' ),
            'capability_type'    => 'post',
            'has_archive'        => true,
            'hierarchical'       => false,
            'menu_position'      => null,
            'supports'           => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
        )
    );
}

那里什么都没有。实际上,它来自食典

元框

让我们继续将作者的metabox添加到我们的书帖类型中:

add_action('admin_init', 'p2p2_add_author_metabox');

function p2p2_add_author_metabox(){
    add_meta_box( 
        'book_author', 
        __('Book Author', 'bandpress'), 
        'p2p2_book_author_metabox', 
        'book', 
        'side', 
        'default', 
        array( 'id' => 'p2p2_author') 
    );
}

在这里,您可以看到一个回调函数p2p2_book_author_metabox,该函数将成为我们的元框内部的函数。

元框的内容

让我们创建一个函数:

function p2p2_book_author_metabox($post, $args){
    wp_nonce_field( plugin_basename( __FILE__ ), 'p2p2_book_author_nonce' );
    $author_id = get_post_meta($post->ID, 'p2p2_book_author', true);

    echo "<p>Select the author of the book</p>";
    echo "<select id='p2p2_book_author' name='p2p2_book_author'>";
    // Query the authors here
    $query = new WP_Query( 'post_type=author' );
    while ( $query->have_posts() ) {
        $query->the_post();
        $id = get_the_ID();
        $selected = "";

        if($id == $author_id){
            $selected = ' selected="selected"';
        }
        echo '<option' . $selected . ' value=' . $id . '>' . get_the_title() . '</option>';
    }
    echo "</select>";
}

这就是魔术发生的地方。首先,我们将在数据库中查询作者,然后<select>使用查询结果填充。有关更多信息,请查阅食典WP_Query。现在,您可以转到您的书帖类型并查看下拉菜单:

我们的下拉菜单

保存我们的内容

当然,我们想保存选择,所以我们添加了另一个为我们保存元框的函数:

add_action('save_post', 'p2p2_save_author_metabox', 1, 2);

function p2p2_save_author_metabox($post_id, $post){
    // Don't wanna save this now, right?
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return;
    if ( !isset( $_POST['p2p2_book_author_nonce'] ) )
        return;
    if ( !wp_verify_nonce( $_POST['p2p2_book_author_nonce'], plugin_basename( __FILE__ ) ) )
        return;

    // We do want to save? Ok!
    $key = 'p2p2_book_author';
    $value = $_POST["p2p2_book_author"];
    if ( get_post_meta( $post->ID, $key, FALSE ) ) { // If the custom field already has a value
        update_post_meta( $post->ID, $key, $value );
    } else { // If the custom field doesn't have a value
        add_post_meta( $post->ID, $key, $value );
    }
    if ( !$value ) delete_post_meta( $post->ID, $key ); // Delete if blank
}

现在去与作者保存一本书!这本书的作者将保存在wp_postmeta数据库表中,并且下拉列表的选定值将在元数据中。

书的作者专栏

让我们扩展书籍的管理区域。我们将从更改列开始:

add_filter('manage_edit-book_columns', 'p2p2_add_book_columns');

function p2p2_add_book_columns($columns){
    $new_columns['cb'] = '<input type="checkbox" />';

    $new_columns['title'] = _x('Title', 'column name', 'bandpress');

    $new_columns['p2p2_author'] = __('Author', 'bandpress');

    return $new_columns;
}

此函数确保我们仅看到列标题和p2p2_author。WordPress的批量编辑功能需要cb复选框列。现在,我们需要向列中添加一些信息。我们添加以下功能:

add_action('manage_book_posts_custom_column', 'p2p2_fill_book_columns', 10, 2);

function p2p2_fill_book_columns($column_name, $id) {
    global $wpdb;
    switch ($column_name) {
        case 'p2p2_author':
            $author_id = get_post_meta($id, 'p2p2_book_author', true);
            $author = get_post($author_id);
            $permalink = get_permalink($author_id);
            echo "<a href='" . $permalink . "'>" . $author->post_title . "</a>";
            break;
        default:
            break;
    } // end switch
}

该开关适用于您在上一个功能中刚刚添加的每一列。通过回显要显示的内容来填充它。我们得到的是该书的作者,并在其“个人资料页”上创建了一个不错的永久链接。看起来是这样的:

我们的作者专栏

未完待续

我们在WordPress网站的后端连接了两种帖子类型,但是在前端看不到它。要完成这项工作,还需要做更多的工作,但是可能性是无限的。我们可以:

  1. 按作者对书籍排序
  2. 在作者页面上显示书籍清单
  3. 在书籍页面上显示作者的其他书籍清单
  4. 用作者的图片创建一个精美的metabox
  5. 在作者管理页面中为他/她写的书创建一列
  6. 还有更多...

由于我自己需要此解决方案,因此我将继续研究此答案。但是,我将暂时停止工作。我将从明天开始更新此答案。


感谢您分享惊人的回复。您将如何显示作者撰写的书籍清单?
威廉

4

我不会担心太多,因为一些出色的开发人员自愿提供继续支持。但是,如果您想使用其他内容,请查看“ ACF关系”字段


孤立的链接和插件建议被认为是质量较差的答案。原因很简单:如果链接消失了,答案(和这个站点)就会遭受链接腐烂的困扰。
kaiser 2014年

3
随着时间的流逝,无链接的解决方案也会变得过时,这比死链接更糟糕,因为有些人可能会浪费时间尝试实施这些过时的解决方案,而又不知道它们不再起作用了。此外,ACF及其网站可能会持续很长时间。最后,非常感谢Bjorn提出的出色替代方案。
drake035 2014年

2

由于最初的问题是“如果P2P消失了该怎么办?” 我有一个想法/建议。我确实需要,因为如果您要构建一个插件,告诉用户安装另一个插件并不总是可行的。

一种简单的方法是使用Post Meta。例如。在作者的post_meta中,您可以存储书籍。可以是唯一条目,也可以是单个逗号分隔的条目,也可以是序列化的数组。然后在书上,存储作者的逆信息。

另一个方法是添加一个新的数据库表(不赞成使用),该表存储关系和其他相关信息。

不知道哪种解决方案在规模上有多有效,但它们都能奏效。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.