显示带有短代码的自定义帖子

时间:2016-02-10 09:26:52

标签: php html wordpress shortcode

我已经在这个论坛上寻找了2天的帮助,但我无法找到解决方案来解决我想要达到的目标。

我有一个名为“product”的自定义帖子类型,并且在该帖子类型的每个帖子中有两个名为produktnamn(带产品名称的文本字段)和produktbild(产品图片)的自定义字段。就是这样。

现在我需要一个短代码,通过输入它的slug(与它的名字相同)来显示该帖子类型中的特定帖子。

像这样: [product name =“myproduct”]

这将在一些HTML标记内呈现名称和产品图像。

请帮忙!

到目前为止我的代码:

//Product image
function cpt_content_func($atts){

    extract( shortcode_atts(['name' => null], $atts ) );

    $args = [
        'name' => $slug,
        'post_type' => 'product',
        'numberposts' => 1
    ];

    $posts = get_posts( $args );
    $post = $post[0];

    $title = $post->title;
    $id = $post->ID;

    get_post_meta('produktbild', $id);

    $content = $post[0]->post_title;
    return '<h3>'.$content.'</h3>';
}

add_shortcode('product','cpt_content_func');

解决了它。这是代码!

function display_custom_post_type( $atts ){
// Handle the attributes
$atts = shortcode_atts(
    array(
        'cat' => ' '
    ), 
$atts, 'products_by_cat' );

// Set default values for the post
$args = array(
    'posts_per_page' => -1,
    'post_type' => 'product',
    'post_status' => 'publish',
    'category' => $atts['cat']
);
// Get posts
$posts_array = get_posts( $args );

// Check if posts exist
if( !empty($posts_array) ){
    $string = '<div class="row">';
    foreach( $posts_array as $post ){
        $string .= '<div class="col-sm-3 text-center">';
        $string .= '<div class="product-container">';
        $string .= '<a href="' . get_field( "order_link", $post->ID ) . '">';
        $string .= '<img class="product-img" src="' . get_field( "produktbild", $post->ID ) . '">';
        $string .= '</a>';
        $string .= '</div>';
        $string .= '<p class="product-btn">' . get_field( "produktnamn", $post->ID ) . '</p>';
        $string .= '</div>';
    }
    $string .= '</div>';
} else {
    // Didn't find any posts.
}

// Return HTML
  return $string;

1 个答案:

答案 0 :(得分:-1)

我同意詹姆斯 - 我只是使用woocommerce。

但您必须首先学习如何构建短代码:http://code.tutsplus.com/tutorials/wordpress-shortcodes-the-right-way--wp-17165

一旦您尝试创建自己的短代码,如果事情仍然无效,那就是寻求帮助的时候了。

相关问题