Wordpressなんか必要か?

Wordpressなんか必要か?と思っていたエンジニアのWordpress入門

Findメソッド

定義

public function find ( $params = null, $limit = 15, $where = null, $sql = null )  

パラメータ

|パラメータ|型|説明| ||| |$params|配列or文字列or整数|関連パラメタの配列、アイテムのID、or for advanced content types the item's slug. $limit (int) (optional) (deprecated) Limit the number of items to find, use -1 to return all items with no limit $where (string) (optional) (deprecated) SQL WHERE declaration to use $sql (string) (optional) (deprecated) For advanced use, a custom SQL query to run

Additional Parameter Options

OPTION TYPE DEFAULT DETAILS where (string) $where SQL WHERE to use, ie "t.my_field = 'test'" - This field also supports tableless traversal like "my_relationship_field.id = 3" with unlimited depth orderby (string) null SQL ORDER BY to use, like "t.name DESC" - This field also supports tableless traversal like "my_relationship_field.name DESC" with unlimited depth groupby (string) null SQL GROUP BY, like 't.city'. limit (int) $limit Limit the number of items to find, use -1 to return all items with no limit offset (int) null Override what's calculated automatically based on 'limit' and 'page' search (bool) true Whether to handle search. Defaults to $this->search, which can be globally overridden by defining the constant PODS_GLOBAL_POD_SEARCH to true/false pagination (bool) true Whether to handle pagination. Defaults to $this->pagination, which can be globally overridden by defining the constant PODS_GLOBAL_POD_PAGINATION to true/false page (int) 1 Specify a page of the results to get. Defaults to $this->page, table (string) Default of current pod type Table to base find() off of select (string) t. or t., d.* Fields to select from the database. The "t" prefix will reference the primary table, "d" prefixes are used for the Pod table for any WP Object and the "t" prefix references that WP Object (wp_posts, wp_terms, wp_users, wp_comments) join (string or array) null Additional table(s) to JOIN, using SQL syntax like "LEFT JOIN my_table ON my_table.id = t.id" expires (int) null Whether to cache the results or not, 0 will cache it until caches are cleared, 1+ will cache it for X amount of seconds; Default is no caching (null) cache_mode (string) cache Cache mode to use, available options are cache, transient, or site-transient

Returns

(Pods) The pod object

Examples

Example 1 <?php // Find can be called in one of three ways

// Example #1 $mypod = pods( 'mypod', $params );

// Example #2 $mypod = pods( 'mypod' )->find( $params );

// Example #3 $mypod = pods( 'mypod' ); $mypod->find( $params );

// Here's how to use find() $params = array( 'limit' => 3,
'page' => 2,
// Be sure to sanitize ANY strings going here 'where'=>"category.name = 'My Category'" );

// Run the find $mypod = pods( 'mypod', $params );

// Loop through the records returned while ( $mypod->fetch() ) { echo $mypod->display( 'name' ) . "\n"; } The above example will output: Pod Title 1 Pod Title 2 Pod Title 3 Using a variable in a where clause When the where clause must be created dynamically, a variable can be passed to it like in this example:

<?php // get value from input to a form $keyword = like_escape( pods_v_sanitized( 'keyword', 'post' ) );

// set up find parameters, where meta field title matches $keyword $params = array( 'where' => 't.post_title LIKE "%' . $keyword . '%" OR my_field.meta_value LIKE "%' . $keyword . '%"' );

//search in articles pod $pods = pods( 'articles', $params );

//loop through results if ( 0 < $pods->total() ) { while ( $pods->fetch() ) { echo $pods->display( 'issue' ); } } ?> Additional Information

Traversal notation for field names in the 'where' option

Saveメソッド

save

Save an item by giving an array of field data or set a specific field to a specific value. Though this function has the capacity to add new items, best practice should direct you to use add() for that instead.

Function Definition

public function save ( $data = null, $value = null, $id = null )

Source File: /pods/classes/Pods.php Parameters

PARAMETER TYPE DETAILS $data (array|string) Either an associative array of field information or a field name $value (mixed) (optional) Value of the field, if $data is a field name $id (int) (optional) ID of the pod item to update Returns

(int) The item ID

Examples

Save Multiple Fields At Once <?php // Get the book item with an ID of 5 $pod = pods( 'book', 5 );

