"Upon using the wordpress get_posts() function, it seems that the_ID()

I am facing an issue when trying to load a list of posts from a specific category using AJAX. Strangely, I am getting the correct number of posts and excerpts for each post, but the ID and title are empty, and the date is showing as 1.1.1970. Below is my function in functions.php:

function ajax_cat(){

if( isset($_GET['action'])&& $_GET['action'] == 'ajax_cat'){
 $my_id = htmlspecialchars($_GET["id"]);
 $args = array(
                'offset'          => 0,
                'category'        => $my_id,
                'orderby'         => 'post_date',
                'order'           => 'DESC',
                'post_type'       => 'post',
                'post_status'     => 'publish' ); 

            $myposts = get_posts( $args );
            foreach( $myposts as $post ) :  setup_postdata($post); ?>
                <div class="nadpis1" id="<?php the_ID(); ?>" >
                <a href="#<?php the_ID(); ?>"><?php the_title(); ?></a>
                <span class="sipka"><?php the_date("d.m. Y"); ?></span>
                </div>
                <div class="vnutro" ><?php echo the_excerpt();?></div>
            <?php endforeach; 
    die();
    }
}

This code used to work well within the loop, but now it's not functioning correctly. The output I currently get looks like this:

<div class="nadpis1" id="" >
   <a href="#"></a>
   <span class="sipka">01.01. 1970</span>
</div>
<div class="vnutro" ><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p></div>

<div class="nadpis1" id="" >
   <a href="#"></a>
   <span class="sipka"></span>
</div>
<div class="vnutro" ><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec adipiscing ultrices posuere. Aenean et egestas enim. Phasellus sit amet nisl elit. Sed pulvinar, purus nec commodo condimentum, lectus risus lacinia urna, sed ultrices magna est vitae turpis. Sed convallis pulvinar gravida. Sed non sem sem, at lobortis tellus. Etiam commodo risus vitae diam cursus volutpat. [...]</p></div>

<div class="nadpis1" id="" >
   <a href="#"></a>
   <span class="sipka"></span>
</div>
<div class="vnutro" ><p>gfdgdfsgngfjty ty jghj ty jtyhjghj dh gfdj5 fgjfdthbkdfgxhjsrgv ,f xfhbtyj dc rtjdtxhvcntydxvhctr shxfc</p></div>

<div class="nadpis1" id="" >
   <a href="#"></a>
   <span class="sipka">01.01. 1970</span>
</div>
<div class="vnutro" ><p>Vitajte vo WordPress. Toto je váš prvý článok. Môžete ho upraviť alebo vymazať a potom už len začať písať!</p></div

Your suggestions are greatly appreciated!

Answer №1

It is not recommended to utilize the the_ functions outside of The Loop. Instead, consider using get_the_title($postid); and similar get_ functions. These get_ functions return values without displaying them, so you'll need to use echo get_the_title($postid);.

Update: Upon further examination, it appears that you are using setup_postdata(). However, it may still be beneficial to opt for functions that accept the ID as a parameter rather than altering global settings with your loop. Take a look at $post using print_r to identify what data is already available in your foreach loop before making additional database queries.

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

How to display only the thumbnail on WordPress archive page and remove the post excerpt

I am currently in the process of revamping my category archive to resemble a grid layout by utilizing custom CSS. I have successfully eliminated the elements I desired using code like this: .archive .entry-footer { display: none; } Now, I only have t ...

Unable to retrieve data from JSON file using Ajax request

Trying to populate an HTML table with data from an external JSON file is proving to be a challenge. Despite making an AJAX request using pure JavaScript, nothing happens when the "Test" button is clicked. Take a look at the JSON data: { "row":[ { ...

New users placing orders through WooCommerce that are created programmatically will not be charged any tax

Currently, I am using Gravity forms to programmatically create a WooCommerce order. When an email already exists in the form, it retrieves the shipping and billing information from the user's account and correctly adds VAT. However, for new users who ...

Having trouble establishing a connection with the C# Controller when processing the frontend request

Having trouble implementing the Search by siteId functionality using typescript and C#. The issue arises when trying to connect to the C# controller from the frontend request. The parameter I need to pass is siteId. Below is the code snippet: HTML: ...

WordPress Error: Ajax Search Functionality

I am currently using WordPress for my website and have implemented Woocommerce for selling products. However, I encountered an error message as shown below when searching on the site: Catchable fatal error: Object of class WP_Error could not be converte ...

Implementing Ajax image upload functionality in Symfony2 framework

I am trying to implement a functionality where clicking on an image opens a window to select a new image and update the screen. However, when attempting to change the picture in the database, I encountered the following error: Catchable Fatal Error: Arg ...

Error: Attempting to create a 'guid' property on the 'option:selected' string is not possible and results in a TypeError

Encountering an error when trying to implement cascading drop down functionality using Ajax. Can someone provide assistance? <script type="text/javascript"> $("#os").change(function () { debugger var osid = $(this).select("opt ...

Having trouble with my $.ajax() call function, it's not behaving how I expected

When I send an ajax request like this: $.ajax({ type: "POST", url: "/videos", data: { title: oembed.title } }); within the function call to the Embedly API: $('a.oembed').embedly({maxWidth:300,'method':'replace'}). ...

A guide on sending multiple input values using the same class name or id through ajax

My goal is to send multiple input values through AJAX to my PHP script. Everything works smoothly when I use getElementById. However, I have the functionality to add a child. The issue arises when it only retrieves values from the first child while iterati ...

Revise Total Amount in Woocommerce Checkout Using an Ajax Call

Before seeking help on SO, I researched extensively to understand how to make an AJAX request with WordPress. Although my code and request are functioning correctly, they are not achieving the desired outcome. My goal is to update the "Total" value when c ...

Exploring AngularJS: Effortlessly Retrieving Object Values

HTML: <div ng-app = "" ng-controller = "personController"> <p>Persoon: <select ng-model="persoon"> <option ng-repeat="person in persons">{{person.FirstName}} {{person.FamilyName}}</option> & ...

Managing User Session Timeout in Ruby on Rails with Devise

My application is utilizing devise for security, with a session timeout set to 30 minutes. Everything works fine when users navigate normally - if they click a link after timing out, they are redirected to the login screen with a message stating "Your sess ...

Troubleshooting 404 Errors When Accessing Wordpress Custom Post Type Posts and Categories

I have recently developed multiple custom post types on a WordPress website. The issue I am facing is that while the links are generated correctly in the form of root/category/id/postname, each link to the full post, pagination or category results in a 404 ...

Encountering difficulties loading a Partial View using a JQuery ActionResult request in ASP.NET Core

I've been struggling with this issue for what seems like forever. Although I can initiate the ActionResult that returns PartialView("MODEL"), I'm having trouble rendering the actual View into the div within the Index cshtml page. Here's wh ...

Postback fails to trigger following JavaScript onchange event

Within my asp.NET application, I have incorporated a control that validates form input data using server-side logic. The concept is simple - drag the control to the desired location, configure it in the code behind, and watch as the form gets validated. ...

Encountering an Error when using Jquery Ajax to call session variables

I have been attempting to retrieve session variables using a Jquery Ajax call, but I keep encountering the "Unexpected token < in JSON" error in the jquery response. Below is my Jquery code - $( document ).ready(function() { $.ajax({ url: "mys ...

What if the targeted URL is unresponsive and not returning any results?

Here is an example of the code I'm using to send a request to a URL at a fixed time interval. $(document).ready(function() { var counter = 1; $.doTimeout( 1000, function() { $.ajax({ type: "GET", url: "<%=e ...

Issue with BlueImp JQuery Upload: File Queue Not Being Cleared Post Upload

I am currently facing two issues that seem to be related. My situation involves using BlueImp's Upload plugin to upload multiple files to an ASP.NET MVC controller, which then returns the necessary JSON response upon completion. The uploading process ...

Refresh the page only when on the initial page of the pagination

I've been utilizing this jQuery code with AJAX for pagination purposes. Currently, I am fetching data from a PHP file that displays limited information. Here is the index file snippet: <script type="text/javascript"> $(document).ready(fun ...

How can I utilize JQuery to dynamically refresh a dropdown menu?

My dropdown list is initially empty: <div> <label>Boarding Point </label> <select title="Select pickup city" id="boardingDropdown"> </select> </div> I am trying to popula ...