Enhancing Efficiency through Leveraging get_post_meta in WordPress

In my WordPress, I have implemented a logic where each CPT shop_order has a post_meta called "luck_number". However, the issue arises when there are more than 1000 sales per post in this CPT. When I try to retrieve the post_meta with get_post_meta inside a while loop, the page takes around 15 minutes to load.

I conducted a test and found that the speed is acceptable when there are only a few post_meta. But as soon as we reach the thousands, it becomes significantly slower.

Is there a better approach to ensure good performance even in scenarios where there are thousands of post_meta per POST?

The relevant section of code looks like this:

<?php 

$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); 
                      
          $numbers = get_post_meta(get_the_ID(),"luck_number",false);

          $a = 0;
          while($a<count($numbers)):

            // DO SOMETHING WITH THE NUMBER
            $a++;

          endwhile;

endwhile; 
wp_reset_query(); 

When each post contains an average of 0 to 500 numbers, everything works fine. However, when the count exceeds 1000, the performance degrades significantly.

I typically have 'posts_per_page' set at 25, but even reducing this number doesn't have much impact on the result. The server infrastructure (a reliable VPS) and PHP memory_limit (currently set to 1024M) do not seem to be major factors influencing the performance.

Answer №1

If you are looking to retrieve a single custom field from a Custom Post Type (CPT), there is no need to utilize the WP_Query function. Instead, you can simply gather all the fields in an array using the $wpdb object.

Give this code a try:

