How to insert data into a wordpress table using a custom function

10,896

Solution 1

I suggest you to create any content on wordpress by using WP API. It can be anywhere you want. If you insert data to wp db manually, your system may not work well. For example, when you create a post, it sends an email. If you insert db manually, this does not work. Instead of that, you can use WP API like below;

class WPClient {

    var $xmlRpcUrl = "";
    var $username  = "";
    var $password = "";

    public function __construct($xmlrpcurl, $username, $password) {
        $this->xmlRpcUrl = $xmlrpcurl;
        $this->username  = $username;
        $this->password = $password;
    }

    function sendRequest($requestname, $params) {
        $request = xmlrpc_encode_request($requestname, $params);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
        curl_setopt($ch, CURLOPT_URL, $this->xmlRpcUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 1);
        $results = curl_exec($ch);
        curl_close($ch);
        return $results;
    }

    function createPost($title, $body, $category, $keywords = '', $encoding='UTF-8') {

        $title = htmlentities($title, ENT_NOQUOTES, $encoding);
        $keywords = htmlentities($keywords, ENT_NOQUOTES, $encoding);

        $postData = array(
            'title' => $title,
            'description' => $body,
            'mt_allow_comments' => 0,  // If 1 => allow comments
            'mt_allow_pings' => 0,  // If 1 => allow trackbacks
            'post_type' => 'post',
            'mt_keywords' => $keywords,
            'categories' => array($category)
        );
        $params = array(0, $this->username, $this->password, $postData, true);

        return $this->sendRequest('metaWeblog.newPost', $params);
    }
}

And usage;

$wpClient = new WPClient("http://yourdomain.com/xmlrpc.php", "your_username", "your_password");
$wpClient->createPost("Your title", "Your Content", "Post category", "your tags");

Solution 2

You should be able to use $wpdb.

This article explains how you can access the wordpress database from outside a WordPress build.

http://www.stormyfrog.com/using-wpdb-outside-wordpress/

Then you can use $wpdb to carry out your SQL in a custom function.

<?php 
  global $wpdb;

  $table = 'wp_posts';

  $data  = array(post_title=>$post_title, post_content=>$post_content, post_status=>$post_status, post_type=>$post_type, comment_status=>$comment_status, page_template=>$page_template);

  $wpdb->insert( $table, $data);
?> 

WPDB reference:

https://codex.wordpress.org/Class_Reference/wpdb

Share:
10,896
Mutuma
Author by

Mutuma

Ruby on rails developer and javascript enthusiast Beginner php developer

Updated on June 04, 2022

Comments

  • Mutuma
    Mutuma almost 2 years

    I have a wordpress app hosted on Azure, and I need to insert data into the wp_posts table, using a custom function since I'm running this script as a background job and I cannot use wordpress functions since the script is not on the wordpress folder.

    I've tried:

    mysql_query("INSERT INTO wp_posts(post_title, post_content, post_status, post_type, comment_status, page_template), VALUES($title, $sum, 'publish', 'post', 'closed', 'content.php')");
    

    But I get the following error: PHP Warning: mysql_query(): An attempt was made to access a socket in a way forbidden by its access permissions.

    The log file is as follows:

    [04/07/2014 09:51:47 > adf9f5: SYS INFO] Status changed to Initializing
    [04/07/2014 09:51:47 > adf9f5: SYS INFO] Run script 'data.php' with script host - 'PhpScriptHost'
    [04/07/2014 09:51:47 > adf9f5: SYS INFO] Status changed to Running
    [04/07/2014 09:51:48 > adf9f5: ERR ] PHP Warning:  mysql_query(): An attempt was made to access a socket in a way forbidden by its access permissions.
    [04/07/2014 09:51:48 > adf9f5: ERR ]  in C:\DWASFiles\Sites\abacuskenya\Temp\jobs\triggered\y\rdksuocv.xbx\data.php on line 50
    [04/07/2014 09:51:48 > adf9f5: ERR ] PHP Warning:  mysql_query(): A link to the server could not be established in   C:\DWASFiles\Sites\abacuskenya\Temp\jobs\triggered\y\rdksuocv.xbx\data.php on line 50
    [04/07/2014 09:51:48 > adf9f5: ERR ] PHP Warning:  mysql_insert_id(): An attempt was made to access a socket in a way forbidden by its access permissions.
    

    How do I get my script to insert data into that table using a custom function other than wordpress's wp_insert_post

    My data.php is as follows:

    <?php
    define('DB_NAME', '**********');
    define('DB_USER', '********');
    define('DB_PASSWORD', '**************');
    define('DB_HOST', '*******');
    
    $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
    
    if (!$link){
        die('Could not connect: ' . mysql_error());
    }
    
    $db_selected = mysql_select_db(DB_NAME, $link);
    
    if(!$db_selected){
        die('Cannot use '. DB_NAME . ': ' .mysql_error());
    }
    $pages = array("page0", "page1", "page2", "page3", "page4");
        foreach($pages as $page){
            $json_feed = "http://digitalrand.net/api/url_data/?key=*****&pass=*****%&".$page;
            $json = file_get_contents($json_feed);
            $obj = json_decode($json, true);
                foreach($obj as $article_array){
    
                $url = $article_array['url'];
                $domain = $article_array['domain'];
                $favicon = $article_array['favicon'];
                $title = $article_array['title'];
                $category = $article_array['category'];
                $large_summary = $article_array['summary'];
                $sum = implode(',',$large_summary);
                $images = $article_array['images'];
    
                $image_array = reset($images);
                $image = $image_array["image"];
    
                $sql = "INSERT INTO wp_posts(post_title, post_content, post_status, post_type, comment_status, page_template), VALUES($title, $sum, 'publish', 'post', 'closed', 'content.php')";
                echo $sql;
    
                mysql_query($sql);
    
                $post_id = mysql_insert_id();
                echo "The Post ID is " . $post_id . "<br>";
    
                $data = array($favicon, $domain, $image);
    
                $value = implode(',',$data);
    
    
                //$a = add_post_meta($post_id, 'post_favicon_domain_image', $value, true);
                $sql2 = "INSERT INTO wp_postmeta(post_id, meta_key, meta_value), VALUES($post_id, 'post_favicon_domain_image', $value)";
                mysql_query($sql2);
                //echo $a;
                }
        }
    
  • Mutuma
    Mutuma about 10 years
    The first article requires me to have a path to the wordpress folder of my app but I am hosted on an Azure payment version that does not allow me access to the server so I cannot get the wordpress folder. How would I be able to do this without having to access the wordpress folder?
  • Mutuma
    Mutuma about 10 years
    The data.php file which is the php job script which is totally out of wordpress. So how would I be able to require the class WPClient in it. Note that I'm on an Azure payment version that does not grant me access to the wordpress folder itself so requiring files from the wordpress folder will not work
  • Hüseyin BABAL
    Hüseyin BABAL about 10 years
    You can put above class in a file WpClient.php and include it in your data.php . And instantiate it like in my answer. You do not need to use in wp folder
  • Mutuma
    Mutuma about 10 years
    What I am trying to do is, fetch data from a JSON FEED using a background job, data.php and then insert that data into a wordpress database which I can then display in my wordpress app. Note that in my Azure payment version I am not granted access to control the server since I am not on a vitual box so creation of the wpclient.php is not allowed. I need to be able to do everything on my data.php.
  • Mutuma
    Mutuma about 10 years
    I have included my data.php file in the edit for you to clearly understand what I want to achieve
  • Hüseyin BABAL
    Hüseyin BABAL about 10 years
    How did you put data.php in azure?
  • MÖRK
    MÖRK about 10 years
    If you don't have access to any of the files to be able to add this functionality, your best bet is to use Hüseyin's method.
  • Hüseyin BABAL
    Hüseyin BABAL about 10 years
    You can put that class in data.php also
  • Daniel Garcia Sanchez
    Daniel Garcia Sanchez over 9 years
    Thanks! It helped me :)