4

I'm developing a little wordpress plugin which creates a custom post type with a custom field where I would like to store an ID of one of the active contribution page of CiviCRM in order to associate this content with the contribution page information.

This very same code works in theme files but fails when is used in plugin files, breaking the site.

   function get_contribution_info($f_type){
   $params = array(
       'version'    =>  3,
        'financial_type_id' => $f_type,
        'is_active' => '1'
    );
    try{
       $result = civicrm_api3('contribution_page', 'get', $params);
    } catch (CiviCRM_API3_Exception $e) {
        // handle error here
        $errorMessage = $e->getMessage();
        $errorCode = $e->getErrorCode();
        $errorData = $e->getExtraParams();
        return array('error' => $errorMessage, 'error_code' => $errorCode, 'error_data' => $errorData);
    }
    return $result[values];
    }

    $get_contrib = get_contribution_data( '1' );
    $contributions = array();
    $i = 0;
    foreach($get_contrib as $c) {
        $contributions[$i]['label'] = $c['title'];
        $contributions[$i]['value'] = $c['id'];
        $i++;
    }

I've tried to add a require_once the class.api.php without positive results.

Thanks in advance for your help!

2 Answers 2

4

Try prefixing your API call with:

civicrm_initialize();

The "class.api.php" is for when you want to use the REST API from an external site.

2
  • 2
    class.api.php works as well locally, but it does implement a class that is a wrapper around civicrm_api3, not that function, so doesn't solve your problem indeed.
    – Xavier
    Commented Jan 14, 2016 at 7:41
  • @bgm Not seems to work in the plugin files. I added civicrm_initialize(); inside the try {} just over the api call and still brakes the site. But works well in themes files... Commented Jan 14, 2016 at 13:30
2

Solved!!!

   function get_contribution_info($f_type){

   $params = array(
       'version'    =>  3,
       'financial_type_id' => $f_type,
       'is_active' => '1'
   );
   try{
       if ( ! function_exists( 'civicrm_initialize' ) ) { return; }
       civicrm_initialize();
       $result = civicrm_api3('contribution_page', 'get', $params);
   } catch (CiviCRM_API3_Exception $e) {
       // handle error here
       $errorMessage = $e->getMessage();
       $errorCode = $e->getErrorCode();
       $errorData = $e->getExtraParams();
       return array('error' => $errorMessage, 'error_code' => $errorCode, 'error_data' => $errorData);
    }
   return $result[values];
}

The key was on adding civicrm_initialize();. Thanks to @bgm for the advice!

Your Answer

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

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