[英]My Wordpress plugin does not create page when I upload a file to media library
Hey I wrote a custom plugin for my wordpress site which should create a new page with a download link when I upload a file to media library, but it does not seem to work and I am fairly new to php and wordpress ecosystem so I do not know where the problem lies.嘿,我为我的 wordpress 网站写了一个自定义插件,当我将文件上传到媒体库时,它应该创建一个带有下载链接的新页面,但它似乎不起作用,而且我对 php 和 wordpress 生态系统还很陌生,所以我不知道知道问题出在哪里。
Here is the code that I wrote这是我写的代码
<?php
/**
* Plugin Name: Automatic Download Page Creator
* Plugin URI: https://example.com/automatic-download-page-creator
* Description: Automatically creates a page or post with a download link for a file when it is uploaded to the media library.
* Version: 1.0
* Author: Wisecraft
* Author URI: https://example.com
* License: GPL2
*/
// Hook into the 'wp_insert_attachment' action
add_action( 'wp_insert_attachment', 'create_download_page', 10, 2 );
// Custom function to create the download page or post
function create_download_page( $attachment_id, $attachment ) {
// Get the file URL and post title
$file_url = wp_get_attachment_url( $attachment_id );
$post_title = get_the_title( $attachment_id );
// Create the post content with a download link
$post_content = '<p>Click the link below to download the file:</p>';
$post_content = '<p><a href="' . $file_url . '">Download ' . $post_title . '</a></p>';
// Insert the page or post
$new_post = array(
'post_type' => 'post', // or 'post'
'post_title' => $post_title,
'post_content' => $post_content,
'post_status' => 'publish',
);
$post_id = wp_insert_post( $new_post );
}
?>
I expected my plugin to create a new page with a custom content when I upload a file to Media Library in WordPress, but it does not do anything and I cannot find a problem with the code as well.当我将文件上传到 WordPress 中的媒体库时,我希望我的插件创建一个包含自定义内容的新页面,但它什么也没做,我也找不到代码问题。
This code should work.这段代码应该可以工作。 You used wrong hook.
你用错了钩子。 And if you want add string to existing you need to use.= operator for $post_content.
如果您想将字符串添加到现有内容中,则需要对 $post_content 使用 .= 运算符。 And if you want add Page not Post you need to change post_type in $args array to "page"
如果你想添加页面而不是帖子,你需要将 $args 数组中的 post_type 更改为“page”
add_action( 'add_attachment', 'create_download_page', 10, 1 );
function create_download_page( $attachment_id ) {
// Get the file URL and post title
$file_url = wp_get_attachment_url( $attachment_id );
$post_title = get_the_title( $attachment_id );
// Create the post content with a download link
$post_content = '<p>Click the link below to download the file:</p>';
$post_content .= '<p><a href="' . $file_url . '">Download ' . $post_title . '</a></p>';
// Insert the page or post
$new_post = array(
'post_type' => 'page', // or 'post'
'post_title' => $post_title,
'post_content' => $post_content,
'post_status' => 'publish',
);
$post_id = wp_insert_post( $new_post );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.