2009-12-11 114 views
0

我運行了一些我會聚合到我的主博客中的博文。 我使用simplepie解析來自其他博客的提要,因此帖子正在自動創建。在Wordpress中自動生成自定義字段值

我的典型職位是奠定了這樣的:

  1. IMAGE
  2. 內容/ TEXT
  3. HYPERLINK

什麼我希望做的是自動抓取超鏈接,將其插入到自定義字段中。自定義字段已存在於帖子中,但我需要將帖子內容中包含的超鏈接作爲值插入。

我只需要鏈接,無需HTML,所以價值將只是一個直的鏈 - http://domain.com/fsdds

我知道有一些與圖像完成這個插件,但是我還沒有看到任何可以與其他任何東西一起做的事情,比如超鏈接。

我在Wordpress論壇發佈了這個問題,被告知我必須解析整個帖子內容尋找鏈接,我知道,問題是我不太確定該怎麼做。

感謝

回答

1

安東尼的回答大廈,使用更新後的META一旦你有你的鏈接...

在functions.php文件將這個:

function catch_that_link() { 
     global $post, $posts; 
     $first_link = ''; 
     ob_start(); 
     ob_end_clean(); 
     $output = preg_match_all('/(https?://)?(www.)?([a-zA-Z0-9_%]*)\b.[a-z]{2,4}(.[a-z]{2})?((/[a-zA-Z0-9_%])+)?(.[a-z])?/', $post->post_content, $matches); 
     $first_link = $matches [1] [0]; 

     if(empty($first_link)){ //Defines a default image 
     return 'no link found'; 
     } 
     return $first_link; 
    } 

然後在您的查詢循環,類別文件或任何PHP文件,你會做以下

<?php 

$post_id = 13; //replace the number with the specific post 
$meta_key = 'key_example' //replace with your custom field name 
$meta_value = catch_that_link(); 

update_post_meta($post_id, $meta_key, $meta_value); 
?> 
+0

這樣做,感謝你和安東尼 – rocky 2010-01-29 06:12:51

0

我一直在思考這個我和解決方案必須是在其上運行save_post動作鉤子函數。不幸的是,這是沒有在Wordpress Codex中的文件,我沒有時間去更遠的地方。

1

這是在後抓住了第一個圖像的功能:你只需要更換第一preg_match_all參數

function catch_that_image() { 
     global $post, $posts; 
     $first_img = ''; 
     ob_start(); 
     ob_end_clean(); 
     $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); 
     $first_img = $matches [1] [0]; 

     if(empty($first_img)){ //Defines a default image 
     $first_img = "/images/default.jpg"; 
     } 
     return $first_img; 
    } 

「/(HTTPS://)? (www。)?([a-zA-Z0-9_%] )\ b。[az] {2,4}(。[az] {2})?((/ [a-zA-Z0-9_ %])+)?(。[az] *)?/'

將整個函數添加到您的functions.php中,並從腳本中調用該函數。 它應該返回它在帖子內容中找到的第一個鏈接。