首页 文章

在WordPress中显示页面上的特定帖子

提问于
浏览
1

在网站上,每个产品都是一个帖子,但是当我们添加新产品时,我们想要一些类似于时事通讯的内容,大多数情况下就像一个帖子,因此在主页的侧边栏中,您可以看到本月的新产品或事件 .

我正在使用页面,因为我不想在每个新的时事通讯上重新发布产品,所以我想要在页面内显示帖子 .

在产品页面中,我按类别和子类别分隔每个产品,但由于我想将特定帖子分组以在侧栏上发布,我认为页面是最好的方法 .

Right now I'm using this code:

<?php
$productos = new WP_Query(array(
'post__in'=> array(81, 83),
'orderby'=>'title',
'order'=>'ASC'
)
); if ($productos->have_posts()) : while ($productos->have_posts()) : $productos->the_post();
?>

它显示id为81和83的帖子,我想用'name'来显示slug的帖子,因为它会花费一些时间来检查新帖子的ID,而不是使用名称每一个新产品,但它不能在阵列中工作或我做错了什么 .

现在我会喜欢做这样的工作

$names = get_post_meta($post->ID, "names", $single = true); 

$productos = new WP_Query(array(
'name'=> array($names),
'orderby'=>'title',
'order'=>'ASC'
)
);

因此,每次我发布一个新页面时,我只是在自定义字段中编写我想要包含在页面中的帖子,因为你可以看到我对PHP不是很好但是我想学习并搜索一个在这里询问之前可以使用的东西很多 .

我尝试ggis内联post插件,虽然它有效,但我需要包含我要包含的每个帖子的id,我需要编辑插件,因为我想在帖子的输出中有不同的顺序,这就是为什么我不喜欢很依赖插件 .

Update:

所以我现在正在寻找是否可以使用短代码制作这个,现在我有这个:

function producto_func($atts) {
    extract(shortcode_atts(array(
        'nombre' => ''
    ), $atts));
    global $post;
    $pieza = get_page_by_title($nombre,OBJECT, 'post');
                echo '<h1>'. $pieza->ID . '</h1>';
}
add_shortcode('producto', 'producto_func');
enter code here

所以我只需在页面中输入短代码 [producto nombre="ff 244"] 并显示其ID,我可以添加任意数量的短代码,具体取决于我需要的帖子数量 . 但是如何显示帖子的全部内容 .

任何的想法?

2 回答

  • 1

    来自Wordpress Codex

    通过slug显示 post

    $ query = new WP_Query('name = about-my-life');

    通过slug显示 page

    $ query = new WP_Query('pagename = contact');

    UPDATE

    尝试改变这个:

    'name'=> array($names),
    

    对此:

    'name'=> $names,
    

    'name'和'pagename' - 参数不接受数组 . 只有一个字符串 . 以逗号分隔的列表应该在 Headers 为“名称”的自定义字段中为您提供所需的内容,但我还没有测试过这种方法 .

    另外,感谢您使用WP_Query而不是query_posts .

  • 1

    我找到了使用Shortcodes的解决方案 . 所以我把它放在我的functions.php页面上

    function productos($atts, $content = null) {
        extract(shortcode_atts(array(
            "slug" => '',
            "query" => ''
        ), $atts));
        global $wp_query,$post;
        $temp = $wp_query;
        $wp_query= null;
        $wp_query = new WP_Query(array( 
        'name'=> $slug,
        ));
        if(!empty($slug)){
            $query .= '&name='.$slug;
        }
        if(!empty($query)){
            $query .= $query;
        }
        $wp_query->query($query);
        ob_start();
        ?>
        <?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
            <h1><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h1>
            <div><?php the_content() ?></div>
        <?php endwhile; ?>
    
        <?php $wp_query = null; $wp_query = $temp;
        $content = ob_get_contents();
        ob_end_clean();
        return $content;
    }
    add_shortcode("producto", "productos");
    

    在我的页面模板中,我只写了[producto slug =“MY-SLUG”],这样我就可以用slug显示多个帖子 . 希望有人觉得这很有用 .

相关问题