0

I'm writing a WP Plugin for one of my sites that hooks into a public API to get app data and save that within Wordpress to allow for WP to be able to search & filter the data based on new parameters created in Wordpress as well as parameters from the API.

When I try and activate the plugin, I get a warning message through the /wp-admin/plugins.php that states

Plugin could not be activated because it triggered a fatal error.

    // Register cb Cron Jobs Activation & Add to Cron Queue
    register_activation_hook(__FILE__, 'cb_cron_jobs_activation');
    add_action('my_hourly_event', 'cb_app_post_type_sync');

    function cb_cron_jobs_activation() {
      wp_schedule_event(time(), 'hourly', 'my_hourly_event' );  
    }

    // Update "app" Custom Post Type with cb App Market API Sync
    function cb_app_post_type_sync() {

      if ( post_type_exists('app') ){



        /* ================================================================
        ** GET & USE MERCHANT PLANS API
        *  ================================================================ */

        // GET API info from MerchantPlans for bundle details for above apps
        $merchantplans_get_response = wp_remote_get( 'https://www.cb.com/v3/merchant_plans?expand=modules' );

        $merchantplans_api_body_response = json_decode( wp_remote_retrieve_body( $merchantplans_get_response ), true );


        // Disect merchant_plans objects
        $merchantplans_elements = $merchantplans_api_body_response['elements'];

        // Generate 3 arrays with module key=>value pairs: classic_bundle, terminal_bundle, register_bundle
        foreach ( $merchantplans_elements as $merchantplans_element ) {

          // Convert merchant bundle name into lowercase joined by underscores for better calling into taxonomies later
          $merchantplan_lowercase = strtolower($merchantplans_element['name']);
          $merchantplan_underscores = str_replace(' ', '_', $merchantplan_lowercase);
          ${$merchantplan_underscores} = array();

          // set variable for each merchant bundle module
          $merchantplans_modules_elements = $merchantplans_element['modules']['elements'];

          // add each marchant bundle module into the array of the associated merchant bundle with the id as the key in the key => value pair
          foreach( $merchantplans_modules_elements as $merchantplans_modules_element ) {
            ${$merchantplan_underscores}[$merchantplans_modules_element['id']] = $merchantplans_modules_element['name'];
          }

        }

        // find the difference between the register_bundle's modules & the terminal_bundle's modules
        $register_unique_modules = array_diff( $register_bundle, $terminal_bundle );
        // This is useful later when we are checking to see which apps belong in which bundles


        /* ================================================================
        ** GET & USE APPMARKET API TO SYNC APP INFO
        *  ================================================================ */

        // GET API info from apps for App Market details
        $appmarket_get_response = wp_remote_get( 'https://www.cb.com/v3/apps?expand=modules%2CavailableMetereds%2CavailableSubscriptions%2CdeviceTypes&filter=approvalStatus%3DPUBLISHED&filter=hidden%3Dfalse' );

        $appmarket_api_body_response = json_decode( wp_remote_retrieve_body( $appmarket_get_response ), true );

        // Unpack the $appmarket_api_body_response array & Build a table to show the data
        $apps_elements = $appmarket_api_body_response['elements'];

        // Run through every app returned in the appmarket API Get request and either update the "app" post type or create a new "app" in WP
        foreach ($apps_elements as $apps_element) {

          // Define the Available Subscription Arrays and Available Metered Arrays
          $available_subscription_elements = $apps_element['availableSubscriptions']['elements'];
          $available_metered_elements = $apps_element['availableMetereds']['elements'];

          // sort Availabe Subscription Arrays & return in lowest to highest amount order
          $subscription_amount_tmp = array();
          foreach( $available_subscription_elements as $key => &$element_row) {
              $subscription_amount_tmp[$key] = &$element_row['subscriptionCountries']['elements'][0]['amount'];
          }
          array_multisort($subscription_amount_tmp, $available_subscription_elements);

          // sort Available Metered Arrays & return in lowest to highest amount order
          $metered_amount_tmp = array();
          foreach( $available_subscription_elements as $key => &$element_row) {
              $metered_amount_tmp[$key] = &$element_row['meteredCountries']['elements'][0]['amount'];
          }
          array_multisort($metered_amount_tmp, $available_subscription_elements);

          // define the apps modules for comparing with the modules in register & terminal bundles to determine which bundle it belongs in
          $third_party_module_elements = $apps_element['modules']['elements'];

          // Count the modules per app and compare with modules in $register_unique_modules array
          // this allows us to determine if the app uses the register plan or the terminal plan
          $module_count = 0;
          foreach ( $third_party_module_elements as $third_party_module_element ) {
            if ( in_array( $third_party_module_element['name'], $register_unique_modules )) {
                $module_count++;
            }
          }
          if ($module_count > 0) {
              $associated_app_plan = 'register-bundle';
          } else {
              $associated_app_plan = 'terminal-bundle';
          }
          /*
          $app_delete_query = array(
            'post_type' => 'app',
            );
          */

          // Query the existing 'app' post type to see if apps exist with the proper app_id.
          $app_update_args = array(
            'post_type' => 'app',
            'name' => 'us-' . $apps_element['id'],
          );
          $app_update_query = new WP_Query( $app_update_args );

          // if the app exists check to see if the following values are the same and if not update them
          if ( $app_update_query->have_posts() ) : 
            while ( $app_update_query->have_posts() ) : $app_update_query->the_post();

              $app_in_wpdb = array(
                'ID'             => get_the_ID();
                'post_title'     => $apps_element['name'],
                'post_content'   => $apps_element['description'],
                'post_name'      => 'us-' . $apps_element['id'],    // The name (slug) for your post
                'post_status'    => 'publish',
                'post_type'      => 'app',
                'post_author'    => 1,
                'menu_order'     => $apps_element['sortOrder'],
                'tax_input'      => array( 'cb_plan' => $associated_app_plan ) // GET API info from apps for App Market details
              );

              wp_insert_post( $app_in_wpdb );

              if (is_wp_error($post_id)) {
                $errors = $post_id->get_error_messages();
                foreach ($errors as $error) {
                  echo $error;
                }
              }

            endwhile;

          // if the app doesn't exist, create the 'app' post, and fill with the following values
          else:

            $new_app_in_wpdb = array(
                'post_title'     => $apps_element['name'],          // The title of your post.
                'post_content'   => $apps_element['description'],   // The full text of the post.
                'post_name'      => 'us-' . $apps_element['id'],    // The name (slug) for your post
                'post_status'    => 'publish',
                'post_type'      => 'app',
                'post_author'    => 1,
                'menu_order'     => $apps_element['sortOrder'],
                'tax_input'      => array( 'cb_plan' => $associated_app_plan ) // GET API info from apps for App Market details
              );
            $post_id = wp_insert_post( $new_app_in_wpdb );

            if (is_wp_error($post_id)) {
                $errors = $post_id->get_error_messages();
                foreach ($errors as $error) {
                  echo $error;
                }
              }
              // add app icon to WP Uploads Directory & then attach as featured image to post
              $image_url  = $apps_element['filenameIconLarge']; // Define the image URL here
              $upload_dir = wp_upload_dir(); // Set upload folder
              $image_data = file_get_contents($image_url); // Get image data
              $filename   = basename($image_url); // Create image file name

              // Check folder permission and define file location
              if( wp_mkdir_p( $upload_dir['path'] ) ) {
                  $file = $upload_dir['path'] . '/' . $filename;
              } else {
                  $file = $upload_dir['basedir'] . '/' . $filename;
              }

              // Create the image  file on the server
              file_put_contents( $file, $image_data );

              // Check image file type
              $wp_filetype = wp_check_filetype( $filename, null );

              // Set attachment data
              $attachment = array(
                  'post_mime_type' => $wp_filetype['type'],
                  'post_title'     => sanitize_file_name( $filename ),
                  'post_content'   => '',
                  'post_status'    => 'inherit'
              );

              // Create the attachment
              $attach_id = wp_insert_attachment( $attachment, $file, $post_id );

              // Include image.php
              require_once(ABSPATH . 'wp-admin/includes/image.php');

              // Define attachment metadata
              $attach_data = wp_generate_attachment_metadata( $attach_id, $file );

              // Assign metadata to attachment
              wp_update_attachment_metadata( $attach_id, $attach_data );

              // And finally assign featured image to post
              set_post_thumbnail( $post_id, $attach_id );

              // update public_app_url
              $public_app_url = 'https://www.cb.com/appmarket/apps/' . $apps_element['id'];
              update_field( 'field_550c63cc17698', $public_app_url, $post_id );

              // update app market ID
              update_field( 'field_55dcf06582888', $apps_element['id'], $post_id);

              if ( !empty($available_subscription_elements) ) {
                // update available subscriptions
                $subscription_field_key = "field_55dd0bbdccfe6";
                $subscription_value = get_field($subscription_field_key, $post_id);

                foreach ( $available_subscription_elements as $available_subscription_element ) {
                  $country_specific_available_subscriptions = $available_subscription_element['subscriptionCountries']['elements'];

                  foreach ( $country_specific_available_subscriptions as $country_specific_available_subscription ) {
                      $subscription_value[] = array('field_55dd0beaccfe7' => $country_specific_available_subscription['id'], 'field_55dd0c1bccfe8' => $country_specific_available_subscription['name'], 'field_55dd0d6fccfe9' => $country_specific_available_subscription['amount']);
                    }
                }
                update_field( $subscription_field_key, $subscription_value, $post_id );
              }

              if (!empty($available_metered_elements)) {
                // update available metered
                $metered_field_key = "field_55e4f6eda039f";
                $metered_value = get_field($metered_field_key, $post_id);

                foreach ( $available_metered_elements as $available_metered_element ) {
                  $country_specific_available_metered_tiers = $available_metered_element['meteredCountries']['elements'];

                  foreach ( $country_specific_available_metered_tiers as $country_specific_available_metered_tier ) {
                      $metered_value[] = array('field_55e4f6eda03a0' => $country_specific_available_metered_tier['id'], 'field_55e4f6eda03a1' => $country_specific_available_metered_tier['action'], 'field_55e4f6eda03a2' => $country_specific_available_metered_tier['amount']);
                    }
                }
                update_field( $metered_field_key, $metered_value, $post_id );
              }

          endif;

          // Reset Post Data
          wp_reset_postdata();
        }

      }

      // delete all 'app' posts that don't have a matching app ID


    }



    register_deactivation_hook(__FILE__, 'cb_cron_jobs_deactivation');

    function cb_cron_jobs_deactivation() {
      wp_clear_scheduled_hook('my_hourly_event');
    }

    ?>
4
  • 4
    Have you enabled WP_DEBUG? Sep 10, 2015 at 17:45
  • Yes. This is in my wp-config file define('WP_DEBUG', true); define('WP_DEBUG_LOG', true); define('WP_DEBUG_DISPLAY', false); @ini_set('display_errors',0); Sep 10, 2015 at 20:00
  • Do you see any errors in your debug.log in the wp-content folder? Sep 10, 2015 at 20:07
  • I have PHP Warnings & PHP Strict Standards, but none are from the 'cb-cron-jobs' plugin folder or file, all are from other plugins Sep 10, 2015 at 20:08

1 Answer 1

0

Disabled all plugins and re-enabled only the necessary ones for this plugin to run correctly (a custom-post-types & custom-taxonomies plugin). Re-activated the plugin and got the error message but with a detail that the line 128 had a semicolon in it. As this was a function being called to get the ID of the element in an array, it should have been followed by a , rather than a ;. Changed this, and activated the plugin successfully.

Moral of the story: Try deactivating plugins that may be interfering with error display & if the error display appears clearly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.