Wordpress自定义订购后链接功能

时间:2014-05-19 11:38:33

标签: wordpress

我使用自定义帖子类型来保存产品,每个产品都通过自定义字段保存一个名称。当我通过其单一模板显示产品时,最好有一个下一个&之前的链接要经过这些产品,但它应按照其名称顺序浏览。目前这是不可能的,因为他们将按他们的发布日期排序。

所以我在functions.php中添加了以下代码,但是它不起作用,我不知道这是否必须以不同的方式进行:

if(is_singular('products')) {
    add_filter('get_previous_post_join', 'rt_post_join');
    add_filter('get_next_post_join', 'rt_post_join');
    add_filter('get_previous_post_where', 'rt_prev_post_where');
    add_filter('get_next_post_where', 'rt_next_post_where');
    add_filter('get_previous_post_sort', 'rt_prev_post_sort');
    add_filter('get_next_post_sort', 'rt_next_post_sort');
}

function rt_post_join($join, $isc, $ec) {
    global $wpdb;

    $join = " INNER JOIN $wpdb->postmeta AS pm ON pm.post_id = p.ID";
    return $join;
}

function rt_prev_post_where($w) {
    global $wpdb, $post;

    $prd = get_post_meta($post->ID, 'data_product_name_product', true);
    $w = $wpdb->prepare(" WHERE pm.meta_key = 'data_product_name_product' AND pm.meta_value < '$prd' AND p.post_type = 'products' AND p.post_status = 'publish'");
    return $w;
}

function rt_next_post_where($w) {
    global $wpdb, $post;

    $prd = get_post_meta($post->ID, 'data_product_name_product', true);
    $w = $wpdb->prepare(" WHERE pm.meta_key = 'data_product_name_product' AND pm.meta_value > '$prd' AND p.post_type = 'products' AND p.post_status = 'publish'");
    return $w;
}

function rt_prev_post_sort($o) {
    $o = "ORDER BY pm.meta_value DESC LIMIT 1";
    return $o;
}
function rt_next_post_sort($o) {
    $o = "ORDER BY pm.meta_value ASC LIMIT 1";
    return $o;
}

在我的单页产品(single-products.php)中,我添加了以下代码来显示分页链接:

<?php next_post_link('%link', 'Next product'); ?>
<?php previous_post_link('%link','Previous product'); ?>

感谢。

2 个答案:

答案 0 :(得分:0)

您实际需要的是自定义查询。你可以尝试这个(没有测试过):

将它放在你的functions.php中:

function getProductsQuery() {
    return new WP_Query(array(
        'posts_per_page' => 10,
        'post_type' => 'product',
        'orderby' => 'title',
        'order' => 'ASC'
    ));
}

然后,用以下内容替换你的循环:

<?php $products = getProductsQuery(); ?>
<?php while($products->have_posts()): $products->the_post(); ?>
    <h2><?php the_title(); ?></h2>
    (...)
<?php endwhile; ?>

答案 1 :(得分:0)

最后我解决了!

我刚刚使用了插件Next/Previous Post Link Plus for WordPress并在我的产品单页中添加了以下代码(single-products.php):

<?php next_post_link_plus( array(
                            'order_by' => 'custom',
                            'meta_key' => 'data_product_name_product',
                            'link' => 'Next product',
                            'format' => '%link'
                            )); ?>
<?php previous_post_link_plus( array(
                            'order_by' => 'custom',
                            'meta_key' => 'data_product_name_product',
                            'link' => 'Previous product',
                            'format' => '%link'
                            )); ?>