将woocommerce产品连接到帖子

LTe*_*ech 2 wordpress woocommerce

我在wordpress网站上使用woocommerce.我在卖画.产品是绘画.我有一个艺术家列表作为帖子.每个艺术家都是一个帖子.我想连接帖子和产品,以便我可以在绘画页面上显示艺术家的名字,用户可以点击名称,然后将它们带到艺术家的帖子.我该怎么做呢?

Dan*_*jel 5

这是如何在WooCommerce产品常规选项卡中添加自定义字段的示例.由于艺术家是帖子(未指定类别),因此它将收集所有帖子的链接并将其放入下拉列表中.此字段的价值将显示在价格下方的单个产品页面上(您可以content-single-product.php在WooCommerce主题中打开文件,查看单个产品模板的操作和附加的功能,并根据需要更改woocommerce_product_artist功能的优先级更改链接将出现的位置).

<?php

add_action( 'admin_init', 'woocommerce_custom_admin_init' );

function woocommerce_custom_admin_init() {

    // display fields
    add_action( 'woocommerce_product_options_general_product_data', 'woocommerce_add_custom_general_fields' );

    // save fields
    add_action( 'woocommerce_process_product_meta', 'woocommerce_save_custom_general_fields' );

}

function woocommerce_add_custom_general_fields() {

    // creating post array for the options ( id => title)
    $posts = array( '' => __( 'Select Artist' ) );
    array_walk( get_posts( array( 'numberposts' => -1 ) ), function( $item ) use ( &$posts ) {
        $posts[ $item->ID ] = $item->post_title;
    } );

    // creating dropdown ( woocommerce will sanitize all values )
    echo '<div class="options_group">';
    woocommerce_wp_select(
        array(
            'id' => '_artist',
            'label' => __( 'Artist' ),
            'options' => $posts
        )
    );
    echo '</div>';

}


function woocommerce_save_custom_general_fields( $post_id ) {
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

    // validate id of artist page and save
    if ( isset( $_POST['_artist'] ) ) {
        $value = filter_input( INPUT_POST, '_artist', FILTER_VALIDATE_INT, array( 'options' => array( 'min_range' => 0 ) ) );       
        update_post_meta( $post_id, '_artist', $value );        
    }

}

add_action( 'init', 'woocommerce_custom_init' );

function woocommerce_custom_init() {    

    // hook the woocommerce_product_artist function on to woocommerce_single_product_summary action ( priority 15 )
    add_action( 'woocommerce_single_product_summary', 'woocommerce_product_artist', 15 );

}

function woocommerce_product_artist() {
    global $post;

    // get the artist page id and show in template ( if exists )
    $artist_id = get_post_meta( $post->ID, '_artist', true );

    if ( $artist_id ) : 
    ?>
        <div class="product-artist"><a href="<?php echo get_permalink( $artist_id ); ?>"><?php echo get_the_title( $artist_id ); ?></a></div>

    <?php endif;
}

?>
Run Code Online (Sandbox Code Playgroud)