// Set the author (a user relationship field) // to a user with an ID of 2 $pod->save( 'author', 2 );

// Set a group of fields to specific values $data = array( 'name' => 'New book name', 'author' => 2, 'description' => 'Awesome book, read worthy!' );

// Save the data as set above $pod->save( $data );

// Let's save another book's data.. // Save the same data from above, // but for the book with an ID of 4 $pod->save( $data, null, 4 ); Add An Image Submitted In A Form You can add an image to a image field using pods::save() by passing the file path or the URL for the image.

IMPORTANT: This example skips data sanitization and validation for the sake of simplicity to explain a concept. Do not use as is, always sanitize data from a form.

<?php //get URL of image from form input $img = $_POST[ 'image' ];

//add image to media library and get its ID $img = pods_attachment_import( $img );

//create array of data to be added //You can add additional fields here if you want $data = array( 'image_field' => $img , ); //get pods object for item of ID $id $pod = pods( 'pod_name', $id ); //update the item and return item id in $item $item = $pod->save( $data);

フォームの作成

form

Embed a form to add / edit a pod item from within your theme. Provide an array of $fields to include and override options where needed. For WP object based Pods, you can pass through the WP object field names too, such as “post_title” or “post_content” for example.

Function Definition

public function form ( $params = null, $label = null, $thank_you = null )

パラメータ

$params (array) (optional) Fields to show on the form, defaults to all fields $label (string) (optional) Save button label, defaults to "Save Changes" $thank_you (string) (optional) Thank you URL to send to upon success

戻り値

(bool|mixed)

Examples

コード例

<?php 
$mypod = pods( 'mypod' ); 

// Output a form with all fields 
echo $mypod->form(); 


// Only show the 'name', 'description', and 'other' fields. 
$fields = array( 'name', 'description', 'other' ); 

// Override the options of a specific field 
$fields = array( 'name', 'description' => array( 'type' => 'paragraph', 'label' => 'Special Label' ), 'other' ); 

//set default value for fields 
$params = array( 'lightsaber_color' => array( 'default' => 'green' ) , array( 'sith_or_jedi'=> array( 'default' => 'jedi' )  )  );
echo $mypod->form( $params ); 

// Output a form with specific fields 
echo $mypod->form( $fields ); 


// Edit an item (shorthand) 
$mypod = pods( 'mypod', $id ); 

// Output an edit form with all fields 
echo $mypod->form(); 


// Edit an item (shorthand) 
echo pods( 'mypod', $id )->form(); 


// Output a form with specific fields, custom label, and thank you URL  
// (with ID passed into it) 
echo $mypod->form( $fields, 'Submit', '/thank-you-for-submitting/?new_id=X_ID_X' );

Output fields only, without submit. This functionality was added in Pods 2.3.19

<?php 
$pods = pods( 'jedi' ); 
$params = array( 'fields_only' => true, 'fields' => array('side_of_force', 'lightsaber_color') ); 
echo $pods->form( $params );

The above example will output: HTML for form fields for 'side_of_force' and 'light_saber_color' without the rest of the HTML for the form or submit.

Podsクラス

podsクラス

Padsクラスをインクルードし、初期化する。

コンストラクタ呼出

function pods ( $type = null, $id = null, $strict = false )  
パラメ-タ 内容
$type (文字列)pod登録名
$id 数値、オブジェクト(オプション)IDまたはスラッグ。
既存の単一レコードを読み込むためのパラメタ。
単一レコードに対するクエリパラメタの配列も可能。
$strict ブール(オプション)trueを指定すると、レコードの存在是非をtrue/falseで返す。
通常の戻り値はPodsオブジェクト
Podsアイテムそのものの存在是非は、静的メソッド pods::exists() を使用

戻り値

ブール値またはPodsオブジェクト(パラメータによる)

プログラム例1

<?php 
// Podsオブジェクトを生成して取得 
$mypod = pods( 'mypod' ); 

// 特定レコードを指定してオブジェクト取得
$mypod = pods( 'mypod', $id_or_slug ); 

// クエリパラメタを作成して取得 
$params = array( 
    'orderby' => 't.name DESC',     
    'limit' => 15, 
    'where' => 't.name != "Buster"' 
    ); 
