正在尝试为单个帖子创建iCal文件

时间:2015-04-04 作者:Brian C

我有一个单独的研讨会活动页面,我正在创建一个“添加到日历”功能。现在我有一个链接设置,它将查询字符串中的当前帖子ID传递给生成iCal文件的PHP文件。我很确定我应该能够从wp\\u查询中生成这样的文件,但我知道我的代码可能错误得离谱。我整天都在做这件事,似乎找不到其他关于这件事的帖子了。任何帮助都将不胜感激。我是wordpress的新手,所以要温柔!

文件如下:

//allow access to the wp_query method:
$parse_uri = explode( \'wp-content\', $_SERVER[\'SCRIPT_FILENAME\'] );
require_once( $parse_uri[0] . \'wp-blog-header.php\' );

//get the post ID from the incoming query string:
$workshop_id = @$_GET[\'workshop_id\'];

$args = array(
\'p\' => $workshop_id,
\'post_type\' => \'any\');

$the_query = new WP_Query($args);

// The Loop
if ( $the_query->have_posts() ) :

while ( $the_query->have_posts() ) :
        $the_query->the_post();

$workshop = array(
    \'workshop_title\' => get_field(\'workshop\');
);

header("Content-Type: text/Calendar");
header("Content-Disposition: inline; filename=calendar.ics");
echo "BEGIN:VCALENDAR\\n";
echo "VERSION:2.0\\n";
echo "PRODID:-//Foobar Corporation//NONSGML Foobar//EN\\n";
echo "METHOD:REQUEST\\n"; // requied by Outlook
echo "BEGIN:VEVENT\\n";
echo "UID:".date(\'Ymd\').\'T\'.date(\'His\')."-".rand()."-example.com\\n"; // required by Outlok
echo "DTSTAMP:".date(\'Ymd\').\'T\'.date(\'His\')."\\n"; // required by Outlook
echo "DTSTART:20080413T000000\\n"; 
//  echo "SUMMARY:{$workshop[\'workshop_title\']}\\n";
echo "DESCRIPTION: this is just a test\\n";
echo "END:VEVENT\\n";
echo "END:VCALENDAR\\n";

endwhile;

endif;

?>

2 个回复
最合适的回答,由SO网友:TheDeadMedic 整理而成

有两件事。首先,不要自己加载WordPress。使用WordPress主页URL,而不是直接链接到插件文件:

<a href="<?php echo home_url( \'?workshop_id=X\' ) ?>">Download iCal</a>
。。。然后拦截请求:

function wpse_183197_send_ical() {
    if ( ! empty( $_GET[\'workshop_id\'] ) && ! is_admin() ) {
         // Your code
         exit;
    }
}

add_action( \'init\', \'wpse_183197_send_ical\' );
至于代码本身,由于您只在一个帖子上操作,我们可以使其更加精简:

if ( ! $id = ( int ) $_GET[\'workshop_id\'] )
    return; // Invalid parameter

if ( ! $post = get_post( $id ) )
    return; // Invalid post

if ( ! $title = get_field( \'workshop\', $post->ID /* You can pass a post ID as a second arg to ACF get_field */ ) )
    return; // No workshop

if ( $post->post_status !== \'publish\' )
    return; // Might want to protect access to drafts and the like

// Calendar headers
echo "SUMMARY:$title\\n";

SO网友:Domain

请检查您是否获得有效值。如果在while循环中设置了标头,则可能会导致一些错误。如果可能,在while循环之后创建日历文件。

“\\n”可能有问题。相反,请尝试按如下方式回显整个字符串,

 $UID = date(\'Ymd\').\'T\'.date(\'His\')."-".rand()."-example.com";
 $date_stamp = date(\'Ymd\').\'T\'.date(\'His\');

 echo "BEGIN:VCALENDAR
 VERSION:2.0
 PRODID:-//Foobar Corporation//NONSGML Foobar//EN
 BEGIN:VEVENT
 UID:{$UID}
 DTSTAMP:{$date_stamp}
 DTSTART:20080413T000000
 DESCRIPTION: this is just a test
 END:VEVENT
 END:VCALENDAR";

结束

相关推荐