WordPress Shortcode - 按ID获取发布数据

时间:2014-08-23 21:21:53

标签: php wordpress shortcode

我创建了一个帖子类型名称“Gallery”,并添加了一些帖子元框。现在,让我们说每个单独的图库都有标题和内容。

现在,我想用Shortcode来利用这些数据。这怎么可能?

例如 -
[gallery id = x]

我知道如何获取ID( x )的值,但如何输出具有该值ID的帖子?

我像这样注册了这个短代码(但当然没有完成)

function shortcote_gallery( $atts , $content = null ) {
    extract( shortcode_atts(
        array(
            'title' => 'Default Gallery Title'
        ), $
    return "<h3>$title</h3><p>$content</p>";
}
add_shortcode( 'gallery', 'shortcote_gallery' );

我希望我足够清楚。如果没有,请告诉我,以便我更好地解释自己。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

你需要这个功能吗?或者我还没有理解你的问题。 https://codex.wordpress.org/Function_Reference/get_post

享受您的代码!

答案 1 :(得分:0)

在你的例子中:

[gallery id=x] 将字段id作为参数。

所以在你的短代码函数中,你也需要提取它。

function shortcote_gallery( $atts , $content = null ) {
    extract( shortcode_atts(
        array(
            'title' => 'Default Gallery Title',
            'id' => '',
        ), $atts));
    return "<h3>$title</h3><p>$content</p>";
}

你现在可以用通常的php方式做你想做的一切。 $id现在具有您在帖子中输入的值。因此,如果您想输出具有此ID的内容,只需向数据库发出查询并获取所需的结果。

如果你有这样的事情:

global $wpdb;
$results = $wpdb->get_results("SELECT * FROM `myTable` WHERE id ='".$id."'");

在这里,您可以格式化输出:

$content = "You have selected ".$results[0]->myField." with the id: $id";
return $content;
相关问题