Wordpress продукт данных скребок / API - PullRequest
0 голосов
/ 29 апреля 2018

Я хочу автоматически получать данные о товарах с других веб-сайтов, либо просматривая их, либо получая доступ к API с помощью cURL. Поскольку наш сайт использует Wordpress, я пытаюсь создать плагин. Сейчас я пытаюсь получить поля на странице настроек плагина, чтобы заполнить имя веб-сайта, формат ссылки для cURL и идентификаторы продуктов, которые должны быть импортированы. На странице настроек плагина будет кнопка, которая добавляет те же поля в другой раз при нажатии. Я пытаюсь использовать класс с объектами, так как я хочу использовать несколько веб-сайтов. Я получаю ошибку HTTP 500 на нашем веб-сайте, поэтому я думаю, что что-то не так после части "// ** START Plugin Settings" в моем коде. Было бы здорово, если бы кто-то просмотрел мой код и дал мне толчок в правильном направлении :). Я также довольно новичок в PHP, поэтому, если есть советы о том, как сделать мой код более читабельным или как получить данные о продукте лучше, это было бы здорово!

С уважением, Мартейн

<?php
/**
 * Plugin Name: Dropship Data Scraper
 * Plugin URI: http://example.com/
 * Description: This plugin scrapes data from websites and puts them in product pages
 * Version: 1.0.0
 * Author: Martijn
 * Author URI: https://example.com/
 * License: Proprietary
 */

//**START Adding custom fields to product options Inventory tab**
//Display Fields
add_action( 'woocommerce_product_options_inventory_product_data', 'woo_add_custom_general_fields' );

//Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );

function woo_add_custom_general_fields() {

  global $woocommerce, $post;

  echo '<div class="options_group">';

  //Custom fields will be created here...
    //Purchase Price Field
    woocommerce_wp_text_input( 
        array( 
            'id'                => '_purchase_price', 
            'label'             => __( 'Purchase price', 'woocommerce' ), 
            'placeholder'       => '', 
            'desc_tip'                => 'true',
            'description'       => __( 'Enter the purchase price here.', 'woocommerce' ),
            'type'              => 'number', 
            'custom_attributes' => array(
                    'step'  => 'any',
                    'min'   => '0'
                ) 
        )
    );

    //Product Link Field
    woocommerce_wp_text_input( 
        array( 
            'id'          => '_product_link', 
            'label'       => __( 'Product link', 'woocommerce' ), 
            'placeholder' => 'http://',
            'desc_tip'    => 'true',
            'description' => __( 'Enter the product link from the supplier here.', 'woocommerce' ) 
        )
    );

  echo '</div>';
}

function woo_add_custom_general_fields_save( $post_id ){
    //Purchase Price Field
    $woocommerce_purchase_price = $_POST['_purchase_price'];
    if( !empty( $woocommerce_purchase_price ) )
        update_post_meta( $post_id, '_purchase_price', esc_attr( $woocommerce_purchase_price ) );
  elseif( empty( $woocommerce_purchase_price ) )
        update_post_meta( $post_id, '_purchase_price', NULL );

    //Product Link Field
    $woocommerce_product_link = $_POST['_product_link'];
    if( !empty( $woocommerce_product_link ) )
        update_post_meta( $post_id, '_product_link', esc_attr( $woocommerce_product_link ) );
  elseif( empty( $woocommerce_product_link ) )
        update_post_meta( $post_id, '_product_link', NULL );
}
//**END Adding custom fields to product options Inventory tab**

//**START Plugin Settings Page
//Settings page dropship ids class
class DropshipFields {
  public static $counter = 0;
  private $dropshipIds;

  //Constructor to count how many DropshipFields objects are created
  function __construct() {
     self::$counter++;
  }
  //function to register settings
  public function ff_dropship_data_scraper_settings() {
    $this->dropshipIds = "dropship-ids" . BaseClass::$counter;
    return register_setting( 'ff-dropship-data-scraper-settings-group', $this->dropshipIds );
  }
  //function to display the dropship fields in ff_dropship_data_scraper_settings_page()
  public function displayFields() {

  }
}

//Eventually I want to put here some code that makes a new object everytime a button is pushed on the settings page
$DropshipFields1 = new DropshipFields();

