Показанное по умолчанию изображение только для типа «POST» (исключая «страницу»)

Здравствуйте, я пытаюсь установить изображение по умолчанию для post_type = пост только исключая post_type = «страница».

Я написал следующий код в файле функций дочерней темы, но я продолжаю получать эту ошибку:

Примечание: попытка получить свойство необъекта в
/home/ossettto/public_html/wp-content/themes/sport-child/functions.php
на линии 18

function wpforce_featured()
{
global $post;
$post_type = get_post_type($post->ID);
if ($post_type === 'post')
{
$already_has_thumb = has_post_thumbnail($post->ID); // If post have a featured image use that.
if (!$already_has_thumb)
{
//If post does not have a featured image then get the first post image and set as featured image.
$attached_image = get_children("post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1"); // Number 1 relates to taking post image number 1 and adding it as a featured image.
if ($attached_image)
{
foreach ($attached_image as $attachment_id => $attachment)
{
set_post_thumbnail($post->ID, $attachment_id);
//$attachment_id = attachment_url_to_postid( $image_url );
//echo $attachment_id;
}
}
else
{
set_post_thumbnail($post->ID, '27264'); // Find attachment media id by right clicking the image in the Media library and selecting inspect element. Look for the data-id number. This number is then added to the post id.
}
}
}
}

//end function
add_action('the_post', 'wpforce_featured');
add_action('save_post', 'wpforce_featured');
add_action('draft_to_publish', 'wpforce_featured');
add_action('new_to_publish', 'wpforce_featured');
add_action('pending_to_publish', 'wpforce_featured');
add_action('future_to_publish', 'wpforce_featured');

Любая помощь будет оценена.
Благодарю.

3

Решение

Неясны две вещи:

  1. Почему вы должны сделать это в the_post, save_postи другие крючки все вместе.
  2. Было бы полезно узнать, какая строка является строкой 18, но я предполагаю, что это строка: $post_type = get_post_type( $post->ID );,

Однако причина, по которой вы получаете уведомление, заключается в том, что эти действия не обязательно имеют $post объект готов для вас global $post, Далее все эти действия имеют разные сигнатуры функций, передавая $post как параметр в разных местах.

Учитывая все фильтры, к которым вы подключаетесь, вам нужно создать «абстракцию» или «обертку» вокруг вашей функции, чтобы вы могли правильно вызывать ее с помощью $post в правильном положении аргументов.

Посмотрите на документы, чтобы увидеть примеры того, где $post проходит:

действие the_post — передается в качестве единственного параметра
действие save_post — передается как второй параметр
draft_to_published (и другие хуки) — передается как ТРЕТИЙ параметр

// New function that accepts proper parameters for save action
function wpforce_featured_on_save( $post_id, $post, $update ) {
// No need to duplicate code.  Instead, call your original function
// passing it the $post parameter
wpforce_featured_status( $post );
}

// New function that accepts proper parameters for these actions
function wpforce_featured_on_status_change( $new, $old, $post ) {
// No need to duplicate code.  Instead, call your original function
// passing it the $post parameter
wpforce_featured( $post );
}

// Your original function with slight modifications
// NOTE: ONLY accepts $post object - no global post
function wpforce_featured( $post ) {
// REMOVED global $post - not helpful here
$post_type = get_post_type( $post->ID );
// ... the rest of your code here
}

// Your original hook, it's passing the $post_object parameter
add_action('the_post', 'wpforce_featured');
// The save hook, which passes parameters - modified to call a different function
add_action('save_post', 'wpforce_featured_save', 10, 3);
// The status change hooks, which pass parameters - modified to call a different function
add_action('draft_to_publish', 'wpforce_featured_on_status_change', 10, 3);
add_action('new_to_publish', 'wpforce_featured_on_status_change', 10, 3);
add_action('pending_to_publish', 'wpforce_featured_on_status_change', 10, 3);
add_action('future_to_publish', 'wpforce_featured_on_status_change', 10, 3);
3

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector