【问题标题】:Display custom posts with shortcode使用简码显示自定义帖子
【发布时间】:2016-02-11 21:40:05
【问题描述】:

我已经在这个论坛上搜索了 2 天来寻求帮助,但我找不到我想要实现的解决方案。

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

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

像这样: [产品名称=“我的产品”]

这将在一些 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;

【问题讨论】:

  • 有什么理由不能只使用 WooCommerce?
  • 我的原因是我希望网站非常轻便。我不需要网站的整个电子商务功能包。我们只会在某些页面上展示我们的部分产品(最多 20 种产品)。这是我追求的唯一功能。我认为只创建一个短代码来显示特定页面上的示例 4 产品会容易得多。用于订购产品的整个电子商务页面在 wordpress 之外。但是请随时与我讨论为什么我仍然应该使用 woocommerce。我对这一切都很陌生,我正在边做边学。 :)
  • 我的建议是对问题进行编码尝试。 SO 上没有人会从头开始为您做这一切。这就是你被否决的原因。其实我真正的建议是使用 WooCommerce 哈哈。
  • 我明白了!我只是认为没有必要显示我的代码,因为它可能一团糟,哈哈。但我已将其添加到我的第一篇文章中!我的一个朋友(他不想一直帮助我)告诉我,由于我在这种帖子类型上使用高级自定义字段,我可以编写这段代码并根据我的需要对其进行自定义从每个产品中获取两个字段,这基本上就是我所需要的,他说。但我不知道把它放在哪里,或者从我现有的代码中删除什么

标签: php html wordpress shortcode


【解决方案1】:

我同意 James 的观点——我只会使用 woocommerce。

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

一旦您尝试创建自己的短代码,如果仍然无法正常工作,那就是寻求帮助的时候了。

【讨论】:

  • 该教程错误且过时,应该使用
  • 我已经为同一个网站写了很多简码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-20
  • 2014-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多