//Add menu item on admin side
  add_action('admin_menu', 'ff_dropship_data_scraper_menu');
  function ff_dropship_data_scraper_menu() {
    add_menu_page('FF Dropship Data Scraper Settings', 'FF Dropship Data Scraper Settings', 'administrator', 'ff-dropship-data-scraper-settings', 'ff_dropship_data_scraper_settings_page', '
dashicons-clipboard');
  }

  add_action( 'admin_init', 'ff_dropship_data_scraper_settings' );
  function ff_dropship_data_scraper_settings() {
    $DropshipFields1->ff_dropship_data_scraper_settings();
  }

  function ff_dropship_data_scraper_settings_page() { ?>
    <div class="wrap">
    <h1>Dropship data</h1>

    <form method="post" action="options.php">
        <?php settings_fields( 'ff-dropship-data-scraper-settings-group' ); ?>
        <?php do_settings_sections( 'ff-dropship-data-scraper-settings-group' ); ?>
        <table class="form-table">
            <tr valign="top">
            <th scope="row">Dropship IDs</th>
            <td><textarea placeholder="Your dropship product ids" name="dropship-ids" rows="5" cols="1000"><?php echo esc_attr( get_option('dropship-ids') ); ?></textarea></td>
            </tr>
        </table>

        <table class="form-table">
            <tr valign="top">
            <th scope="row">Dropship IDs</th>
            <td><textarea placeholder="Your dropship product ids" name="dropship-ids" rows="5" cols="1000"><?php echo esc_attr( get_option('dropship-ids') ); ?></textarea></td>
            </tr>
        </table>

        <?php submit_button(); ?>

    </form>
    </div>
  <?php }
//**END Plugin Settings Page

//**START cURL Scraper
foreach($colors as $value) {
  //Variables
  $url = "https://apibeta.banggood.com/getAccessToken?apiTest=1&apiTest=1app_id=&app_secret=";
  $json;

  //Initialize
  $ch = curl_init();

  //Set options
  //Url to send the request to
  curl_setopt($ch, CURLOPT_URL, $url);

  //Return instead of outputting directly
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  //Include header in the output, set to false
  curl_setopt($ch, CURLOPT_HEADER, 0);

  //Execute the request and fetch the response. Check for errors
  $output = curl_exec($ch);

  if ($output === FALSE) {
    echo 'cURL ERROR: ' . curl_error($ch);
  }

  //Close and free up the cURL handle
  curl_close($ch);

  //decode json
  $json = json_decode($output, true);
}

//**END cURL Scraper

//**START creating, updating or deleting dropship products
//Put dropship-ids in an array
$text = get_option('dropship-ids');
//explode all separate lines into an array
$textAr = explode("\n", $text);
//trim all lines contained in the array.
$textAr = array_filter($textAr, 'trim');

//Update dropship products from dropship-ids
//Array for the last dropship-ids
$last_ids = [];
//Update function
function update_product_data() {
    foreach($textAr as $value) {
     if (in_array($value, $last_ids)) {

    }
    foreach($last_ids as $value) {
      if (in_array($value, $textAr)) {

      }
    }
  }
}
//**END creating, updating or deleting dropship products



?>

1 Ответ

0 голосов
/ 30 апреля 2018

Попробуйте этот код

Я изменил эту строку $DropshipFields1->ff_dropship_data_scraper_settings(); до $DropshipFields1->ff_dropship_data_scraper_settings;

и add_menu_page код

<?php
/**
 * Plugin Name: Dropship Data Scraper
 * Plugin URI: http://example.com/
 * Description: This plugin scrapes data from websites and puts them in product pages
 * Version: 1.0.0
 * Author: Martijn
 * Author URI: https://example.com/
 * License: Proprietary
 */

//**START Adding custom fields to product options Inventory tab**
//Display Fields
add_action( 'woocommerce_product_options_inventory_product_data', 'woo_add_custom_general_fields' );

//Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );

function woo_add_custom_general_fields() {

  global $woocommerce, $post;

  echo '<div class="options_group">';

  //Custom fields will be created here...
    //Purchase Price Field
    woocommerce_wp_text_input( 
        array( 
            'id'                => '_purchase_price', 
            'label'             => __( 'Purchase price', 'woocommerce' ), 
            'placeholder'       => '', 
            'desc_tip'                => 'true',
            'description'       => __( 'Enter the purchase price here.', 'woocommerce' ),
            'type'              => 'number', 
            'custom_attributes' => array(
                    'step'  => 'any',
                    'min'   => '0'
                ) 
        )
    );

    //Product Link Field
    woocommerce_wp_text_input( 
        array( 
            'id'          => '_product_link', 
            'label'       => __( 'Product link', 'woocommerce' ), 
            'placeholder' => 'http://',
            'desc_tip'    => 'true',
            'description' => __( 'Enter the product link from the supplier here.', 'woocommerce' ) 
        )
    );

  echo '</div>';
}

function woo_add_custom_general_fields_save( $post_id ){
    //Purchase Price Field
    $woocommerce_purchase_price = $_POST['_purchase_price'];
    if( !empty( $woocommerce_purchase_price ) )
        update_post_meta( $post_id, '_purchase_price', esc_attr( $woocommerce_purchase_price ) );
  elseif( empty( $woocommerce_purchase_price ) )
        update_post_meta( $post_id, '_purchase_price', NULL );

    //Product Link Field
    $woocommerce_product_link = $_POST['_product_link'];
    if( !empty( $woocommerce_product_link ) )
        update_post_meta( $post_id, '_product_link', esc_attr( $woocommerce_product_link ) );
  elseif( empty( $woocommerce_product_link ) )
        update_post_meta( $post_id, '_product_link', NULL );
}
//**END Adding custom fields to product options Inventory tab**

//**START Plugin Settings Page
//Settings page dropship ids class
class DropshipFields {
  public static $counter = 0;
  private $dropshipIds;

  //Constructor to count how many DropshipFields objects are created
  function __construct() {
     self::$counter++;
  }
  //function to register settings
  public function ff_dropship_data_scraper_settings() {
    $this->dropshipIds = "dropship-ids" . BaseClass::$counter;
    return register_setting( 'ff-dropship-data-scraper-settings-group', $this->dropshipIds );
  }
  //function to display the dropship fields in ff_dropship_data_scraper_settings_page()
  public function displayFields() {

  }
}

//Eventually I want to put here some code that makes a new object everytime a button is pushed on the settings page
$DropshipFields1 = new DropshipFields();

//Add menu item on admin side
  add_action('admin_menu', 'ff_dropship_data_scraper_menu');
  function ff_dropship_data_scraper_menu() {
    add_menu_page('FF Dropship Data Scraper Settings', 'FF Dropship Data Scraper Settings', 'administrator', 'ff-dropship-data-scraper-settings', 'ff_dropship_data_scraper_settings_page' , 'dashicons-clipboard');
  }

  add_action( 'admin_init', 'ff_dropship_data_scraper_settings' );
  function ff_dropship_data_scraper_settings() {
    $DropshipFields1->ff_dropship_data_scraper_settings;
  }

  function ff_dropship_data_scraper_settings_page() { ?>
    <div class="wrap">
    <h1>Dropship data</h1>

    <form method="post" action="options.php">
        <?php settings_fields( 'ff-dropship-data-scraper-settings-group' ); ?>
        <?php do_settings_sections( 'ff-dropship-data-scraper-settings-group' ); ?>
        <table class="form-table">
            <tr valign="top">
            <th scope="row">Dropship IDs</th>
            <td><textarea placeholder="Your dropship product ids" name="dropship-ids" rows="5" cols="1000"><?php echo esc_attr( get_option('dropship-ids') ); ?></textarea></td>
            </tr>
        </table>

        <table class="form-table">
            <tr valign="top">
            <th scope="row">Dropship IDs</th>
            <td><textarea placeholder="Your dropship product ids" name="dropship-ids" rows="5" cols="1000"><?php echo esc_attr( get_option('dropship-ids') ); ?></textarea></td>
            </tr>
        </table>

        <?php submit_button(); ?>

    </form>
    </div>
  <?php }
//**END Plugin Settings Page

//**START cURL Scraper
foreach($colors as $value) {
  //Variables
  $url = "https://apibeta.banggood.com/getAccessToken?apiTest=1&apiTest=1app_id=&app_secret=";
  $json;

  //Initialize
  $ch = curl_init();

  //Set options
  //Url to send the request to
  curl_setopt($ch, CURLOPT_URL, $url);

  //Return instead of outputting directly
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  //Include header in the output, set to false
  curl_setopt($ch, CURLOPT_HEADER, 0);

  //Execute the request and fetch the response. Check for errors
  $output = curl_exec($ch);

  if ($output === FALSE) {
    echo 'cURL ERROR: ' . curl_error($ch);
  }

  //Close and free up the cURL handle
  curl_close($ch);

  //decode json
  $json = json_decode($output, true);
}

//**END cURL Scraper

//**START creating, updating or deleting dropship products
//Put dropship-ids in an array
$text = get_option('dropship-ids');
//explode all separate lines into an array
$textAr = explode("\n", $text);
//trim all lines contained in the array.
$textAr = array_filter($textAr, 'trim');

//Update dropship products from dropship-ids
//Array for the last dropship-ids
$last_ids = [];
//Update function
function update_product_data() {
    foreach($textAr as $value) {
     if (in_array($value, $last_ids)) {

    }
    foreach($last_ids as $value) {
      if (in_array($value, $textAr)) {

      }
    }
  }
}
//**END creating, updating or deleting dropship products



?>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...