Recently I wanted to get a list of all the tutorials we’d published on LowEndBox.
While I could do this in the wp-admin, I wanted to get something I could copy-paste into a page. Going through the dashboard would involve copy-pasting each title and link, which would be a ton of work.
My first impulse was to script something in SQL that queried the database and spit out a list of href’d article titles. But a few minutes’ research showed this was the wrong approach. You really shouldn’t need to write SQL to query your WordPress DB. Using WordPress’s code is much easier.
In fact, it’s so easy that I was able to complete my task in about 30 minutes. I went from never having written a single line of WordPress code to producing the report I wanted in that short time.
Let’s take a look!
Create a .php file like this in the root of your WordPress directory:
<html> <body> <?php require __DIR__ . '/wp-blog-header.php'; $the_query = new WP_Query( array( 'category_name' => 'tutorials', 'nopaging' => true ) ); echo 'found posts ' . $the_query->found_posts . '<br />'; if ( $the_query->have_posts() ) { echo "<ul>\n"; while ( $the_query->have_posts() ) { $the_query->the_post(); echo '<li><a href="' . get_permalink() . '">' . esc_html( get_the_title() ) . "</li>\n"; } echo "</ul>\n"; } else { esc_html_e( 'Sorry, no posts matched your criteria.' ); } ?> </body> </html>
Let’s walk through it. This line loads the WP libraries:
require __DIR__ . '/wp-blog-header.php';
Once that’s done, we can use WP_Query to create our query. The WordPress Codex reference has all the details. In this case, we’re querying by category_name (“tutorials”) and turning on “nopaging”. Without “nopaging” you’ll only get the first set of results. With “nopaging” set to true, you’ll get every result in the set.
echo 'found posts ' . $the_query->found_posts . '<br />';
This reports how many results are found.
Now we start The Loop, which is WordPress terminology for a big “foreach post found” loop. We wrap it in a test to make sure we have some posts, and then here’s the heart:
while ( $the_query->have_posts() ) { $the_query->the_post(); echo '<li><a href="' . get_permalink() . '">' . esc_html( get_the_title() ) . "</li>\n"; }
This code means “for each post returned by the query (the “while”), get the post as an object and then use it”. the_post() fetches the next post from the query and puts it in the current context, so the functions get_permalink() and get_the_ttitle() return the desired results.
And it’s just that easy!
Related Posts:
- CYBER MONDAY: VerpexWeb has Cheap cPanel Hosting for Under $7/Year!DirectAdmin for Only $3.50/Year! - December 2, 2024
- CYBER MONDAY: A VPS for Only $8.88 a Year!Wow!Check Out DediRock’s Cyber Monday Sale - December 2, 2024
- CYBER MONDAY: HostDare has a VPS for Less Than $10/Year in Los Angeles, California! - December 2, 2024
Leave a Reply