gpt4 book ai didi

wordpress - 将 woocommerce 产品连接到帖子

转载 作者:行者123 更新时间:2023-12-02 01:05:50 30 4
gpt4 key购买 nike

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

最佳答案

这是一个如何在 WooCommerce 产品常规选项卡中添加自定义字段的示例。由于艺术家是帖子(未指定类别),它将收集所有帖子的链接并将它们放在下拉列表中。该字段的值将在价格下方的单品页面上可见(您可以在 WooCommerce 主题中打开 content-single-product.php 文件,以查看单品模板的操作,以及附加功能,如果您想更改链接出现的位置,请更改 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;
}

?>

关于wordpress - 将 woocommerce 产品连接到帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22618776/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com