Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I suddenly have a bug in my plugin, and I don't know what on earth could be causing it. This code is failing because get_permalink() is returning empty at all times:

$select = "SELECT * FROM `".DB_NAME."`.`wp_posts` WHERE `post_status` = 'publish'";
$result = mysql_query($select);
while($meta_posts = mysql_fetch_array($result, MYSQL_ASSOC) ){
    $menu .= "<option value=\"".get_permalink($meta_posts['ID'])."\">".$meta_posts['post_title']."</option>\n";
}

It used to work just fine, all it does is return a dropdown menu of all the published WP posts/pages. Now I get the dropdown full of titles, but there is no permalink in the option value.

Anyone have any ideas why get_permalink() would be empty? I've even tried hardcoding a known postid into it, and it's still empty.

share|improve this question
add comment

2 Answers

First off, you should use get_posts instead of a raw SQL query. Or at least use $wpdb.

<?php
$posts = get_posts(
    array(
        'post_status' => 'publish'
        'numberposts' => -1
    )
);

Then, try passing the entire post object to get_permalink, which saves some database queries.

<?php
foreach( $posts as $p )
{
    $link = get_permalink( $p );
    // do stuff here...
}

The only thing I saw in get_permalink that might cause an empty string it it checking for an empty post ID. Try the above, and see if it works for what you need.

share|improve this answer
    
Thanks for the suggestion. Unfortunately, this just returns an empty array: $posts = get_posts( array( 'post_status' => 'publish', 'numberposts' => -1 ) ); die(print_r($posts)); –  Jonathan van Clute Oct 28 '11 at 22:22
    
Just try doing $posts = get_posts(); without any additional arguments. –  chrisguitarguy Oct 28 '11 at 22:35
    
no difference, empty array... –  Jonathan van Clute Oct 28 '11 at 22:38
    
You do have posts, correct? Or do you only have pages? Other than that I have no idea why get_permalink or get_posts is not working. Sorry. –  chrisguitarguy Oct 28 '11 at 22:44
    
have both posts and pages. =( Can't make any sense of this... –  Jonathan van Clute Oct 28 '11 at 22:46
show 6 more comments

Try this:

query_posts( 'post_status=publish&posts_per_page=-1' );

while ( have_posts() ) : the_post();
    $menu .= "<option value=\"".get_permalink(get_the_ID())."\">".get_the_title()."</option>\n";
endwhile;
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.