使用wp_query列出帖子标题

时间:2012-10-21 12:18:54

标签: php ajax wordpress

我正在尝试使用常规wp_query列出帖子标题,只是将永久链接添加到项目的href中,这是我正在使用的代码:

    <?php $the_query = new WP_Query( 'post_type=artworks_post' );
        // The Loop
        while ( $the_query->have_posts() ) : $the_query->the_post();
            echo '<a rel="' .the_permalink(). '" href="' .the_permalink. ' ">';
            the_title();
            echo '</a>';
        endwhile;

        // Reset Post Data
        wp_reset_postdata();
    ?> 

问题是代码无效,只返回带有“永久链接”一词的href,但没有链接本身。

我在这里做错了什么?

3 个答案:

答案 0 :(得分:6)

尝试使用get_permalink而不是the_permalink。函数the_permalink正在打印永久链接本身(http://codex.wordpress.org/Function_Reference/the_permalink),但函数get_permalink返回永久链接字符串(http://codex.wordpress.org/Function_Reference/get_permalink)。

无论如何只是一个建议,使用printf而不是echo。比如,

<?php $the_query = new WP_Query( 'post_type=artworks_post' );
    // The Loop
    while ( $the_query->have_posts() ) : $the_query->the_post();
        echo '<a rel="' .the_permalink(). '" href="' .the_permalink. ' ">';
        the_title();
        echo '</a>';
    endwhile;

    // Reset Post Data
    wp_reset_postdata();
?> 

根据要求,我使用echo而不是printf

添加示例
<?php
    $the_query = new WP_Query( 'post_type=artworks_post' );
    // The Loop
    while ( $the_query->have_posts() ) : $the_query->the_post();
        echo '<a rel="' .get_permalink(). '" href="' .get_permalink(). ' ">';
        the_title();
        echo '</a>';
    endwhile;

    // Reset Post Data
    wp_reset_postdata();
?> 

答案 1 :(得分:1)

你错过了括号;

         echo '<a rel="' .the_permalink(). '" href="' .the_permalink(). ' ">';
        the_title();
        echo '</a>';

答案 2 :(得分:1)

您在the_permalink之后使用了the_permalink()而不是href

但是,您应该使用的是get_permalink(),它会立即返回echo而不是echo使用的值。