$mypod = pods( 'mypod', $params ); 

// こういう記法でもOK
$mypod = pods( 'mypod' )->find( $params ); 

// こうやっても同じ
$mypod = pods( 'mypod' ); 
$mypod->find( $params ); 

// 取得値をループして表示 
while ( $mypod->fetch() ) { 
    echo '<p>' . $mypod->display( 'my_field_name' ) . '</p>'; 
} 

// レコードの有無をチェック 
// at http://mysite.com/bunnies/voodoo-rabbit/ 
$slug = pods_var( 1, 'url' ); // get the second level of the current URL 
$pods = pods( 'bunny', $slug ); 

if ( $pods->exists() ) { 
    // This bunny exists! 
} 
else { 
    // This bunny was not found, better send a 404. 
    // This only works if it's ran in a Pod Page Precode 
    // or if you set the $pods global to this before the 
    // theme runs, which is usually right after the 
    // 'after_setup_theme' action. 
    $pods = 404; 
}

Add Default Values To Fields Output a Pods Form for Pod 'fruit' with two fields, 'yellow_fruit' and 'blue_fruit' with the field 'yellow_fruit' pre-populated with the value 'Banana'.

<?php 
//Create pods object 
$pods = pods( 'fruits' ); 
//setup fields array 
$params = array( 
    'yellow_fruit' => array( 
        'default' => 'Banana'  
   ), 
   'orange_fruit' 
); 
echo $pods->form( $params ); 
?>
Use strict mode and pods::exists() to avoid errors if Pod or Pod item do not exist
Illustrates the difference between strict mode, which returns false if the pod does not exist, versus pods::exists()

プログラムによるPodsデータ追加

通常のWordpress Padsフォームからではなく、普通のformや、他のいろいろなプログラムからデータを追加・更新することも可能。
通常のWordpressプラグイン、Advenced Custom Formよりはるかに簡単です。

メソッド

public function add ( $data = null, $value = null )  
パラメータ 内容
$data (配列または文字列) Either an associative array of field information or a field name
$value (mixed) (optional) Value of the field, if $data is a field name

戻り値

(int) The item ID

コード例

<?php 
// pod オブジェクトを取得 
$pod = pods( 'book' ); 

// アイテムを追加するには、まずデータをセットする 
$data = array( 
    'name' => '新しい本', 
    'author' => 2, // リレーションシップ項目のためのユーザID 
    'description' => 'すぐれた著作、読む価値あり!' 
); 

// アイテムを追加して新規IDを取得 
$new_book_id = $pod->add( $data ); 

ちなみに、既存データにアイテムを追加する場合は、

<?php
// 既存IDからpodオブジェクト取得
$pod = pods( 'book', 4 ); 

// ほかのアイテムに影響を与えずデータを変更 
$new_book_id = $pod->add( $data );

実際の処理例

送信フォームから"applicant"レコードを新規に追加する例

<?php 
function add_new_applicant () { 
    // 送信フォームから値を取得 
    $first_name = $_POST['first_name']; 
    $last_name = $_POST['last_name']; 
    $telephone = $_POST['telephone']; 
    $email = $_POST['email']; 
     
    $fields = array( 
        'first_name'    => $first_name, 
        'last_name'        => $last_name, 
        'telephone'        => $telephone, 
        'email'            => $email 
    ); 
                     
    $new_id = pods( 'applicant' )->add( $fields ); 
     
    return $new_id; 
}

Wordpressって何それ、ブログじゃねーか

長いあいだ、ずっとプロのエンジニアやってました。 それも、マイクロソフト系の業務アプリ開発者です。

マイクロソフト系というと、Visual Basicにはじまり、AccessExcelなどのいわゆるOffice系、Microsoft SQL Serverを使ったデータベース開発、ここ15年ほどは、.NETテクノロジ(Visual Basic .NETC#など)を使った開発がメインです。

自分がこの業界を志した頃は、すでにHTML、JavascriptperlphpMySQLなどがあったため、当初はMacintoshを使う、イマドキのような「オープン系」エンジニアだったのですが、当時はじめて世に出た「Microsoft .NETテクノロジ」と、最強の開発環境であった「Microsoft Visual Studio 2002」にあこがれて、思い切り人生の舵をきってしまいました。