function get_custom_field_from_db( $key = '', $type = 'post', $status = 'publish' ) {
    
        global $wpdb;

    if( empty( $key ) )
        return;
                        
        $result = $wpdb->get_results( $wpdb->prepare( "
        SELECT pm.post_id, pm.meta_value FROM {$wpdb->postmeta} pm
        LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
        WHERE pm.meta_key = '%s' 
        AND p.post_status = '%s' 
        AND p.post_type = '%s'
    ", $key, $status, $type ) );

        foreach($result as $value) {
        if($value !="") {
        $custom_field_array[$value->post_id] = $value->meta_value;
        }

    }
    
    return $custom_field_array;
    
}



$array_result = get_custom_field_from_db('custom_field_key','custom_post_type_name', 'publish');

print_r($array_result);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The functionality of the jQuery script is not operating optimally, causing the expected alert to not be displayed

I implemented this jQuery script: $('input[name="add-post"]').on('click', function(form) { form.preventDefault(); for ( instance in CKEDITOR.instances ) CKEDITOR.instances[instance].updateElement(); $.ajax({ typ ...

Using Javascript code within functions.php

I am facing an issue with the code below; function add_js_functions(){ $gpls_woo_rfq_cart = gpls_woo_rfq_get_item(gpls_woo_rfq_cart_tran_key() . '_' . 'gpls_woo_rfq_cart'); if(is_array($gpls_woo_rfq_cart)){ $count = count($gpls_woo_r ...

Having trouble with unexpected ternary statements appearing in Laravel Blade?

In one of my blade templates, I have a function call that should receive a string as its first parameter. However, Laravel seems to be interpreting the string and adding a ternary operation because it detects a '?' symbol followed by 'or&apo ...

Having Issues Getting Results from Curl Post Scraping

I am trying to scrape data from the website marcanet.impi.gob.mx/marcanet/controler/RegistroBusca using the code below, but I am unable to reach the result page. $form_url = "http://marcanet.impi.gob.mx/marcanet/controler/RegistroLista"; $data_to_post = a ...

Utilizing Laravel: executing several functions on a single object instance

As someone who is new to laravel and OOP, I find myself facing some challenges with facades that I can't quite understand. Let's say I am working on a class in PHP to interact with an API and create shipment labels for ecommerce orders. The clas ...

Embedding services into Entities: Verifying the presence of an image file

Currently, I am working with PHP and the Doctrine ORM. The situation at hand involves a product table that has an image field. My goal is to create an event that verifies whether an image exists in my assets cloud storage (specifically Amazon S3). If the f ...

The server's delayed response caused the jQuery ajax request to be aborted

Encountering delayed AJAX response from the PHP server upon aborting the AJAX request. Currently utilizing the CodeIgniter framework for the server script. Javascript Code: cblcurrentRequest = $.ajax({ url: baseurl + 'Login/getChannelBra ...

The sum function in MySQL only seems to work accurately for the first row, but can often give

Here is the SQL query I am using: SELECT `cuenta`.`reservaId`, sum(`cuenta`.`tarifaTotal`) FROM `check`,`cuenta`,`comanda`,`reserva` WHERE `comanda`.`id`=`cuenta`.`idComanda` AND `comanda`.`tipo`=0 GROUP BY `cuenta`.`reservaId` ORDER BY `check`.`id` Howe ...

Symfony allows for unique field validation for one-to-many relationships

My Request entity contains multiple Interventions structured as follows: Request.php /** * @ORM\OneToMany(targetEntity=Intervention::class, mappedBy="request") * @Assert\Count(min=1, max=3) * @Assert\Valid ...

adjust variable increment in JavaScript

As I work on developing a Wordpress theme, I have encountered an issue with incrementing a load more button using Javascript. This is my first time facing this problem with a javascript variable, as I don't always use Wordpress. The variable pull_page ...

Enhance the appearance of specific wordpress usernames by adding a touch of "flair" next to them

I'm looking to add a special "flair" next to specific users on my WordPress website, similar to how YouTube distinguishes verified users. I have the CSS for changing the color on hover, but I need help keeping it positioned correctly. Examples from Y ...

Select a particular item and transfer its unique identifier to a different web page. Are there more efficient methods to accomplish this task without relying on href links and using the $_GET

Could there be a more efficient method for transferring the ID of a specific motorcycle from index.php to inventory.php when it is clicked on, aside from using href and $_GET? Perhaps utilizing hidden fields or submitting a form through JavaScript? What ...

Presenting JSON information in a concise and visually appealing manner

How can I extract a value from JSON data and display it in an HTML text field? The JSON data looks like this: {"name":"paul"}, but I only want to display "paul" in my text field. Here is my code in CodeIgniter PHP: $data['name'] = $this->name ...

Tips for using Carbon to calculate the duration of the weekends in hours?

I've been trying to utilize Carbon's weekend related functions, but they don't seem to be working as expected for me. My goal is to determine the duration of the weekend in hours and minutes. For instance, considering that the weekend star ...

Transform a SQL PHP script into ColdFusion

Our developers have provided a script for PHP to generate a best sellers list from our database. However, we need it to work in ColdFusion! Is there an easy way to convert it or will it require a complete rewrite? Thank you in advance for any advice :-) ...

Sending a JSON object with scheduled task cron job

I have a PHP cron job that is quite complex. It retrieves data from an external webpage and consolidates all the information into one variable, encoding it in JSON. Unfortunately, this entire process is slow and consumes a significant amount of time. My d ...

When using jQuery and AJAX, the functions each, if, post, and .html work properly but occasionally erase data inexplicably

I have a PHP page containing FedEx and UPS tracking numbers stored in a MySQL database, which are displayed within DIVs with the class "trackingnumber". Using JavaScript, I loop through these divs to retrieve the ID and then send it to a PHP page that fetc ...

Looking into time zones that do not observe daylight saving time

My code successfully converts timezones to GMT/UTC and vice-versa. However, I am looking to enhance its functionality by checking for non-DST timezones and allowing for dates/times in any format. For example, if only a date is provided, the correct result ...

What could be causing the undefined status of my checkUser() function?

I have implemented a brief script on my signup page to define the function checkUser(user) at line 6. In the code section at the end of the HTML for the sign up form, I included an inline script onBlur='checkUser(this) within the <input> named ...

I'm wondering why this isn't working properly and not displaying the closing form tag

What could be the reason for this not functioning properly? The tag appears to close on its own and the closed tag is not being displayed. As a result, the if(isset($_POST['payoneer-btn'])) statement is not triggering. https://i.stack.imgur.com/ ...