0

I have a custom post type "product" and I want to retrieve and display on a page all the values for a ACF field "product_url". I don't have access to the db via PHP MyAdmin, so I'm trying to query the data and display on a page. I cannot get it to work correctly. The closest I have come is getting Post Titles, but anytime I modify the below code, it stops working.

function output_product_links() {
    global $wpdb;
    $custom_post_type = 'product'; 
    $results = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = %s and post_status = 'publish'", $custom_post_type ), ARRAY_A );
    if ( ! $results )
            return;
            $output = '<ul id="links">';
            foreach( $results as $index => $post ) {
            $output .= '<li id="' . $post['ID'] . '">' . $post['post_title'] . '</li>';
                }
            $output .= '</ul>';
            return $output;
    }

Whenever I change "post_title" in the SQL query and the $output to "product_url" nothing is output. I would like a list that displays the product name then the product url for all posts type=product in a list.

1

Why are you using $wpdb? This is a simple query, check the ACF docs for usage examples (https://www.advancedcustomfields.com/resources/query-posts-custom-fields/)

<?php 
// args
$args = array(
    'numberposts'   => -1,
    'post_type'     => 'product'
);

// query
$the_query = new WP_Query($args);

?>
<?php if( $the_query->have_posts() ):?>
    <ul>
    <?php while( $the_query->have_posts() ) : $the_query->the_post();?>
        <li>
            <?php the_title();?> - <a href="<?php the_field('product_url');?>"><?php the_field('product_url');?></a>
        </li>
    <?php endwhile;?>
    </ul>
<?php endif;?>

<?php wp_reset_query();?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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