尝试在一个简单的插件中获取自定义字段数据

时间:2018-12-14 作者:Praveen Kalarikkal

该值未在此插件中获取和显示。当我在主题的其他地方添加代码时,它工作正常。

<?php
    function related_posts( $atts ) {

    // set the category ID (or multiple category IDs)
    // you want to ignore in the following array
    $cats_to_ignore = array( 2 );
    $categories = wp_get_post_categories( get_the_ID() );
    $category_in = array_diff( $categories, $cats_to_ignore );
    // ignore only if we have any category left after ignoring
    if( count( $category_in ) == 0 ) {
        $category_in = $categories;
    }
    $cat_args = array(
        \'category__in\'   => $category_in,
        \'posts_per_page\' => 5,
        \'orderby\'        => \'date\',
        \'post__not_in\'   => array( get_the_ID() )
        );
    $cat_query = new WP_Query( $cat_args );
    while ( $cat_query->have_posts() ) : $cat_query->the_post();
        /* just example markup for related posts */
        echo \'<li style="list-style: none;"><a href="\' . get_the_permalink() . \'">\' . get_the_title() . \'</a></li>\';
        $gread = get_post_meta($post->ID, \'read_time\', true);
        $gdate = get_the_date();
        echo \'<span style="font-size:12px; margin-left: 22px;"> Read Time: \'.$gread.\' Minutes </span>\';
        echo \'<span style="font-size:12px; margin-left: 22px;"> Posted: \'.$gdate.\' </span>\';
    endwhile;
    // reset $post after custom loop end

}
add_shortcode( \'relatedpost\', \'related_posts\' );

1 个回复
SO网友:Max Yudin

你没有$post 对象,但尝试在代码中使用它($post->ID). 使用get_the_ID() 改为函数:

<?php
while ( $cat_query->have_posts() ) : $cat_query->the_post();
    // $gread = get_post_meta( $post->ID, \'read_time\', true );  // Wrong
    $gread = get_post_meta( get_the_ID(), \'read_time\', true );      // Right
endwhile;

}
从现在开始always enable debugging 当你发展的时候。这样你就可以避免浪费时间和问一些不切实际的问题。

相关推荐

如何让`wp-list-table`显示我在Custom-Post中的`Custom-Fields`

一切都好吗<我需要wp-list-table 也要显示custom-fields 在每个custom-post 我有,但我不知道如何做到这一点,在这幅图中,它显示了带有字段的表格:Title, Author and Publication Date: 我想要的是能够选择custom-fields 将出现,例如以下示例Title, Carta, Naipe, Author, and Date of Publication: