Ryan NZ
Ryan NZ

Reputation: 626

Convert a function value into a string?

I have added require_once $_SERVER['DOCUMENT_ROOT'] . 'blog/wp-load.php';

to my website in order to display the latest blog posts to the footer of my custom php built website.

However this has tripled the resources used by my server which is causing issues with my server due to traffic that my website is getting particularly from search engine spiders.

To get around this, I want to include this file to a cronjob file which will insert the last 5 blog posts into a new mysql table (before emptying the table completely) and remove wp-load.php from my website.

However I am having issues with inserting the urls / titles into my mysql table from a function.

$args = array(
'posts_per_page' => 5 // Specify how many posts you'd like to retrieve
);
$latest_posts = new WP_Query( $args );
if ( $latest_posts->have_posts() ) {
    while ( $latest_posts->have_posts() ) {
    $latest_posts->the_post();      

class url {
    public function __toString() {
      the_permalink();
    }
}

$url = strval(new url);

class title {
    public function __toString() {
        echo the_title();
    }
}

$title = strval(new title);

    $stmt = $pdo->prepare("INSERT INTO latestblogposts (`url`, `title`) VALUES (?,?);");
    $stmt->execute([$url, $title]);
    }
}

Here is the contents of the the_permalink(); function

    function the_permalink( $post = 0 ) {
18          /**
19           * Filters the display of the permalink for the current post.
20           *
21           * @since 1.5.0
22           * @since 4.4.0 Added the `$post` parameter.
23           *
24           * @param string      $permalink The permalink for the current post.
25           * @param int|WP_Post $post      Post ID, WP_Post object, or 0. Default 0.
26           */
27          echo esc_url( apply_filters( 'the_permalink', get_permalink( $post ), $post ) );
28  }

How can I convert this to a string so I can insert the contents into mysql?

Upvotes: 0

Views: 90

Answers (1)

Ryan NZ
Ryan NZ

Reputation: 626

I have built an alternative method which will query the wordpress table, exclude all post data aside from actual blog posts and add the slug information to build a complete url.

Posting below for others to use, however still curious if my original question is achievable at all :)

    select post_name, post_title, slug from wp_posts
LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
LEFT JOIN wp_terms ON (wp_term_relationships.term_taxonomy_id = wp_terms.term_id)

where post_status = 'publish' and post_type = 'post' GROUP BY post_name
ORDER BY `post_date`DESC LIMIT 3

As you can see from my new relic logs below, I removed this at around 1.45pm. Removing this file has a big impact on performance. New Relic

Upvotes: 1

Related Questions