qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
351,315 | <p>I am having an issue where an image block in Gutenberg editor is not the full with of the page even though I have selected "Full Width" in the back-end. Is there a way to fix this?</p>
<p>Image for reference:
<a href="https://i.stack.imgur.com/c1WTe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c1WTe.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 351164,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 2,
"selected": false,
"text": "<p>You definitely need to set <code>map_meta_cap</code> to <code>true</code> instead of false to create custom capabilities.</p>\n\n<p>I haven't seen the <code>'capability_type' => ['note','notes']</code> way of creating capabilities before - maybe it's shorthand, but if just changing <code>map_meta_cap</code> doesn't work, you might want to spell everything out the long way:</p>\n\n<pre><code><?php\n$args = array(\n 'labels' => $labels,\n 'public' => false,\n 'show_ui' => true,\n 'show_in_menu' => true,\n 'query_var' => true,\n 'has_archive' => false,\n 'menu_position' => null,\n // The most crucial change: true\n 'map_meta_cap' => true,\n // Possibly required: spelling out every capability individually\n 'capabilities' => array(\n 'edit_post' => 'edit_note',\n 'read_post' => 'read_note',\n 'delete_post' => 'delete_note',\n 'create_posts' => 'create_notes',\n 'delete_posts' => 'delete_notes',\n 'delete_others_posts' => 'delete_others_notes',\n 'delete_private_posts' => 'delete_private_notes',\n 'delete_published_posts' => 'delete_published_notes',\n 'edit_posts' => 'edit_notes',\n 'edit_others_posts' => 'edit_others_notes',\n 'edit_private_posts' => 'edit_private_notes',\n 'edit_published_posts' => 'edit_published_notes',\n 'publish_posts' => 'publish_notes',\n 'read_private_posts' => 'read_private_notes'\n ),\n 'rewrite' => [ 'slug' => 'note', 'with_front' => false ],\n 'supports' => [ 'editor' ],\n 'menu_icon' => 'dashicons-format-aside',\n);\nregister_post_type( 'note', $args );\n?>\n</code></pre>\n\n<p>You may also want to grant your custom role a few other capabilities:</p>\n\n<pre><code><?php\n$role = get_role( 'my_custom_role' );\n// Read (front end) all post types\n$role->add_cap('read');\n// Adjust their dashboard\n$role->add_cap('edit_dashboard');\n// Upload files\n$role->add_cap('upload_files');\n// See the list of users (but not manage them)\n$role->add_cap('list_users');\n// Allow taxonomy management - Categories and custom taxonomies\n$role->add_cap('manage_categories');\n// Use the Customizer\n$role->add_cap('edit_theme_options');\n// Only if you really need to, allow them to paste in HTML/JS\n$role->add_cap('unfiltered_html');\n?>\n</code></pre>\n\n<p>At a minimum I usually grant \"read\" to custom roles so they can see the front end of the site.</p>\n"
},
{
"answer_id": 377082,
"author": "szabo.eva.irma",
"author_id": 196585,
"author_profile": "https://wordpress.stackexchange.com/users/196585",
"pm_score": 0,
"selected": false,
"text": "<p>My problem was the same and here that worked for me:</p>\n<p>Add this line to capabilities:\n$role->add_cap('create_notes');</p>\n<p>And this plugin is very useful to clear custom rules and capabilities when you modify somthing and changes don't apply: <a href=\"https://wordpress.org/plugins/reset-roles-and-capabilities/\" rel=\"nofollow noreferrer\">Reset roles and capabilities</a></p>\n<p>Plus you can try this plugin: <a href=\"https://wordpress.org/plugins/capability-manager-enhanced/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/capability-manager-enhanced/</a></p>\n"
}
] | 2019/10/26 | [
"https://wordpress.stackexchange.com/questions/351315",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/152944/"
] | I am having an issue where an image block in Gutenberg editor is not the full with of the page even though I have selected "Full Width" in the back-end. Is there a way to fix this?
Image for reference:
[](https://i.stack.imgur.com/c1WTe.png) | You definitely need to set `map_meta_cap` to `true` instead of false to create custom capabilities.
I haven't seen the `'capability_type' => ['note','notes']` way of creating capabilities before - maybe it's shorthand, but if just changing `map_meta_cap` doesn't work, you might want to spell everything out the long way:
```
<?php
$args = array(
'labels' => $labels,
'public' => false,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'has_archive' => false,
'menu_position' => null,
// The most crucial change: true
'map_meta_cap' => true,
// Possibly required: spelling out every capability individually
'capabilities' => array(
'edit_post' => 'edit_note',
'read_post' => 'read_note',
'delete_post' => 'delete_note',
'create_posts' => 'create_notes',
'delete_posts' => 'delete_notes',
'delete_others_posts' => 'delete_others_notes',
'delete_private_posts' => 'delete_private_notes',
'delete_published_posts' => 'delete_published_notes',
'edit_posts' => 'edit_notes',
'edit_others_posts' => 'edit_others_notes',
'edit_private_posts' => 'edit_private_notes',
'edit_published_posts' => 'edit_published_notes',
'publish_posts' => 'publish_notes',
'read_private_posts' => 'read_private_notes'
),
'rewrite' => [ 'slug' => 'note', 'with_front' => false ],
'supports' => [ 'editor' ],
'menu_icon' => 'dashicons-format-aside',
);
register_post_type( 'note', $args );
?>
```
You may also want to grant your custom role a few other capabilities:
```
<?php
$role = get_role( 'my_custom_role' );
// Read (front end) all post types
$role->add_cap('read');
// Adjust their dashboard
$role->add_cap('edit_dashboard');
// Upload files
$role->add_cap('upload_files');
// See the list of users (but not manage them)
$role->add_cap('list_users');
// Allow taxonomy management - Categories and custom taxonomies
$role->add_cap('manage_categories');
// Use the Customizer
$role->add_cap('edit_theme_options');
// Only if you really need to, allow them to paste in HTML/JS
$role->add_cap('unfiltered_html');
?>
```
At a minimum I usually grant "read" to custom roles so they can see the front end of the site. |
351,334 | <p>I have used this method to create a custom post page but I want the content to be the imported XML file content to be the content of this file.
<a href="https://stackoverflow.com/a/32314726/3697484">https://stackoverflow.com/a/32314726/3697484</a></p>
<p>I have the XML content as a file saved inside a plugin folder.</p>
<p>I am basically looking for a method to use the WordPress importer function inside an admin options page to automate the process.
- User clicks on the link in the admin options page
= It imports the XML page with it it's content. </p>
<p>I have no idea if there is a function or API to get it done.
please help</p>
<p>No category, no tags or the custom fields are being imported.</p>
<p><hr>
// I am actually trying a method to import the json output from elementor / xml output of elementor page from wordpress exporter</p>
<p>This is where elementor converts json to a page : <a href="https://github.com/elementor/elementor/blob/master/includes/template-library/sources/local.php" rel="nofollow noreferrer">https://github.com/elementor/elementor/blob/master/includes/template-library/sources/local.php</a> - line 895</p>
<pre><code>public function admin_import_template_form() {
if ( ! self::is_base_templates_screen() ) {
return;
}
/** @var \Elementor\Core\Common\Modules\Ajax\Module $ajax */
$ajax = Plugin::$instance->common->get_component( 'ajax' );
?>
<div id="elementor-hidden-area">
<a id="elementor-import-template-trigger" class="page-title-action"><?php echo __( 'Import Templates', 'elementor' ); ?></a>
<div id="elementor-import-template-area">
<div id="elementor-import-template-title"><?php echo __( 'Choose an Elementor template JSON file or a .zip archive of Elementor templates, and add them to the list of templates available in your library.', 'elementor' ); ?></div>
<form id="elementor-import-template-form" method="post" action="<?php echo admin_url( 'admin-ajax.php' ); ?>" enctype="multipart/form-data">
<input type="hidden" name="action" value="elementor_library_direct_actions">
<input type="hidden" name="library_action" value="direct_import_template">
<input type="hidden" name="_nonce" value="<?php echo $ajax->create_nonce(); ?>">
<fieldset id="elementor-import-template-form-inputs">
<input type="file" name="file" accept=".json,application/json,.zip,application/octet-stream,application/zip,application/x-zip,application/x-zip-compressed" required>
<input type="submit" class="button" value="<?php echo esc_attr__( 'Import Now', 'elementor' ); ?>">
</fieldset>
</form>
</div>
</div>
<?php
}
</code></pre>
<p>Another method : </p>
<pre><code> private function import_single_template( $file_name ) {
$data = json_decode( file_get_contents( $file_name ), true );
if ( empty( $data ) ) {
return new \WP_Error( 'file_error', 'Invalid File' );
}
$content = $data['content'];
if ( ! is_array( $content ) ) {
return new \WP_Error( 'file_error', 'Invalid File' );
}
$content = $this->process_export_import_content( $content, 'on_import' );
$page_settings = [];
if ( ! empty( $data['page_settings'] ) ) {
$page = new Model( [
'id' => 0,
'settings' => $data['page_settings'],
] );
$page_settings_data = $this->process_element_export_import_content( $page, 'on_import' );
if ( ! empty( $page_settings_data['settings'] ) ) {
$page_settings = $page_settings_data['settings'];
}
}
$template_id = $this->save_item( [
'content' => $content,
'title' => $data['title'],
'type' => $data['type'],
'page_settings' => $page_settings,
] );
if ( is_wp_error( $template_id ) ) {
return $template_id;
}
return $this->get_item( $template_id );
}
Not sure if they use this:
public function import_template( $name, $path ) {
if ( empty( $path ) ) {
return new \WP_Error( 'file_error', 'Please upload a file to import' );
}
$items = [];
$file_extension = pathinfo( $name, PATHINFO_EXTENSION );
if ( 'zip' === $file_extension ) {
if ( ! class_exists( '\ZipArchive' ) ) {
return new \WP_Error( 'zip_error', 'PHP Zip extension not loaded' );
}
$zip = new \ZipArchive();
$wp_upload_dir = wp_upload_dir();
$temp_path = $wp_upload_dir['basedir'] . '/' . self::TEMP_FILES_DIR . '/' . uniqid();
$zip->open( $path );
$valid_entries = [];
// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
for ( $i = 0; $i < $zip->numFiles; $i++ ) {
$zipped_file_name = $zip->getNameIndex( $i );
$zipped_extension = pathinfo( $zipped_file_name, PATHINFO_EXTENSION );
if ( 'json' === $zipped_extension ) {
$valid_entries[] = $zipped_file_name;
}
}
if ( ! empty( $valid_entries ) ) {
$zip->extractTo( $temp_path, $valid_entries );
}
$zip->close();
$file_names = array_diff( scandir( $temp_path ), [ '.', '..' ] );
foreach ( $file_names as $file_name ) {
$full_file_name = $temp_path . '/' . $file_name;
$import_result = $this->import_single_template( $full_file_name );
unlink( $full_file_name );
if ( is_wp_error( $import_result ) ) {
return $import_result;
}
$items[] = $import_result;
}
rmdir( $temp_path );
} else {
$import_result = $this->import_single_template( $path );
if ( is_wp_error( $import_result ) ) {
return $import_result;
}
$items[] = $import_result;
}
return $items;
}
</code></pre>
<p>Any possibility of replicating this process? </p>
<p>Json Export : </p>
<pre><code> {
"version":"0.4",
"title":"Export Template",
"type":"page",
"content":[
{
"id":"1f161830",
"settings":{
"content_width":{
"unit":"px",
"size":"980"
},
"custom_height":{
"unit":"px",
"size":"120"
},
"content_position":"middle",
"structure":"20",
"background_background":"classic",
"background_color":"#003e53",
"padding":{
"unit":"px",
"top":"0",
"right":"0",
"bottom":"30",
"left":"0",
"isLinked":false
},
"padding_tablet":{
"unit":"px",
"top":"0",
"right":"20",
"bottom":"0",
"left":"20",
"isLinked":false
},
"padding_mobile":{
"unit":"px",
"top":"30",
"right":"30",
"bottom":"30",
"left":"30",
"isLinked":true
}
},
"elements":[
{
"id":"4c55a461",
"settings":{
"_column_size":50,
"_inline_size":"64.388",
"padding":{
"unit":"px",
"top":"0",
"right":"0",
"bottom":"0",
"left":"0",
"isLinked":false
}
},
"elements":[
{
"id":"7c41176b",
"settings":{
"title":"Your Dream Vacation is Here",
"header_size":"h3",
"align_mobile":"center",
"title_color":"#ffffff",
"typography_typography":"custom",
"typography_font_size":{
"unit":"px",
"size":36
},
"typography_font_size_mobile":{
"unit":"px",
"size":32
},
"typography_font_family":"Roboto",
"typography_font_weight":"300"
},
"elements":[
],
"isInner":false,
"widgetType":"heading",
"elType":"widget"
}
],
"isInner":false,
"elType":"column"
},
{
"id":"528d240a",
"settings":{
"_column_size":50,
"_inline_size":"35.613"
},
"elements":[
{
"id":"79cddb6",
"settings":{
"text":"Book A Room",
"align":"right",
"align_mobile":"center",
"size":"lg",
"icon":"fa fa-angle-double-right",
"icon_align":"right",
"typography_typography":"custom",
"typography_font_size_tablet":{
"unit":"px",
"size":"15"
},
"typography_font_family":"Playfair Display",
"background_color":"#e4bc36",
"button_background_hover_color":"#8daca6",
"border_radius":{
"unit":"px",
"top":"0",
"right":"0",
"bottom":"0",
"left":"0",
"isLinked":true
}
},
"elements":[
],
"isInner":false,
"widgetType":"button",
"elType":"widget"
}
],
"isInner":false,
"elType":"column"
}
],
"isInner":false,
"elType":"section"
},
{
"id":"8ffa3fa",
"settings":{
"content_width":{
"unit":"px",
"size":"980"
},
"content_position":"middle",
"structure":"20",
"padding":{
"unit":"px",
"top":"80",
"right":"0",
"bottom":"0",
"left":"0",
"isLinked":false
},
"padding_tablet":{
"unit":"px",
"top":"60",
"right":"30",
"bottom":"30",
"left":"30",
"isLinked":false
},
"reverse_order_mobile":"reverse-mobile"
},
"elements":[
{
"id":"a721fd6",
"settings":{
"_column_size":50,
"_inline_size":null,
"padding":{
"unit":"px",
"top":"0",
"right":"60",
"bottom":"0",
"left":"0",
"isLinked":false
},
"padding_mobile":{
"unit":"px",
"top":"0",
"right":"0",
"bottom":"0",
"left":"0",
"isLinked":false
}
},
"elements":[
{
"id":"452fa18b",
"settings":{
"title":"Enjoy Some You-Time",
"header_size":"h3",
"align_mobile":"center",
"title_color":"#8daca6",
"typography_typography":"custom",
"typography_font_size":{
"unit":"px",
"size":36
},
"typography_font_family":"Playfair Display",
"typography_font_weight":"normal"
},
"elements":[
],
"isInner":false,
"widgetType":"heading",
"elType":"widget"
},
{
"id":"3c932056",
"settings":{
"editor":"<p>I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.<\/p>",
"align_mobile":"center",
"typography_typography":"custom",
"typography_font_family":"Roboto"
},
"elements":[
],
"isInner":false,
"widgetType":"text-editor",
"elType":"widget"
},
{
"id":"2ae50433",
"settings":{
"text":"Read More",
"align":"left",
"align_mobile":"center",
"size":"md",
"icon":"fa fa-angle-double-right",
"icon_align":"right",
"typography_typography":"custom",
"typography_font_family":"Playfair Display",
"background_color":"#e4bc36",
"button_background_hover_color":"#8daca6",
"border_radius":{
"unit":"px",
"top":"0",
"right":"0",
"bottom":"0",
"left":"0",
"isLinked":true
}
},
"elements":[
],
"isInner":false,
"widgetType":"button",
"elType":"widget"
}
],
"isInner":false,
"elType":"column"
},
{
"id":"169d14c2",
"settings":{
"_column_size":50,
"_inline_size":null
},
"elements":[
{
"id":"41d9ad60",
"settings":{
"image":{
"id":591,
"url":"http:\/\/demo.geekygreenowl.com\/wp-content\/uploads\/2019\/11\/main2.jpg"
},
"image_size":"full",
"image_border_border":"solid",
"image_border_width":{
"unit":"px",
"top":"10",
"right":"10",
"bottom":"10",
"left":"10",
"isLinked":true
},
"image_border_color":"#ffffff",
"image_box_shadow_box_shadow_type":"yes",
"image_box_shadow_box_shadow":{
"horizontal":"10",
"vertical":"10",
"blur":"20",
"spread":0,
"inset":"",
"color":"rgba(0,0,0,0.12)"
},
"_padding_mobile":{
"unit":"px",
"top":"0",
"right":"0",
"bottom":"30",
"left":"0",
"isLinked":false
}
},
"elements":[
],
"isInner":false,
"widgetType":"image",
"elType":"widget"
}
],
"isInner":false,
"elType":"column"
}
],
"isInner":false,
"elType":"section"
}
]
}
</code></pre>
| [
{
"answer_id": 351926,
"author": "Cas Dekkers",
"author_id": 153884,
"author_profile": "https://wordpress.stackexchange.com/users/153884",
"pm_score": 1,
"selected": false,
"text": "<p>So if I understand your question correctly, you have an XML file, and you would like to import it and save the content to a post?</p>\n\n<p>You can do this with a plugin, for example, <a href=\"https://wordpress.org/plugins/wp-all-import/\" rel=\"nofollow noreferrer\">this one</a>, but if you're not too keen on third-party plugins, you could try parsing the XML yourself with PHP's SimpleXML parser. Here's an example from <a href=\"https://www.w3schools.com/php/php_xml_simplexml_read.asp\" rel=\"nofollow noreferrer\">w3schools.com</a>. With it, you can turn your XML data into PHP objects. To my knowledge, there exists no built-in WP API that you can use for this purpose.</p>\n\n<p>Does this answer your question?</p>\n"
},
{
"answer_id": 352175,
"author": "Cas Dekkers",
"author_id": 153884,
"author_profile": "https://wordpress.stackexchange.com/users/153884",
"pm_score": 1,
"selected": true,
"text": "<p>So, are you looking for a JSON importer for Elementor? If so, why not use their native importer? See here:</p>\n\n<p><a href=\"https://i.stack.imgur.com/cefCh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cefCh.png\" alt=\"Native Elementor Importer\"></a></p>\n\n<p>However, if you would rather have an option in a menu, try this small plugin. It adds an importer under <code>Tools > Import</code>, called Elementor JSON Importer, that you can use to import JSON files (it technically also handles .zip files). With it, you can upload a JSON file and it generates an Elementor template from it. It saves the uploaded files in the <code>wp-content/uploads</code> folder.</p>\n\n<pre><code><?php\n/**\n * Elementor JSON Importer\n *\n * Plugin Name: Elementor Importer\n * Plugin URI: https://example.com\n * Description: Imports local JSON data and creates an Elementor post.\n * Version: 0.1.0\n * Author: Your Name Here\n * Author URI: https://example.com\n * Text Domain: elementor-json-importer\n */\n\nif ( ! defined( 'WP_LOAD_IMPORTERS' ) )\n return;\n\n// Load Importer API\nrequire_once ABSPATH . 'wp-admin/includes/import.php';\n\n// Require Elementor API\nrequire_once plugin_dir_path( __DIR__ ) . 'elementor/includes/template-library/sources/base.php';\nrequire_once plugin_dir_path( __DIR__ ) . 'elementor/includes/template-library/sources/local.php';\n\n// Make sure the importer class exists and is available.\nif ( ! class_exists( 'WP_Importer' ) ) {\n $class_wp_importer = ABSPATH . 'wp-admin/includes/class-wp-importer.php';\n if ( file_exists( $class_wp_importer ) ) {\n require_once $class_wp_importer;\n }\n}\n\n/**\n * Elementor JSON Importer\n *\n * Will process JSON data for importing Elementor posts into WordPress.\n *\n * @since 0.1.0\n */\nif ( class_exists( 'WP_Importer' ) ) {\n\n class Elementor_JSON_Importer extends WP_Importer {\n\n // Constructor\n public function __construct() {\n // Nothing.\n }\n\n // Executes on import dispatch.\n public function dispatch() {\n if ( empty( $_GET['step'] ) ) {\n $step = 0;\n } else {\n $step = (int) $_GET['step'];\n }\n\n $this->header();\n\n switch ($step) {\n case 0:\n $this->greet();\n break;\n case 1:\n check_admin_referer( 'import-upload' );\n $result = $this->import();\n if ( is_wp_error( $result ) ) {\n echo $result->get_error_message();\n }\n break;\n }\n\n $this->footer();\n }\n\n // Echoes page footer.\n protected function footer() {\n echo '</div>';\n }\n\n // Echoes greeting.\n protected function greet() {\n echo '<div class=\"narrow\">';\n echo '<p>'.__( 'This importer allows you to extract posts from an Elementor JSON file into your WordPress site. Pick a JSON file to upload and click Import.', 'elementor-json-importer' ).'</p>';\n wp_import_upload_form( 'admin.php?import=elementor-json&amp;step=1' );\n echo '</div>';\n }\n\n // Echoes page header.\n protected function header() {\n echo '<div class=\"wrap\">';\n screen_icon();\n echo '<h2>'.__( 'Import JSON', 'elementor-json-importer-importer' ).'</h2>';\n }\n\n // Performs the actual import by using methods of the Elementor API.\n protected function import() {\n $error = new WP_Error();\n $file = wp_import_handle_upload();\n\n if ( isset( $file['error'] ) ) {\n $error->add( 'upload-error', $file['error'] );\n return $error;\n }\n\n $source_local = new Elementor\\TemplateLibrary\\Source_Local();\n if ( ! method_exists( $source_local, 'import_template' ) ) {\n $error->add( 'elementor-api-error', __( 'Elementor API unavailable.', 'elementor-json-importer' ) );\n return $error;\n }\n\n try {\n $result = $source_local->import_template( basename( $file['file'] ), $file['file'] );\n } catch ( Exception $e ) {\n $error->add( 'elementor-import-error', __( 'Elementor import has failed.', 'elementor-json-importer' ) );\n return $error;\n } finally {\n wp_import_cleanup( $file['id'] );\n }\n\n echo '<h3>';\n printf( __( 'All done. <a href=\"%s\">View template</a>', 'rss-importer' ), esc_url( $result[0]['url'] ) );\n echo '</h3>';\n }\n }\n\n // Create a new instance of the importer class.\n $elementor_json_importer = new Elementor_JSON_Importer();\n\n // Attempt to register importer.\n $error = register_importer(\n 'elementor-json',\n __( 'Elementor JSON Importer', 'elementor-json-importer' ),\n __( 'Import posts from an Elementor JSON file.', 'elementor-json-importer' ),\n array ( $elementor_json_importer, 'dispatch' )\n );\n\n if ( is_wp_error( $error ) ) {\n error_log( $error->get_error_message() );\n } \n\n} // class_exists( 'WP_Importer' )\n\nfunction elementor_json_importer_init() {\n load_plugin_textdomain( 'elementor-json-importer', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );\n}\nadd_action( 'init', 'elementor_json_importer_init' );\n</code></pre>\n\n<p>It depends heavily on the Elementor plugin, though, so make sure to check if it works each time the Elementor plugin receives an update.</p>\n"
}
] | 2019/10/27 | [
"https://wordpress.stackexchange.com/questions/351334",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | I have used this method to create a custom post page but I want the content to be the imported XML file content to be the content of this file.
<https://stackoverflow.com/a/32314726/3697484>
I have the XML content as a file saved inside a plugin folder.
I am basically looking for a method to use the WordPress importer function inside an admin options page to automate the process.
- User clicks on the link in the admin options page
= It imports the XML page with it it's content.
I have no idea if there is a function or API to get it done.
please help
No category, no tags or the custom fields are being imported.
---
// I am actually trying a method to import the json output from elementor / xml output of elementor page from wordpress exporter
This is where elementor converts json to a page : <https://github.com/elementor/elementor/blob/master/includes/template-library/sources/local.php> - line 895
```
public function admin_import_template_form() {
if ( ! self::is_base_templates_screen() ) {
return;
}
/** @var \Elementor\Core\Common\Modules\Ajax\Module $ajax */
$ajax = Plugin::$instance->common->get_component( 'ajax' );
?>
<div id="elementor-hidden-area">
<a id="elementor-import-template-trigger" class="page-title-action"><?php echo __( 'Import Templates', 'elementor' ); ?></a>
<div id="elementor-import-template-area">
<div id="elementor-import-template-title"><?php echo __( 'Choose an Elementor template JSON file or a .zip archive of Elementor templates, and add them to the list of templates available in your library.', 'elementor' ); ?></div>
<form id="elementor-import-template-form" method="post" action="<?php echo admin_url( 'admin-ajax.php' ); ?>" enctype="multipart/form-data">
<input type="hidden" name="action" value="elementor_library_direct_actions">
<input type="hidden" name="library_action" value="direct_import_template">
<input type="hidden" name="_nonce" value="<?php echo $ajax->create_nonce(); ?>">
<fieldset id="elementor-import-template-form-inputs">
<input type="file" name="file" accept=".json,application/json,.zip,application/octet-stream,application/zip,application/x-zip,application/x-zip-compressed" required>
<input type="submit" class="button" value="<?php echo esc_attr__( 'Import Now', 'elementor' ); ?>">
</fieldset>
</form>
</div>
</div>
<?php
}
```
Another method :
```
private function import_single_template( $file_name ) {
$data = json_decode( file_get_contents( $file_name ), true );
if ( empty( $data ) ) {
return new \WP_Error( 'file_error', 'Invalid File' );
}
$content = $data['content'];
if ( ! is_array( $content ) ) {
return new \WP_Error( 'file_error', 'Invalid File' );
}
$content = $this->process_export_import_content( $content, 'on_import' );
$page_settings = [];
if ( ! empty( $data['page_settings'] ) ) {
$page = new Model( [
'id' => 0,
'settings' => $data['page_settings'],
] );
$page_settings_data = $this->process_element_export_import_content( $page, 'on_import' );
if ( ! empty( $page_settings_data['settings'] ) ) {
$page_settings = $page_settings_data['settings'];
}
}
$template_id = $this->save_item( [
'content' => $content,
'title' => $data['title'],
'type' => $data['type'],
'page_settings' => $page_settings,
] );
if ( is_wp_error( $template_id ) ) {
return $template_id;
}
return $this->get_item( $template_id );
}
Not sure if they use this:
public function import_template( $name, $path ) {
if ( empty( $path ) ) {
return new \WP_Error( 'file_error', 'Please upload a file to import' );
}
$items = [];
$file_extension = pathinfo( $name, PATHINFO_EXTENSION );
if ( 'zip' === $file_extension ) {
if ( ! class_exists( '\ZipArchive' ) ) {
return new \WP_Error( 'zip_error', 'PHP Zip extension not loaded' );
}
$zip = new \ZipArchive();
$wp_upload_dir = wp_upload_dir();
$temp_path = $wp_upload_dir['basedir'] . '/' . self::TEMP_FILES_DIR . '/' . uniqid();
$zip->open( $path );
$valid_entries = [];
// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
for ( $i = 0; $i < $zip->numFiles; $i++ ) {
$zipped_file_name = $zip->getNameIndex( $i );
$zipped_extension = pathinfo( $zipped_file_name, PATHINFO_EXTENSION );
if ( 'json' === $zipped_extension ) {
$valid_entries[] = $zipped_file_name;
}
}
if ( ! empty( $valid_entries ) ) {
$zip->extractTo( $temp_path, $valid_entries );
}
$zip->close();
$file_names = array_diff( scandir( $temp_path ), [ '.', '..' ] );
foreach ( $file_names as $file_name ) {
$full_file_name = $temp_path . '/' . $file_name;
$import_result = $this->import_single_template( $full_file_name );
unlink( $full_file_name );
if ( is_wp_error( $import_result ) ) {
return $import_result;
}
$items[] = $import_result;
}
rmdir( $temp_path );
} else {
$import_result = $this->import_single_template( $path );
if ( is_wp_error( $import_result ) ) {
return $import_result;
}
$items[] = $import_result;
}
return $items;
}
```
Any possibility of replicating this process?
Json Export :
```
{
"version":"0.4",
"title":"Export Template",
"type":"page",
"content":[
{
"id":"1f161830",
"settings":{
"content_width":{
"unit":"px",
"size":"980"
},
"custom_height":{
"unit":"px",
"size":"120"
},
"content_position":"middle",
"structure":"20",
"background_background":"classic",
"background_color":"#003e53",
"padding":{
"unit":"px",
"top":"0",
"right":"0",
"bottom":"30",
"left":"0",
"isLinked":false
},
"padding_tablet":{
"unit":"px",
"top":"0",
"right":"20",
"bottom":"0",
"left":"20",
"isLinked":false
},
"padding_mobile":{
"unit":"px",
"top":"30",
"right":"30",
"bottom":"30",
"left":"30",
"isLinked":true
}
},
"elements":[
{
"id":"4c55a461",
"settings":{
"_column_size":50,
"_inline_size":"64.388",
"padding":{
"unit":"px",
"top":"0",
"right":"0",
"bottom":"0",
"left":"0",
"isLinked":false
}
},
"elements":[
{
"id":"7c41176b",
"settings":{
"title":"Your Dream Vacation is Here",
"header_size":"h3",
"align_mobile":"center",
"title_color":"#ffffff",
"typography_typography":"custom",
"typography_font_size":{
"unit":"px",
"size":36
},
"typography_font_size_mobile":{
"unit":"px",
"size":32
},
"typography_font_family":"Roboto",
"typography_font_weight":"300"
},
"elements":[
],
"isInner":false,
"widgetType":"heading",
"elType":"widget"
}
],
"isInner":false,
"elType":"column"
},
{
"id":"528d240a",
"settings":{
"_column_size":50,
"_inline_size":"35.613"
},
"elements":[
{
"id":"79cddb6",
"settings":{
"text":"Book A Room",
"align":"right",
"align_mobile":"center",
"size":"lg",
"icon":"fa fa-angle-double-right",
"icon_align":"right",
"typography_typography":"custom",
"typography_font_size_tablet":{
"unit":"px",
"size":"15"
},
"typography_font_family":"Playfair Display",
"background_color":"#e4bc36",
"button_background_hover_color":"#8daca6",
"border_radius":{
"unit":"px",
"top":"0",
"right":"0",
"bottom":"0",
"left":"0",
"isLinked":true
}
},
"elements":[
],
"isInner":false,
"widgetType":"button",
"elType":"widget"
}
],
"isInner":false,
"elType":"column"
}
],
"isInner":false,
"elType":"section"
},
{
"id":"8ffa3fa",
"settings":{
"content_width":{
"unit":"px",
"size":"980"
},
"content_position":"middle",
"structure":"20",
"padding":{
"unit":"px",
"top":"80",
"right":"0",
"bottom":"0",
"left":"0",
"isLinked":false
},
"padding_tablet":{
"unit":"px",
"top":"60",
"right":"30",
"bottom":"30",
"left":"30",
"isLinked":false
},
"reverse_order_mobile":"reverse-mobile"
},
"elements":[
{
"id":"a721fd6",
"settings":{
"_column_size":50,
"_inline_size":null,
"padding":{
"unit":"px",
"top":"0",
"right":"60",
"bottom":"0",
"left":"0",
"isLinked":false
},
"padding_mobile":{
"unit":"px",
"top":"0",
"right":"0",
"bottom":"0",
"left":"0",
"isLinked":false
}
},
"elements":[
{
"id":"452fa18b",
"settings":{
"title":"Enjoy Some You-Time",
"header_size":"h3",
"align_mobile":"center",
"title_color":"#8daca6",
"typography_typography":"custom",
"typography_font_size":{
"unit":"px",
"size":36
},
"typography_font_family":"Playfair Display",
"typography_font_weight":"normal"
},
"elements":[
],
"isInner":false,
"widgetType":"heading",
"elType":"widget"
},
{
"id":"3c932056",
"settings":{
"editor":"<p>I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.<\/p>",
"align_mobile":"center",
"typography_typography":"custom",
"typography_font_family":"Roboto"
},
"elements":[
],
"isInner":false,
"widgetType":"text-editor",
"elType":"widget"
},
{
"id":"2ae50433",
"settings":{
"text":"Read More",
"align":"left",
"align_mobile":"center",
"size":"md",
"icon":"fa fa-angle-double-right",
"icon_align":"right",
"typography_typography":"custom",
"typography_font_family":"Playfair Display",
"background_color":"#e4bc36",
"button_background_hover_color":"#8daca6",
"border_radius":{
"unit":"px",
"top":"0",
"right":"0",
"bottom":"0",
"left":"0",
"isLinked":true
}
},
"elements":[
],
"isInner":false,
"widgetType":"button",
"elType":"widget"
}
],
"isInner":false,
"elType":"column"
},
{
"id":"169d14c2",
"settings":{
"_column_size":50,
"_inline_size":null
},
"elements":[
{
"id":"41d9ad60",
"settings":{
"image":{
"id":591,
"url":"http:\/\/demo.geekygreenowl.com\/wp-content\/uploads\/2019\/11\/main2.jpg"
},
"image_size":"full",
"image_border_border":"solid",
"image_border_width":{
"unit":"px",
"top":"10",
"right":"10",
"bottom":"10",
"left":"10",
"isLinked":true
},
"image_border_color":"#ffffff",
"image_box_shadow_box_shadow_type":"yes",
"image_box_shadow_box_shadow":{
"horizontal":"10",
"vertical":"10",
"blur":"20",
"spread":0,
"inset":"",
"color":"rgba(0,0,0,0.12)"
},
"_padding_mobile":{
"unit":"px",
"top":"0",
"right":"0",
"bottom":"30",
"left":"0",
"isLinked":false
}
},
"elements":[
],
"isInner":false,
"widgetType":"image",
"elType":"widget"
}
],
"isInner":false,
"elType":"column"
}
],
"isInner":false,
"elType":"section"
}
]
}
``` | So, are you looking for a JSON importer for Elementor? If so, why not use their native importer? See here:
[](https://i.stack.imgur.com/cefCh.png)
However, if you would rather have an option in a menu, try this small plugin. It adds an importer under `Tools > Import`, called Elementor JSON Importer, that you can use to import JSON files (it technically also handles .zip files). With it, you can upload a JSON file and it generates an Elementor template from it. It saves the uploaded files in the `wp-content/uploads` folder.
```
<?php
/**
* Elementor JSON Importer
*
* Plugin Name: Elementor Importer
* Plugin URI: https://example.com
* Description: Imports local JSON data and creates an Elementor post.
* Version: 0.1.0
* Author: Your Name Here
* Author URI: https://example.com
* Text Domain: elementor-json-importer
*/
if ( ! defined( 'WP_LOAD_IMPORTERS' ) )
return;
// Load Importer API
require_once ABSPATH . 'wp-admin/includes/import.php';
// Require Elementor API
require_once plugin_dir_path( __DIR__ ) . 'elementor/includes/template-library/sources/base.php';
require_once plugin_dir_path( __DIR__ ) . 'elementor/includes/template-library/sources/local.php';
// Make sure the importer class exists and is available.
if ( ! class_exists( 'WP_Importer' ) ) {
$class_wp_importer = ABSPATH . 'wp-admin/includes/class-wp-importer.php';
if ( file_exists( $class_wp_importer ) ) {
require_once $class_wp_importer;
}
}
/**
* Elementor JSON Importer
*
* Will process JSON data for importing Elementor posts into WordPress.
*
* @since 0.1.0
*/
if ( class_exists( 'WP_Importer' ) ) {
class Elementor_JSON_Importer extends WP_Importer {
// Constructor
public function __construct() {
// Nothing.
}
// Executes on import dispatch.
public function dispatch() {
if ( empty( $_GET['step'] ) ) {
$step = 0;
} else {
$step = (int) $_GET['step'];
}
$this->header();
switch ($step) {
case 0:
$this->greet();
break;
case 1:
check_admin_referer( 'import-upload' );
$result = $this->import();
if ( is_wp_error( $result ) ) {
echo $result->get_error_message();
}
break;
}
$this->footer();
}
// Echoes page footer.
protected function footer() {
echo '</div>';
}
// Echoes greeting.
protected function greet() {
echo '<div class="narrow">';
echo '<p>'.__( 'This importer allows you to extract posts from an Elementor JSON file into your WordPress site. Pick a JSON file to upload and click Import.', 'elementor-json-importer' ).'</p>';
wp_import_upload_form( 'admin.php?import=elementor-json&step=1' );
echo '</div>';
}
// Echoes page header.
protected function header() {
echo '<div class="wrap">';
screen_icon();
echo '<h2>'.__( 'Import JSON', 'elementor-json-importer-importer' ).'</h2>';
}
// Performs the actual import by using methods of the Elementor API.
protected function import() {
$error = new WP_Error();
$file = wp_import_handle_upload();
if ( isset( $file['error'] ) ) {
$error->add( 'upload-error', $file['error'] );
return $error;
}
$source_local = new Elementor\TemplateLibrary\Source_Local();
if ( ! method_exists( $source_local, 'import_template' ) ) {
$error->add( 'elementor-api-error', __( 'Elementor API unavailable.', 'elementor-json-importer' ) );
return $error;
}
try {
$result = $source_local->import_template( basename( $file['file'] ), $file['file'] );
} catch ( Exception $e ) {
$error->add( 'elementor-import-error', __( 'Elementor import has failed.', 'elementor-json-importer' ) );
return $error;
} finally {
wp_import_cleanup( $file['id'] );
}
echo '<h3>';
printf( __( 'All done. <a href="%s">View template</a>', 'rss-importer' ), esc_url( $result[0]['url'] ) );
echo '</h3>';
}
}
// Create a new instance of the importer class.
$elementor_json_importer = new Elementor_JSON_Importer();
// Attempt to register importer.
$error = register_importer(
'elementor-json',
__( 'Elementor JSON Importer', 'elementor-json-importer' ),
__( 'Import posts from an Elementor JSON file.', 'elementor-json-importer' ),
array ( $elementor_json_importer, 'dispatch' )
);
if ( is_wp_error( $error ) ) {
error_log( $error->get_error_message() );
}
} // class_exists( 'WP_Importer' )
function elementor_json_importer_init() {
load_plugin_textdomain( 'elementor-json-importer', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
}
add_action( 'init', 'elementor_json_importer_init' );
```
It depends heavily on the Elementor plugin, though, so make sure to check if it works each time the Elementor plugin receives an update. |
351,357 | <p>Okay so I'm a complete newbie.
Things I've done so far: Install xampp, install wordpress, create a dummy site, have a web address I'd like to use.
The problem: My college provides homepages (www.home.uniname.edu/~username) for the students. Now, the files are handles by nextcloud. We are supposed to basically copy our website files on the public_html folder on the nextcloud account. I tried doing this using HTML templates I found online and it works fine. But I can't figure out how to get my wordpress site running. Is this because WordPress files are php? I've searched online and most of them seem to use cpanel but with hosting form godaddy and others. I have no idea how to go about using cpanel.</p>
<p>Tl;dr: Have a college assigned homepage. HTML templates work fine when uploaded to public_html. Made a wordpress site but can't get it online. Need a walk through. Thanks.</p>
| [
{
"answer_id": 351926,
"author": "Cas Dekkers",
"author_id": 153884,
"author_profile": "https://wordpress.stackexchange.com/users/153884",
"pm_score": 1,
"selected": false,
"text": "<p>So if I understand your question correctly, you have an XML file, and you would like to import it and save the content to a post?</p>\n\n<p>You can do this with a plugin, for example, <a href=\"https://wordpress.org/plugins/wp-all-import/\" rel=\"nofollow noreferrer\">this one</a>, but if you're not too keen on third-party plugins, you could try parsing the XML yourself with PHP's SimpleXML parser. Here's an example from <a href=\"https://www.w3schools.com/php/php_xml_simplexml_read.asp\" rel=\"nofollow noreferrer\">w3schools.com</a>. With it, you can turn your XML data into PHP objects. To my knowledge, there exists no built-in WP API that you can use for this purpose.</p>\n\n<p>Does this answer your question?</p>\n"
},
{
"answer_id": 352175,
"author": "Cas Dekkers",
"author_id": 153884,
"author_profile": "https://wordpress.stackexchange.com/users/153884",
"pm_score": 1,
"selected": true,
"text": "<p>So, are you looking for a JSON importer for Elementor? If so, why not use their native importer? See here:</p>\n\n<p><a href=\"https://i.stack.imgur.com/cefCh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cefCh.png\" alt=\"Native Elementor Importer\"></a></p>\n\n<p>However, if you would rather have an option in a menu, try this small plugin. It adds an importer under <code>Tools > Import</code>, called Elementor JSON Importer, that you can use to import JSON files (it technically also handles .zip files). With it, you can upload a JSON file and it generates an Elementor template from it. It saves the uploaded files in the <code>wp-content/uploads</code> folder.</p>\n\n<pre><code><?php\n/**\n * Elementor JSON Importer\n *\n * Plugin Name: Elementor Importer\n * Plugin URI: https://example.com\n * Description: Imports local JSON data and creates an Elementor post.\n * Version: 0.1.0\n * Author: Your Name Here\n * Author URI: https://example.com\n * Text Domain: elementor-json-importer\n */\n\nif ( ! defined( 'WP_LOAD_IMPORTERS' ) )\n return;\n\n// Load Importer API\nrequire_once ABSPATH . 'wp-admin/includes/import.php';\n\n// Require Elementor API\nrequire_once plugin_dir_path( __DIR__ ) . 'elementor/includes/template-library/sources/base.php';\nrequire_once plugin_dir_path( __DIR__ ) . 'elementor/includes/template-library/sources/local.php';\n\n// Make sure the importer class exists and is available.\nif ( ! class_exists( 'WP_Importer' ) ) {\n $class_wp_importer = ABSPATH . 'wp-admin/includes/class-wp-importer.php';\n if ( file_exists( $class_wp_importer ) ) {\n require_once $class_wp_importer;\n }\n}\n\n/**\n * Elementor JSON Importer\n *\n * Will process JSON data for importing Elementor posts into WordPress.\n *\n * @since 0.1.0\n */\nif ( class_exists( 'WP_Importer' ) ) {\n\n class Elementor_JSON_Importer extends WP_Importer {\n\n // Constructor\n public function __construct() {\n // Nothing.\n }\n\n // Executes on import dispatch.\n public function dispatch() {\n if ( empty( $_GET['step'] ) ) {\n $step = 0;\n } else {\n $step = (int) $_GET['step'];\n }\n\n $this->header();\n\n switch ($step) {\n case 0:\n $this->greet();\n break;\n case 1:\n check_admin_referer( 'import-upload' );\n $result = $this->import();\n if ( is_wp_error( $result ) ) {\n echo $result->get_error_message();\n }\n break;\n }\n\n $this->footer();\n }\n\n // Echoes page footer.\n protected function footer() {\n echo '</div>';\n }\n\n // Echoes greeting.\n protected function greet() {\n echo '<div class=\"narrow\">';\n echo '<p>'.__( 'This importer allows you to extract posts from an Elementor JSON file into your WordPress site. Pick a JSON file to upload and click Import.', 'elementor-json-importer' ).'</p>';\n wp_import_upload_form( 'admin.php?import=elementor-json&amp;step=1' );\n echo '</div>';\n }\n\n // Echoes page header.\n protected function header() {\n echo '<div class=\"wrap\">';\n screen_icon();\n echo '<h2>'.__( 'Import JSON', 'elementor-json-importer-importer' ).'</h2>';\n }\n\n // Performs the actual import by using methods of the Elementor API.\n protected function import() {\n $error = new WP_Error();\n $file = wp_import_handle_upload();\n\n if ( isset( $file['error'] ) ) {\n $error->add( 'upload-error', $file['error'] );\n return $error;\n }\n\n $source_local = new Elementor\\TemplateLibrary\\Source_Local();\n if ( ! method_exists( $source_local, 'import_template' ) ) {\n $error->add( 'elementor-api-error', __( 'Elementor API unavailable.', 'elementor-json-importer' ) );\n return $error;\n }\n\n try {\n $result = $source_local->import_template( basename( $file['file'] ), $file['file'] );\n } catch ( Exception $e ) {\n $error->add( 'elementor-import-error', __( 'Elementor import has failed.', 'elementor-json-importer' ) );\n return $error;\n } finally {\n wp_import_cleanup( $file['id'] );\n }\n\n echo '<h3>';\n printf( __( 'All done. <a href=\"%s\">View template</a>', 'rss-importer' ), esc_url( $result[0]['url'] ) );\n echo '</h3>';\n }\n }\n\n // Create a new instance of the importer class.\n $elementor_json_importer = new Elementor_JSON_Importer();\n\n // Attempt to register importer.\n $error = register_importer(\n 'elementor-json',\n __( 'Elementor JSON Importer', 'elementor-json-importer' ),\n __( 'Import posts from an Elementor JSON file.', 'elementor-json-importer' ),\n array ( $elementor_json_importer, 'dispatch' )\n );\n\n if ( is_wp_error( $error ) ) {\n error_log( $error->get_error_message() );\n } \n\n} // class_exists( 'WP_Importer' )\n\nfunction elementor_json_importer_init() {\n load_plugin_textdomain( 'elementor-json-importer', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );\n}\nadd_action( 'init', 'elementor_json_importer_init' );\n</code></pre>\n\n<p>It depends heavily on the Elementor plugin, though, so make sure to check if it works each time the Elementor plugin receives an update.</p>\n"
}
] | 2019/10/28 | [
"https://wordpress.stackexchange.com/questions/351357",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/177474/"
] | Okay so I'm a complete newbie.
Things I've done so far: Install xampp, install wordpress, create a dummy site, have a web address I'd like to use.
The problem: My college provides homepages (www.home.uniname.edu/~username) for the students. Now, the files are handles by nextcloud. We are supposed to basically copy our website files on the public\_html folder on the nextcloud account. I tried doing this using HTML templates I found online and it works fine. But I can't figure out how to get my wordpress site running. Is this because WordPress files are php? I've searched online and most of them seem to use cpanel but with hosting form godaddy and others. I have no idea how to go about using cpanel.
Tl;dr: Have a college assigned homepage. HTML templates work fine when uploaded to public\_html. Made a wordpress site but can't get it online. Need a walk through. Thanks. | So, are you looking for a JSON importer for Elementor? If so, why not use their native importer? See here:
[](https://i.stack.imgur.com/cefCh.png)
However, if you would rather have an option in a menu, try this small plugin. It adds an importer under `Tools > Import`, called Elementor JSON Importer, that you can use to import JSON files (it technically also handles .zip files). With it, you can upload a JSON file and it generates an Elementor template from it. It saves the uploaded files in the `wp-content/uploads` folder.
```
<?php
/**
* Elementor JSON Importer
*
* Plugin Name: Elementor Importer
* Plugin URI: https://example.com
* Description: Imports local JSON data and creates an Elementor post.
* Version: 0.1.0
* Author: Your Name Here
* Author URI: https://example.com
* Text Domain: elementor-json-importer
*/
if ( ! defined( 'WP_LOAD_IMPORTERS' ) )
return;
// Load Importer API
require_once ABSPATH . 'wp-admin/includes/import.php';
// Require Elementor API
require_once plugin_dir_path( __DIR__ ) . 'elementor/includes/template-library/sources/base.php';
require_once plugin_dir_path( __DIR__ ) . 'elementor/includes/template-library/sources/local.php';
// Make sure the importer class exists and is available.
if ( ! class_exists( 'WP_Importer' ) ) {
$class_wp_importer = ABSPATH . 'wp-admin/includes/class-wp-importer.php';
if ( file_exists( $class_wp_importer ) ) {
require_once $class_wp_importer;
}
}
/**
* Elementor JSON Importer
*
* Will process JSON data for importing Elementor posts into WordPress.
*
* @since 0.1.0
*/
if ( class_exists( 'WP_Importer' ) ) {
class Elementor_JSON_Importer extends WP_Importer {
// Constructor
public function __construct() {
// Nothing.
}
// Executes on import dispatch.
public function dispatch() {
if ( empty( $_GET['step'] ) ) {
$step = 0;
} else {
$step = (int) $_GET['step'];
}
$this->header();
switch ($step) {
case 0:
$this->greet();
break;
case 1:
check_admin_referer( 'import-upload' );
$result = $this->import();
if ( is_wp_error( $result ) ) {
echo $result->get_error_message();
}
break;
}
$this->footer();
}
// Echoes page footer.
protected function footer() {
echo '</div>';
}
// Echoes greeting.
protected function greet() {
echo '<div class="narrow">';
echo '<p>'.__( 'This importer allows you to extract posts from an Elementor JSON file into your WordPress site. Pick a JSON file to upload and click Import.', 'elementor-json-importer' ).'</p>';
wp_import_upload_form( 'admin.php?import=elementor-json&step=1' );
echo '</div>';
}
// Echoes page header.
protected function header() {
echo '<div class="wrap">';
screen_icon();
echo '<h2>'.__( 'Import JSON', 'elementor-json-importer-importer' ).'</h2>';
}
// Performs the actual import by using methods of the Elementor API.
protected function import() {
$error = new WP_Error();
$file = wp_import_handle_upload();
if ( isset( $file['error'] ) ) {
$error->add( 'upload-error', $file['error'] );
return $error;
}
$source_local = new Elementor\TemplateLibrary\Source_Local();
if ( ! method_exists( $source_local, 'import_template' ) ) {
$error->add( 'elementor-api-error', __( 'Elementor API unavailable.', 'elementor-json-importer' ) );
return $error;
}
try {
$result = $source_local->import_template( basename( $file['file'] ), $file['file'] );
} catch ( Exception $e ) {
$error->add( 'elementor-import-error', __( 'Elementor import has failed.', 'elementor-json-importer' ) );
return $error;
} finally {
wp_import_cleanup( $file['id'] );
}
echo '<h3>';
printf( __( 'All done. <a href="%s">View template</a>', 'rss-importer' ), esc_url( $result[0]['url'] ) );
echo '</h3>';
}
}
// Create a new instance of the importer class.
$elementor_json_importer = new Elementor_JSON_Importer();
// Attempt to register importer.
$error = register_importer(
'elementor-json',
__( 'Elementor JSON Importer', 'elementor-json-importer' ),
__( 'Import posts from an Elementor JSON file.', 'elementor-json-importer' ),
array ( $elementor_json_importer, 'dispatch' )
);
if ( is_wp_error( $error ) ) {
error_log( $error->get_error_message() );
}
} // class_exists( 'WP_Importer' )
function elementor_json_importer_init() {
load_plugin_textdomain( 'elementor-json-importer', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
}
add_action( 'init', 'elementor_json_importer_init' );
```
It depends heavily on the Elementor plugin, though, so make sure to check if it works each time the Elementor plugin receives an update. |
351,358 | <p>In my WordPress website, I am using the Cloudflare and Elementor editor also but when I am trying to edit the page using the Elementor, my Elementor is not opening. I think it is because of the Cloudflare in my WordPress.</p>
<p>Cloudflare has added the <code>script</code> in the head and also in the footer:</p>
<pre><code><script src="https://ajax.cloudflare.com/cdn-cgi/scripts/95c75768/cloudflare-static/rocket-loader.min.js" data-cf-settings="9838dd25b616f37c8176faa3-|49"></script>
</code></pre>
<p>So, How to exclude the script from WordPress?</p>
<p>Added this in my <strong>functions.php</strong></p>
<pre><code>add_filter( 'script_loader_tag', function ( $tag, $handle ) {
if ( 'script-handle' !== $handle )
return $tag;
return str_replace( "type='text/javascript' src", ' data-cfasync="false" src', $tag );
}, 10, 2 );
</code></pre>
<blockquote>
<p>But not working.</p>
</blockquote>
<p>Also tried this by adding in the <strong>functions.php</strong>:</p>
<pre><code><script data-cfasync=”false” src=”/javascript.js”></script>
</code></pre>
<blockquote>
<p>But not working.</p>
</blockquote>
<p>Any help is much appreciated.</p>
| [
{
"answer_id": 351380,
"author": "Capolooper",
"author_id": 177390,
"author_profile": "https://wordpress.stackexchange.com/users/177390",
"pm_score": 0,
"selected": false,
"text": "<p>Why you are using a filter?\n<a href=\"https://developer.wordpress.org/themes/basics/including-css-javascript/\" rel=\"nofollow noreferrer\">wp_enqueue_script()</a> function would be much better.\nAnyways, Rocket Loader seems to be conflicting with some WP component, i.e Jetpack.\nHope can help</p>\n"
},
{
"answer_id": 351492,
"author": "Rahul Kumar",
"author_id": 172395,
"author_profile": "https://wordpress.stackexchange.com/users/172395",
"pm_score": 1,
"selected": false,
"text": "<p>This helps me to solve the problem:</p>\n\n<p><a href=\"https://snifflevalve.com/elementor-tutorials/elementor-cloudflares-rocket-loader-not-play-well-together/\" rel=\"nofollow noreferrer\">https://snifflevalve.com/elementor-tutorials/elementor-cloudflares-rocket-loader-not-play-well-together/</a></p>\n"
}
] | 2019/10/28 | [
"https://wordpress.stackexchange.com/questions/351358",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/172395/"
] | In my WordPress website, I am using the Cloudflare and Elementor editor also but when I am trying to edit the page using the Elementor, my Elementor is not opening. I think it is because of the Cloudflare in my WordPress.
Cloudflare has added the `script` in the head and also in the footer:
```
<script src="https://ajax.cloudflare.com/cdn-cgi/scripts/95c75768/cloudflare-static/rocket-loader.min.js" data-cf-settings="9838dd25b616f37c8176faa3-|49"></script>
```
So, How to exclude the script from WordPress?
Added this in my **functions.php**
```
add_filter( 'script_loader_tag', function ( $tag, $handle ) {
if ( 'script-handle' !== $handle )
return $tag;
return str_replace( "type='text/javascript' src", ' data-cfasync="false" src', $tag );
}, 10, 2 );
```
>
> But not working.
>
>
>
Also tried this by adding in the **functions.php**:
```
<script data-cfasync=”false” src=”/javascript.js”></script>
```
>
> But not working.
>
>
>
Any help is much appreciated. | This helps me to solve the problem:
<https://snifflevalve.com/elementor-tutorials/elementor-cloudflares-rocket-loader-not-play-well-together/> |
351,415 | <p>How can I exclude posts with a specific custom field and value with this query?</p>
<pre><code>$my_query = new WP_Query( $args = array(
// It should be in the first category of our post:
'category__in' => array( $st_cat ),
// Our post should NOT be in the list:
'post__not_in' => array( $post->ID ),
'posts_per_page' => 8,
'orderby' => 'desc',
));
</code></pre>
<p><strong>I already tried this without sucess:</strong></p>
<pre><code>$my_query = new WP_Query( $args = array(
// It should be in the first category of our post:
'category__in' => array( $st_cat ),
// Our post should NOT be in the list:
'post__not_in' => array( $post->ID ),
'posts_per_page' => 8,
'orderby' => 'desc',
//extra code added without sucess
'meta_query' => array(
'key' => 'city',
'value' => 'true',
'compare' => 'NOT LIKE',
)
));
</code></pre>
| [
{
"answer_id": 351416,
"author": "user10758246",
"author_id": 177508,
"author_profile": "https://wordpress.stackexchange.com/users/177508",
"pm_score": 2,
"selected": false,
"text": "<p>The meta_query argument takes an array of arrays.</p>\n\n<pre><code>'meta_query' => array(\n array(\n 'key' => 'city',\n 'value' => 'true',\n 'compare' => 'NOT LIKE',\n )\n)\n</code></pre>\n"
},
{
"answer_id": 351460,
"author": "bpy",
"author_id": 18693,
"author_profile": "https://wordpress.stackexchange.com/users/18693",
"pm_score": -1,
"selected": false,
"text": "<p>Perhaps something like this can work:</p>\n\n<pre><code> if ( !$query->is_admin && $query->is_search) {\n $query->set('post__not_in', array(36,33));\n $query->set('meta_query',\n array('relation' => 'OR',\n array('key' => 'city',\n 'value' => 'true', \n 'compare' => 'NOT EXISTS'),\n ));\n }\n return $query;\n</code></pre>\n"
}
] | 2019/10/28 | [
"https://wordpress.stackexchange.com/questions/351415",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/18693/"
] | How can I exclude posts with a specific custom field and value with this query?
```
$my_query = new WP_Query( $args = array(
// It should be in the first category of our post:
'category__in' => array( $st_cat ),
// Our post should NOT be in the list:
'post__not_in' => array( $post->ID ),
'posts_per_page' => 8,
'orderby' => 'desc',
));
```
**I already tried this without sucess:**
```
$my_query = new WP_Query( $args = array(
// It should be in the first category of our post:
'category__in' => array( $st_cat ),
// Our post should NOT be in the list:
'post__not_in' => array( $post->ID ),
'posts_per_page' => 8,
'orderby' => 'desc',
//extra code added without sucess
'meta_query' => array(
'key' => 'city',
'value' => 'true',
'compare' => 'NOT LIKE',
)
));
``` | The meta\_query argument takes an array of arrays.
```
'meta_query' => array(
array(
'key' => 'city',
'value' => 'true',
'compare' => 'NOT LIKE',
)
)
``` |
351,443 | <p>I'm borrowing from the code at <a href="https://wordpress.stackexchange.com/questions/45436/add-filter-menu-to-admin-list-of-posts-of-custom-type-to-filter-posts-by-custo">Add filter menu to admin list of posts (of custom type) to filter posts by custom field values</a> to add a filter to my custom post type with the <code>parse_query</code> filter:</p>
<pre><code>function grievance_posts_filter( $query ){
global $pagenow;
$type = 'post';
if (isset($_GET['post_type'])) {
$type = $_GET['post_type'];
}
if ( 'grievance' == $type && is_admin() && $pagenow=='edit.php' && isset($_GET['step']) && $_GET['step'] != '') {
$query->query_vars['meta_key'] = 'my_first_plugin_fields[step]';
$query->query_vars['meta_value'] = 2;
}
}
add_filter( 'parse_query', 'grievance_posts_filter' );
</code></pre>
<p>In the above code, I have hard-coded the value of the the <code>meta_value</code> to troubleshoot. I expect the above code to show me only the posts with the <code>step</code> value is set to "2". However, instead of filtering the posts, the edit.php page is not showing any posts at all. I don't think I'm using the right values for the <code>meta_key</code> and <code>meta_value</code> elements. I'm not sure what to put there. My meta_key has multiple sub-keys associated with it.</p>
<p>I have also tried:</p>
<pre><code> $query->query_vars['meta_key'] = 'my_first_plugin_fields';
$query->query_vars['meta_value'] = array( 'step' => 2 );
</code></pre>
<p>but this did not work either.</p>
<p>I also attempted:</p>
<pre><code> $meta = [ 'my_first_plugin_fields' => [ 'key' => 'step', 'value' => '2', 'compare' => '=' ] ] ;
$query->query_vars['meta_query'] = $meta;
</code></pre>
<p>without success.</p>
| [
{
"answer_id": 351416,
"author": "user10758246",
"author_id": 177508,
"author_profile": "https://wordpress.stackexchange.com/users/177508",
"pm_score": 2,
"selected": false,
"text": "<p>The meta_query argument takes an array of arrays.</p>\n\n<pre><code>'meta_query' => array(\n array(\n 'key' => 'city',\n 'value' => 'true',\n 'compare' => 'NOT LIKE',\n )\n)\n</code></pre>\n"
},
{
"answer_id": 351460,
"author": "bpy",
"author_id": 18693,
"author_profile": "https://wordpress.stackexchange.com/users/18693",
"pm_score": -1,
"selected": false,
"text": "<p>Perhaps something like this can work:</p>\n\n<pre><code> if ( !$query->is_admin && $query->is_search) {\n $query->set('post__not_in', array(36,33));\n $query->set('meta_query',\n array('relation' => 'OR',\n array('key' => 'city',\n 'value' => 'true', \n 'compare' => 'NOT EXISTS'),\n ));\n }\n return $query;\n</code></pre>\n"
}
] | 2019/10/29 | [
"https://wordpress.stackexchange.com/questions/351443",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86700/"
] | I'm borrowing from the code at [Add filter menu to admin list of posts (of custom type) to filter posts by custom field values](https://wordpress.stackexchange.com/questions/45436/add-filter-menu-to-admin-list-of-posts-of-custom-type-to-filter-posts-by-custo) to add a filter to my custom post type with the `parse_query` filter:
```
function grievance_posts_filter( $query ){
global $pagenow;
$type = 'post';
if (isset($_GET['post_type'])) {
$type = $_GET['post_type'];
}
if ( 'grievance' == $type && is_admin() && $pagenow=='edit.php' && isset($_GET['step']) && $_GET['step'] != '') {
$query->query_vars['meta_key'] = 'my_first_plugin_fields[step]';
$query->query_vars['meta_value'] = 2;
}
}
add_filter( 'parse_query', 'grievance_posts_filter' );
```
In the above code, I have hard-coded the value of the the `meta_value` to troubleshoot. I expect the above code to show me only the posts with the `step` value is set to "2". However, instead of filtering the posts, the edit.php page is not showing any posts at all. I don't think I'm using the right values for the `meta_key` and `meta_value` elements. I'm not sure what to put there. My meta\_key has multiple sub-keys associated with it.
I have also tried:
```
$query->query_vars['meta_key'] = 'my_first_plugin_fields';
$query->query_vars['meta_value'] = array( 'step' => 2 );
```
but this did not work either.
I also attempted:
```
$meta = [ 'my_first_plugin_fields' => [ 'key' => 'step', 'value' => '2', 'compare' => '=' ] ] ;
$query->query_vars['meta_query'] = $meta;
```
without success. | The meta\_query argument takes an array of arrays.
```
'meta_query' => array(
array(
'key' => 'city',
'value' => 'true',
'compare' => 'NOT LIKE',
)
)
``` |
351,549 | <p>I would like to have inside my theme folder, a folder where I can leave all the portion of code and snippets that I don't want to use anymore or I just want to save for a while, and accessible every time I want to check it in the browser, the same way I usually do with frontpage.php. Something I can access through the link: <a href="http://localhost:8888/mydomain.com/temporary/page1.php" rel="nofollow noreferrer">http://localhost:8888/mydomain.com/temporary/page1.php</a>
<a href="http://localhost:8888/mydomain.com/temporary/page2.php" rel="nofollow noreferrer">http://localhost:8888/mydomain.com/temporary/page2.php</a>
<a href="http://localhost:8888/mydomain.com/temporary/page3.php" rel="nofollow noreferrer">http://localhost:8888/mydomain.com/temporary/page3.php</a></p>
<p>pd: i'm using understrap-child-master</p>
| [
{
"answer_id": 351416,
"author": "user10758246",
"author_id": 177508,
"author_profile": "https://wordpress.stackexchange.com/users/177508",
"pm_score": 2,
"selected": false,
"text": "<p>The meta_query argument takes an array of arrays.</p>\n\n<pre><code>'meta_query' => array(\n array(\n 'key' => 'city',\n 'value' => 'true',\n 'compare' => 'NOT LIKE',\n )\n)\n</code></pre>\n"
},
{
"answer_id": 351460,
"author": "bpy",
"author_id": 18693,
"author_profile": "https://wordpress.stackexchange.com/users/18693",
"pm_score": -1,
"selected": false,
"text": "<p>Perhaps something like this can work:</p>\n\n<pre><code> if ( !$query->is_admin && $query->is_search) {\n $query->set('post__not_in', array(36,33));\n $query->set('meta_query',\n array('relation' => 'OR',\n array('key' => 'city',\n 'value' => 'true', \n 'compare' => 'NOT EXISTS'),\n ));\n }\n return $query;\n</code></pre>\n"
}
] | 2019/10/30 | [
"https://wordpress.stackexchange.com/questions/351549",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70257/"
] | I would like to have inside my theme folder, a folder where I can leave all the portion of code and snippets that I don't want to use anymore or I just want to save for a while, and accessible every time I want to check it in the browser, the same way I usually do with frontpage.php. Something I can access through the link: <http://localhost:8888/mydomain.com/temporary/page1.php>
<http://localhost:8888/mydomain.com/temporary/page2.php>
<http://localhost:8888/mydomain.com/temporary/page3.php>
pd: i'm using understrap-child-master | The meta\_query argument takes an array of arrays.
```
'meta_query' => array(
array(
'key' => 'city',
'value' => 'true',
'compare' => 'NOT LIKE',
)
)
``` |
351,567 | <p>I'm using this code to add the alt text to my featured images on upload.</p>
<pre><code>$image_title = get_post( $post->ID )->post_title;
// Sanitize the title: remove hyphens, underscores & extra spaces:
$image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ', $image_title );
// Sanitize the title: capitalize first letter of every word (other letters lower case):
$image_title = ucwords( strtolower( $image_title ) );
// Set the image Alt-Text
add_post_meta( $post->ID, '_wp_attachment_image_alt', $image_title );
</code></pre>
<p>It's working and I can see it on it's database table <code>wp_postmeta</code> under it's post ID.</p>
<p>Altough it's correctly registred on the database, the featured image doesn't have the Alt text (see the image bellow)</p>
<p><a href="https://i.stack.imgur.com/GtQpx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GtQpx.png" alt="missing Alt Text"></a></p>
<p>What could be the problem?</p>
| [
{
"answer_id": 351416,
"author": "user10758246",
"author_id": 177508,
"author_profile": "https://wordpress.stackexchange.com/users/177508",
"pm_score": 2,
"selected": false,
"text": "<p>The meta_query argument takes an array of arrays.</p>\n\n<pre><code>'meta_query' => array(\n array(\n 'key' => 'city',\n 'value' => 'true',\n 'compare' => 'NOT LIKE',\n )\n)\n</code></pre>\n"
},
{
"answer_id": 351460,
"author": "bpy",
"author_id": 18693,
"author_profile": "https://wordpress.stackexchange.com/users/18693",
"pm_score": -1,
"selected": false,
"text": "<p>Perhaps something like this can work:</p>\n\n<pre><code> if ( !$query->is_admin && $query->is_search) {\n $query->set('post__not_in', array(36,33));\n $query->set('meta_query',\n array('relation' => 'OR',\n array('key' => 'city',\n 'value' => 'true', \n 'compare' => 'NOT EXISTS'),\n ));\n }\n return $query;\n</code></pre>\n"
}
] | 2019/10/30 | [
"https://wordpress.stackexchange.com/questions/351567",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/18693/"
] | I'm using this code to add the alt text to my featured images on upload.
```
$image_title = get_post( $post->ID )->post_title;
// Sanitize the title: remove hyphens, underscores & extra spaces:
$image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ', $image_title );
// Sanitize the title: capitalize first letter of every word (other letters lower case):
$image_title = ucwords( strtolower( $image_title ) );
// Set the image Alt-Text
add_post_meta( $post->ID, '_wp_attachment_image_alt', $image_title );
```
It's working and I can see it on it's database table `wp_postmeta` under it's post ID.
Altough it's correctly registred on the database, the featured image doesn't have the Alt text (see the image bellow)
[](https://i.stack.imgur.com/GtQpx.png)
What could be the problem? | The meta\_query argument takes an array of arrays.
```
'meta_query' => array(
array(
'key' => 'city',
'value' => 'true',
'compare' => 'NOT LIKE',
)
)
``` |
351,582 | <p>Our store sells software and we're adding a software voucher code to each purchased. Once the purchase is completed (via the <code>woocommerce_payment_complete</code> hook) we generate the voucher code and add it to each item purchased via <a href="https://docs.woocommerce.com/wc-apidocs/function-wc_add_order_item_meta.html" rel="nofollow noreferrer">wc_add_order_item_meta</a> method. </p>
<p>Summarized code:</p>
<pre><code>add_filter('woocommerce_payment_complete', 'add_voucher_code');
function add_voucher_code( $order_id ) {
$order = new WC_Order( $order_id );
$items = $order->get_items();
foreach ($items as $item) {
for ($i = 1; $i <= $item['qty']; $i++) {
$voucher_code = 'API request based on order information to get voucher code';
wc_add_order_item_meta($item->get_id(), 'Voucher Code', $voucher_code);
}
}
}
</code></pre>
<p>For some reason or another the item custom meta shows up on the order confirmation page, but doesn't in the confirmation email. (<strong>problem 1</strong> slaps forehead) So we're utilizing the <code>woocommerce_order_item_meta_end</code> hook to add it to the confirmation email. (<a href="https://docs.woocommerce.com/wc-apidocs/function-wc_get_order_item_meta.html" rel="nofollow noreferrer">wc_get_order_item_meta</a>) </p>
<p>Summarized code: </p>
<pre><code>add_action('woocommerce_order_item_meta_end', 'email_confirmation_display_order_items', 10, 4);
function email_confirmation_display_order_items($item_id, $item, $order, $plain_text) {
echo '<div>Voucher Code: '. wc_get_order_item_meta( $item_id, 'Voucher Code') .'</div>';
}
</code></pre>
<p><strong>Problem 2</strong> is that added snippet of code shows on the both the order confirmation page (so now it shows twice) and in the order confirmation email. (slaps forehead again) </p>
<p><strong>Current Problem 2 Solution</strong><br>
Right now we solved it by adding an if statement which is suggested <a href="https://stackoverflow.com/questions/52684334/filter-out-unwanted-order-item-meta-data-from-woocommerce-email-notifications/52684694#52684694">here</a>. Like so: </p>
<pre><code>// Only on emails notifications
if( ! (is_admin() || is_wc_endpoint_url() )) {
echo '<div>Voucher Code: '. wc_get_order_item_meta( $item_id, 'Voucher Code') .'</div>';
}
</code></pre>
<p>This feels like a band-aid fix and any insight/suggestions would be much appreciated. Thanks!</p>
| [
{
"answer_id": 351969,
"author": "Ryan",
"author_id": 144151,
"author_profile": "https://wordpress.stackexchange.com/users/144151",
"pm_score": 3,
"selected": true,
"text": "<p>Since this isn't getting much action I'll put our <em>band-aid</em> fix as the current solution.</p>\n\n<p><strong>Problem 1 Solution</strong><br>\nThe added item meta data shows on the order confirmation page and does not show on the confirmation email. We solved this by utilizing the <code>woocommerce_order_item_meta_end</code> hook to add the extra item meta. </p>\n\n<p><strong>Problem 2 Solution</strong><br>\nAdding the item meta data via <code>woocommerce_order_item_meta_end</code> to the confirmation \n email also adds it to the confirmation page (visibly duplicating it). We solved this by adding an if statement suggested by @LoicTheAztec <a href=\"https://stackoverflow.com/questions/52684334/filter-out-unwanted-order-item-meta-data-from-woocommerce-email-notifications/52684694#52684694\">here</a>.</p>\n\n<pre><code>add_action('woocommerce_order_item_meta_end', 'email_confirmation_display_order_items', 10, 4);\n\nfunction email_confirmation_display_order_items($item_id, $item, $order, $plain_text) {\n\n // Only on emails notifications\n if( ! (is_admin() || is_wc_endpoint_url() )) {\n echo '<div>Voucher Code: '. wc_get_order_item_meta( $item_id, 'Voucher Code') .'</div>';\n }\n}\n</code></pre>\n\n<p><strong>Resources</strong><br>\n<a href=\"https://businessbloomer.com/woocommerce-visual-hook-guide-emails/\" rel=\"nofollow noreferrer\">email confirmation hook visual guide</a><br>\n<a href=\"https://docs.woocommerce.com/wc-apidocs/function-wc_get_order_item_meta.html\" rel=\"nofollow noreferrer\">wc_get_order_item_meta docs</a><br>\n<a href=\"https://stackoverflow.com/questions/52684334/filter-out-unwanted-order-item-meta-data-from-woocommerce-email-notifications/52684694#52684694\">Filter out unwanted order item meta data from Woocommerce email notifications</a></p>\n"
},
{
"answer_id": 407860,
"author": "Bas van Dijk",
"author_id": 106380,
"author_profile": "https://wordpress.stackexchange.com/users/106380",
"pm_score": 0,
"selected": false,
"text": "<p>You could also just only execute the add_action whenever you're in a different action. You could hook into <code>add_action( 'woocommerce_email_header' );</code> first and then hook into <code>woocommerce_order_item_meta_end</code>. This way we're only doing this whenever the <code>woocommerce_email_header</code> action is executed.</p>\n<pre><code>add_action( 'woocommerce_email_header', function() {\n add_action( 'woocommerce_order_item_meta_end', [ $this, 'functionThatDoesSomething' ], 10, 2 );\n} );\n</code></pre>\n"
}
] | 2019/10/30 | [
"https://wordpress.stackexchange.com/questions/351582",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144151/"
] | Our store sells software and we're adding a software voucher code to each purchased. Once the purchase is completed (via the `woocommerce_payment_complete` hook) we generate the voucher code and add it to each item purchased via [wc\_add\_order\_item\_meta](https://docs.woocommerce.com/wc-apidocs/function-wc_add_order_item_meta.html) method.
Summarized code:
```
add_filter('woocommerce_payment_complete', 'add_voucher_code');
function add_voucher_code( $order_id ) {
$order = new WC_Order( $order_id );
$items = $order->get_items();
foreach ($items as $item) {
for ($i = 1; $i <= $item['qty']; $i++) {
$voucher_code = 'API request based on order information to get voucher code';
wc_add_order_item_meta($item->get_id(), 'Voucher Code', $voucher_code);
}
}
}
```
For some reason or another the item custom meta shows up on the order confirmation page, but doesn't in the confirmation email. (**problem 1** slaps forehead) So we're utilizing the `woocommerce_order_item_meta_end` hook to add it to the confirmation email. ([wc\_get\_order\_item\_meta](https://docs.woocommerce.com/wc-apidocs/function-wc_get_order_item_meta.html))
Summarized code:
```
add_action('woocommerce_order_item_meta_end', 'email_confirmation_display_order_items', 10, 4);
function email_confirmation_display_order_items($item_id, $item, $order, $plain_text) {
echo '<div>Voucher Code: '. wc_get_order_item_meta( $item_id, 'Voucher Code') .'</div>';
}
```
**Problem 2** is that added snippet of code shows on the both the order confirmation page (so now it shows twice) and in the order confirmation email. (slaps forehead again)
**Current Problem 2 Solution**
Right now we solved it by adding an if statement which is suggested [here](https://stackoverflow.com/questions/52684334/filter-out-unwanted-order-item-meta-data-from-woocommerce-email-notifications/52684694#52684694). Like so:
```
// Only on emails notifications
if( ! (is_admin() || is_wc_endpoint_url() )) {
echo '<div>Voucher Code: '. wc_get_order_item_meta( $item_id, 'Voucher Code') .'</div>';
}
```
This feels like a band-aid fix and any insight/suggestions would be much appreciated. Thanks! | Since this isn't getting much action I'll put our *band-aid* fix as the current solution.
**Problem 1 Solution**
The added item meta data shows on the order confirmation page and does not show on the confirmation email. We solved this by utilizing the `woocommerce_order_item_meta_end` hook to add the extra item meta.
**Problem 2 Solution**
Adding the item meta data via `woocommerce_order_item_meta_end` to the confirmation
email also adds it to the confirmation page (visibly duplicating it). We solved this by adding an if statement suggested by @LoicTheAztec [here](https://stackoverflow.com/questions/52684334/filter-out-unwanted-order-item-meta-data-from-woocommerce-email-notifications/52684694#52684694).
```
add_action('woocommerce_order_item_meta_end', 'email_confirmation_display_order_items', 10, 4);
function email_confirmation_display_order_items($item_id, $item, $order, $plain_text) {
// Only on emails notifications
if( ! (is_admin() || is_wc_endpoint_url() )) {
echo '<div>Voucher Code: '. wc_get_order_item_meta( $item_id, 'Voucher Code') .'</div>';
}
}
```
**Resources**
[email confirmation hook visual guide](https://businessbloomer.com/woocommerce-visual-hook-guide-emails/)
[wc\_get\_order\_item\_meta docs](https://docs.woocommerce.com/wc-apidocs/function-wc_get_order_item_meta.html)
[Filter out unwanted order item meta data from Woocommerce email notifications](https://stackoverflow.com/questions/52684334/filter-out-unwanted-order-item-meta-data-from-woocommerce-email-notifications/52684694#52684694) |
351,718 | <p>I am trying to display recent posts where I have one on the left showing the image, title, excerpt and author info and on the right, just the title, date and author information. I want it to show the remaining info in the right column (stacked on one another). So far I have the one recent post on the left and the next post title on the left column but the third does not stay in the right column but rather moves to the left under the recent post #1.
What I have:
<a href="https://i.stack.imgur.com/2U8sq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2U8sq.png" alt="enter image description here"></a> </p>
<p>What I am trying to achieve:
<a href="https://i.stack.imgur.com/lmTR6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lmTR6.png" alt="enter image description here"></a></p>
<p>Here is my code:</p>
<pre><code><div class="row">
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => 3
);
$counter = 0;
$_posts = new WP_Query($args);
?>
<?php if( $_posts->have_posts() ) : ?>
<?php while ( $_posts->have_posts() ) : $_posts->the_post(); $counter++ ?>
<?php if ( $counter === 0 || $counter === 1) : ?>
<div class="col-md-6 float-left">
<div>
<a href="<?php the_permalink(); ?>" class="mb-4 d-block"><?php if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
the_post_thumbnail( 'full' );
}
?></a>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
</div>
</div>
<?php else : ?>
<div class="col-md-6 float-right">
<div class="post-entry mb-4">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="text-muted mb-3 text-uppercase small"><span><?php the_time('F jS, Y'); ?></span> by <a href="<?php the_permalink(); ?>" class="by"><?php the_author( ', ' ); ?></a></p>
</div>
</div>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; wp_reset_postdata(); ?>
</div>
</div>
</code></pre>
<p>Any help would be greatly appreciated. Thank you.</p>
| [
{
"answer_id": 351719,
"author": "Orbital",
"author_id": 28956,
"author_profile": "https://wordpress.stackexchange.com/users/28956",
"pm_score": 2,
"selected": true,
"text": "<p>Try this</p>\n\n<pre><code><div class=\"row\">\n\n <?php \n\n $args = array(\n 'post_type' => 'post',\n 'posts_per_page' => 3\n );\n\n $counter = 0;\n\n\n $_posts = new WP_Query($args);\n\n ?>\n\n\n <?php if( $_posts->have_posts() ) : ?>\n\n <?php while ( $_posts->have_posts() ) : $_posts->the_post(); $counter++ ?>\n\n <?php if ( $counter === 0 || $counter === 1) : ?>\n\n <div class=\"col-md-6 float-left\">\n <div>\n <a href=\"<?php the_permalink(); ?>\" class=\"mb-4 d-block\"><?php if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.\n the_post_thumbnail( 'full' );\n }\n ?></a>\n <h2><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></h2>\n <?php the_excerpt(); ?>\n </div>\n </div>\n\n <div class=\"col-md-6 float-right\">\n <?php else : ?>\n\n\n\n <div class=\"post-entry mb-4\">\n <h2><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></h2>\n <p class=\"text-muted mb-3 text-uppercase small\"><span><?php the_time('F jS, Y'); ?></span> by <a href=\"<?php the_permalink(); ?>\" class=\"by\"><?php the_author( ', ' ); ?></a></p>\n </div>\n\n\n\n\n <?php endif; ?>\n <?php endwhile; ?>\n\n <?php endif; wp_reset_postdata(); ?>\n </div>\n\n </div>\n</div>\n</code></pre>\n"
},
{
"answer_id": 351721,
"author": "Gopala krishnan",
"author_id": 168404,
"author_profile": "https://wordpress.stackexchange.com/users/168404",
"pm_score": 0,
"selected": false,
"text": "<p>Hope this code will helpfull for you, this code will print output in zig zag(ie. one post is left and next one left ) and so on. </p>\n\n<pre><code><div class=\"row\"><?php \n$args = array(\n 'post_type' => 'post',\n 'posts_per_page' => 3\n);\n$counter = 1;\n$_posts = new WP_Query($args);\nif( $_posts->have_posts() ) : \n while ( $_posts->have_posts() ) : $_posts->the_post(); \n if ( $counter%2 !=0) : ?>\n <div class=\"col-md-6 float-left\">\n <div>\n <a href=\"<?php the_permalink(); ?>\" class=\"mb-4 d-block\"><?php if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.\n the_post_thumbnail( 'full' );\n }\n ?></a>\n <h2><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></h2>\n <?php the_excerpt(); ?>\n </div>\n </div><?php \n else : ?>\n <div class=\"col-md-6 float-right\">\n <div class=\"post-entry mb-4\">\n <h2><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></h2>\n <p class=\"text-muted mb-3 text-uppercase small\"><span><?php the_time('F jS, Y'); ?></span> by <a href=\"<?php the_permalink(); ?>\" class=\"by\"><?php the_author( ', ' ); ?></a></p>\n </div>\n </div><?php \n endif;\n $counter++;\n endwhile; \nendif; \nwp_reset_postdata(); ?></div>\n</code></pre>\n"
}
] | 2019/11/02 | [
"https://wordpress.stackexchange.com/questions/351718",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/174342/"
] | I am trying to display recent posts where I have one on the left showing the image, title, excerpt and author info and on the right, just the title, date and author information. I want it to show the remaining info in the right column (stacked on one another). So far I have the one recent post on the left and the next post title on the left column but the third does not stay in the right column but rather moves to the left under the recent post #1.
What I have:
[](https://i.stack.imgur.com/2U8sq.png)
What I am trying to achieve:
[](https://i.stack.imgur.com/lmTR6.png)
Here is my code:
```
<div class="row">
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => 3
);
$counter = 0;
$_posts = new WP_Query($args);
?>
<?php if( $_posts->have_posts() ) : ?>
<?php while ( $_posts->have_posts() ) : $_posts->the_post(); $counter++ ?>
<?php if ( $counter === 0 || $counter === 1) : ?>
<div class="col-md-6 float-left">
<div>
<a href="<?php the_permalink(); ?>" class="mb-4 d-block"><?php if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
the_post_thumbnail( 'full' );
}
?></a>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
</div>
</div>
<?php else : ?>
<div class="col-md-6 float-right">
<div class="post-entry mb-4">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="text-muted mb-3 text-uppercase small"><span><?php the_time('F jS, Y'); ?></span> by <a href="<?php the_permalink(); ?>" class="by"><?php the_author( ', ' ); ?></a></p>
</div>
</div>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; wp_reset_postdata(); ?>
</div>
</div>
```
Any help would be greatly appreciated. Thank you. | Try this
```
<div class="row">
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => 3
);
$counter = 0;
$_posts = new WP_Query($args);
?>
<?php if( $_posts->have_posts() ) : ?>
<?php while ( $_posts->have_posts() ) : $_posts->the_post(); $counter++ ?>
<?php if ( $counter === 0 || $counter === 1) : ?>
<div class="col-md-6 float-left">
<div>
<a href="<?php the_permalink(); ?>" class="mb-4 d-block"><?php if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
the_post_thumbnail( 'full' );
}
?></a>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
</div>
</div>
<div class="col-md-6 float-right">
<?php else : ?>
<div class="post-entry mb-4">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="text-muted mb-3 text-uppercase small"><span><?php the_time('F jS, Y'); ?></span> by <a href="<?php the_permalink(); ?>" class="by"><?php the_author( ', ' ); ?></a></p>
</div>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; wp_reset_postdata(); ?>
</div>
</div>
</div>
``` |
351,725 | <p>Currently I’m having URL for pagination pages as:</p>
<p><a href="http://www.example.com/category_name/page/2" rel="nofollow noreferrer">http://www.example.com/category_name/page/2</a></p>
<p>But I need to change this URL structure as:</p>
<p><a href="http://www.example.com/category_name/?page=2" rel="nofollow noreferrer">http://www.example.com/category_name/?page=2</a></p>
<p>etc.</p>
<p>any solution?</p>
| [
{
"answer_id": 351719,
"author": "Orbital",
"author_id": 28956,
"author_profile": "https://wordpress.stackexchange.com/users/28956",
"pm_score": 2,
"selected": true,
"text": "<p>Try this</p>\n\n<pre><code><div class=\"row\">\n\n <?php \n\n $args = array(\n 'post_type' => 'post',\n 'posts_per_page' => 3\n );\n\n $counter = 0;\n\n\n $_posts = new WP_Query($args);\n\n ?>\n\n\n <?php if( $_posts->have_posts() ) : ?>\n\n <?php while ( $_posts->have_posts() ) : $_posts->the_post(); $counter++ ?>\n\n <?php if ( $counter === 0 || $counter === 1) : ?>\n\n <div class=\"col-md-6 float-left\">\n <div>\n <a href=\"<?php the_permalink(); ?>\" class=\"mb-4 d-block\"><?php if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.\n the_post_thumbnail( 'full' );\n }\n ?></a>\n <h2><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></h2>\n <?php the_excerpt(); ?>\n </div>\n </div>\n\n <div class=\"col-md-6 float-right\">\n <?php else : ?>\n\n\n\n <div class=\"post-entry mb-4\">\n <h2><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></h2>\n <p class=\"text-muted mb-3 text-uppercase small\"><span><?php the_time('F jS, Y'); ?></span> by <a href=\"<?php the_permalink(); ?>\" class=\"by\"><?php the_author( ', ' ); ?></a></p>\n </div>\n\n\n\n\n <?php endif; ?>\n <?php endwhile; ?>\n\n <?php endif; wp_reset_postdata(); ?>\n </div>\n\n </div>\n</div>\n</code></pre>\n"
},
{
"answer_id": 351721,
"author": "Gopala krishnan",
"author_id": 168404,
"author_profile": "https://wordpress.stackexchange.com/users/168404",
"pm_score": 0,
"selected": false,
"text": "<p>Hope this code will helpfull for you, this code will print output in zig zag(ie. one post is left and next one left ) and so on. </p>\n\n<pre><code><div class=\"row\"><?php \n$args = array(\n 'post_type' => 'post',\n 'posts_per_page' => 3\n);\n$counter = 1;\n$_posts = new WP_Query($args);\nif( $_posts->have_posts() ) : \n while ( $_posts->have_posts() ) : $_posts->the_post(); \n if ( $counter%2 !=0) : ?>\n <div class=\"col-md-6 float-left\">\n <div>\n <a href=\"<?php the_permalink(); ?>\" class=\"mb-4 d-block\"><?php if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.\n the_post_thumbnail( 'full' );\n }\n ?></a>\n <h2><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></h2>\n <?php the_excerpt(); ?>\n </div>\n </div><?php \n else : ?>\n <div class=\"col-md-6 float-right\">\n <div class=\"post-entry mb-4\">\n <h2><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></h2>\n <p class=\"text-muted mb-3 text-uppercase small\"><span><?php the_time('F jS, Y'); ?></span> by <a href=\"<?php the_permalink(); ?>\" class=\"by\"><?php the_author( ', ' ); ?></a></p>\n </div>\n </div><?php \n endif;\n $counter++;\n endwhile; \nendif; \nwp_reset_postdata(); ?></div>\n</code></pre>\n"
}
] | 2019/11/02 | [
"https://wordpress.stackexchange.com/questions/351725",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/177740/"
] | Currently I’m having URL for pagination pages as:
<http://www.example.com/category_name/page/2>
But I need to change this URL structure as:
<http://www.example.com/category_name/?page=2>
etc.
any solution? | Try this
```
<div class="row">
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => 3
);
$counter = 0;
$_posts = new WP_Query($args);
?>
<?php if( $_posts->have_posts() ) : ?>
<?php while ( $_posts->have_posts() ) : $_posts->the_post(); $counter++ ?>
<?php if ( $counter === 0 || $counter === 1) : ?>
<div class="col-md-6 float-left">
<div>
<a href="<?php the_permalink(); ?>" class="mb-4 d-block"><?php if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
the_post_thumbnail( 'full' );
}
?></a>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
</div>
</div>
<div class="col-md-6 float-right">
<?php else : ?>
<div class="post-entry mb-4">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="text-muted mb-3 text-uppercase small"><span><?php the_time('F jS, Y'); ?></span> by <a href="<?php the_permalink(); ?>" class="by"><?php the_author( ', ' ); ?></a></p>
</div>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; wp_reset_postdata(); ?>
</div>
</div>
</div>
``` |
351,787 | <p>Adapting some old SEO module (which was written for TinyMCE), I have to access the current post title and post content via JavaScript. I have been avoiding Gutenberg in the past, but it seems like this will be no longer possible.</p>
<p>Within the old SEO module there are the following lines in the <code>admin.js</code>:</p>
<pre><code>var title = $('#title').val().trim();
var content = $('#content').val().trim();
</code></pre>
<p>Those fields do not exist in Gutenberg anymore. I have tried to find the correct way to do this in the docs, but no luck so far. I have found:</p>
<pre><code>wp.data.select("core/editor").getBlocks()
wp.data.select("core")
</code></pre>
<p>But both seem to be empty arrays in my case (although this post has content). I basically just need a way to get the textual contents of all blocks (and maybe separately from the main post title if this is possible). Who knows how to do that?</p>
| [
{
"answer_id": 351788,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>If we do this in the browser dev tools console:</p>\n<pre class=\"lang-js prettyprint-override\"><code>var b = wp.data.select("core/editor");\n</code></pre>\n<p>We can then inspect the <code>b</code> variable to see what functions it exposes via autocomplete, or debugging tools.</p>\n<p>Notice, I didn't call <code>getBlocks()</code>, the post title has never been a part of the post content, why would that change now?</p>\n<p>A look around gave me this <code>a.getCurrentPost()</code>, which returns a post object with a post title, but this will be the original post title, not the current post title, and doesn't get updated as the user edits the title</p>\n<p>A quick google however gave an identical Question with an indepth answer on stackoverflow: <a href=\"https://stackoverflow.com/questions/51674293/use-page-title-in-gutenberg-custom-banner-block\">https://stackoverflow.com/questions/51674293/use-page-title-in-gutenberg-custom-banner-block</a></p>\n<pre class=\"lang-js prettyprint-override\"><code>const title = select("core/editor").getEditedPostAttribute( 'title' );\n</code></pre>\n"
},
{
"answer_id": 395197,
"author": "JonShipman",
"author_id": 121885,
"author_profile": "https://wordpress.stackexchange.com/users/121885",
"pm_score": 1,
"selected": false,
"text": "<p>Just updating this answer for 2021. You'll want to be familiar with node and optionally yarn (personal preference, but you can usually sub <code>npm run x</code> for <code>yarn x</code> scripts).</p>\n<p>Initialize the folder with <code>yarn init</code> it'll step you through some questions. Typically, the project name will be the same as your plugin or theme name and the version will be the same as the plugin or theme version. Afterwards you'll get a <code>package.json</code>. Now to add the packages.</p>\n<p>In a command prompt/terminal we'll want to <code>yarn add @wordpress/scripts @wordpress/data @wordpress/block-editor @wordpress/blocks</code>. If you want access to React components, there's also <code>@wordpress/element</code> you can add in.</p>\n<p>Next you'll want to create your source file that'll be the compilation start point. You can use one JS file or multiple via imports. Typically I go into it assuming multiple to avoid a refactor down the road.</p>\n<p>For grins, let's make our entrypoint <code>js/src/blocks.js</code>, relative to the project's root. Inside this file, let's import <code>registerBlockType</code> like so:</p>\n<p><code>import { registerBlockType } from '@wordpress/blocks';</code></p>\n<p>Next, let's create the directory for this SEO module, I'll go with <code>js/src/seo/</code>. These can be anything, I'm just going with the flow.</p>\n<p>We'll come back to that folder, but first lets finish the blocks.js.</p>\n<p>Import that directory's exports in blocks.js.</p>\n<p><code>import * as seo from './seo';</code></p>\n<p>And as I mentioned earlier about supporting multiple blocks in one project, we'll build an array and run registerBlockType over each import.</p>\n<pre><code>[ seo ].forEach( ( block ) => {\n if ( ! block ) {\n return;\n }\n\n const { settings, name } = block;\n registerBlockType( name, settings );\n} );\n</code></pre>\n<p>Now let's get into the actual block itself. Inside the seo folder create <code>index.js</code> and <code>block.json</code> files.</p>\n<p>Inside the <code>block.json</code> file you'll want to reference <a href=\"https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/</a>, but to get you started you need at least the following:</p>\n<pre><code>"apiVersion": 2,\n"name": "namespace/seo",\n"title": "Your SEO Block",\n"category": "widgets",\n"description": "SEO Classic Port",\n"textdomain": "namespace"\n</code></pre>\n<p>I could go on for days just talking about the blocks.json file. But this will get you started.</p>\n<p>Next is the index.js file. You'll want to start the file with the following imports:</p>\n<pre><code>import { useBlockProps } from '@wordpress/block-editor';\nimport { useSelect } from '@wordpress/data';\nimport metadata from './block.json';\n</code></pre>\n<p>Now lets use them.</p>\n<pre><code>const { name } = metadata;\nexport { name }\n\nexport const settings = {\n ...metadata,\n edit: function() {\n const { title, content } = useSelect(\n ( select ) => {\n return {\n title: select( 'core/editor' ).getEditedPostAttribute( 'title' ),\n content: select( 'core/editor' ).getEditedPostContent(),\n }\n },\n []\n );\n\n return (\n <div { ...useBlockProps() }>\n <div>Title: { title }</div>\n <div>Content: { content }</div>\n </div>\n );\n },\n save: () => null,\n};\n</code></pre>\n<p>We're exporting the name and settings objects referred in the <code>blocks.js</code> above. Also, we're doing nothing right now on save. Most of the time I use these "quick blocks" to edit a piece of post meta, so returning null is completely valid.</p>\n<p>We'll just need two more steps to round everything out. Adding our blocks.js to the package scripts and registering the script (optionally any styles as well if you import any css or sass).</p>\n<p>First the package scripts. Add the following:</p>\n<pre><code>"scripts": {\n "build": "wp-scripts build ./js/src/blocks.js --output-path=./js/build",\n "start": "wp-scripts start ./js/src/blocks.js --output-path=./js/build"\n}\n</code></pre>\n<p>With these scripts, running <code>yarn start</code> will create a development copy of your compiled JS in the src/build folder. Likewise <code>yarn build</code> will create a minified production ready compile.</p>\n<p>Finally we'll need to enqueue these files. Normally we'd use the <code>admin_enqueue_scripts</code> hook, however, you can enqueue public js with this blocks. So I like to use init. Another reason to use init, we're going to use <code>register_block_type_from_metadata</code>.</p>\n<p>Include this in your plugin file or your functions.php (for themes). I'm assuming plugin for the sake of verbosity. You'll need to change the plugin reference function for theme friendly ones.</p>\n<pre><code>function register_block_files() {\n $asset_file = include plugin_dir_path( __FILE__ ) . 'js/build/blocks.asset.php';\n\n wp_register_script(\n 'your-blocks',\n plugins_url( 'js/build/blocks.js', __FILE__ ),\n $asset_file['dependencies'],\n $asset_file['version'],\n false\n );\n\n $folders = array(\n 'seo',\n );\n\n foreach ( $folders as $folder ) {\n register_block_type_from_metadata(\n plugin_dir_path( __FILE__ ) . 'js/src/' . $folder . '/block.json',\n array(\n 'editor_script' => 'your-blocks',\n )\n );\n } \n}\n\nadd_action( 'init', 'register_block_files' );\n</code></pre>\n<p>That should be all that there's to it! You'll be creating a block that loads under the widgets and will print Title: The Post Title, and Content: The post's html content. Obviously you can do what you want inside the edit function. Usually I split save and import apart into separate files and import them.</p>\n"
}
] | 2019/11/03 | [
"https://wordpress.stackexchange.com/questions/351787",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12035/"
] | Adapting some old SEO module (which was written for TinyMCE), I have to access the current post title and post content via JavaScript. I have been avoiding Gutenberg in the past, but it seems like this will be no longer possible.
Within the old SEO module there are the following lines in the `admin.js`:
```
var title = $('#title').val().trim();
var content = $('#content').val().trim();
```
Those fields do not exist in Gutenberg anymore. I have tried to find the correct way to do this in the docs, but no luck so far. I have found:
```
wp.data.select("core/editor").getBlocks()
wp.data.select("core")
```
But both seem to be empty arrays in my case (although this post has content). I basically just need a way to get the textual contents of all blocks (and maybe separately from the main post title if this is possible). Who knows how to do that? | If we do this in the browser dev tools console:
```js
var b = wp.data.select("core/editor");
```
We can then inspect the `b` variable to see what functions it exposes via autocomplete, or debugging tools.
Notice, I didn't call `getBlocks()`, the post title has never been a part of the post content, why would that change now?
A look around gave me this `a.getCurrentPost()`, which returns a post object with a post title, but this will be the original post title, not the current post title, and doesn't get updated as the user edits the title
A quick google however gave an identical Question with an indepth answer on stackoverflow: <https://stackoverflow.com/questions/51674293/use-page-title-in-gutenberg-custom-banner-block>
```js
const title = select("core/editor").getEditedPostAttribute( 'title' );
``` |
351,804 | <p>I'd like to hide the "add to cart" & price for WooCommerce products in the 'Services' category.</p>
<p>I've tried the following code in my child theme's functions.php, but <a href="https://pureblissmoonhealer.com/product-category/services/" rel="nofollow noreferrer">https://pureblissmoonhealer.com/product-category/services/</a> still displays "add to cart" & price.</p>
<p>Help appreciated.</p>
<pre><code>function insight_hide_price_add_cart_not_logged_in() {
if (! is_user_logged_in()) {
if (is_product_category('Services')) {
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
add_action( 'woocommerce_single_product_summary', 'insight_print_register_to_see', 31 );
add_action( 'woocommerce_after_shop_loop_item', 'insight_print_register_to_see', 11 );
}
}
}
function insight_print_register_to_see() {
echo '<a href="' . get_permalink(wc_get_page_id('myaccount')) . '">' . __('Register to see prices', 'theme_name') . '</a>';
}
add_action( 'init', 'insight_hide_price_add_cart_not_logged_in' );
</code></pre>
| [
{
"answer_id": 351788,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>If we do this in the browser dev tools console:</p>\n<pre class=\"lang-js prettyprint-override\"><code>var b = wp.data.select("core/editor");\n</code></pre>\n<p>We can then inspect the <code>b</code> variable to see what functions it exposes via autocomplete, or debugging tools.</p>\n<p>Notice, I didn't call <code>getBlocks()</code>, the post title has never been a part of the post content, why would that change now?</p>\n<p>A look around gave me this <code>a.getCurrentPost()</code>, which returns a post object with a post title, but this will be the original post title, not the current post title, and doesn't get updated as the user edits the title</p>\n<p>A quick google however gave an identical Question with an indepth answer on stackoverflow: <a href=\"https://stackoverflow.com/questions/51674293/use-page-title-in-gutenberg-custom-banner-block\">https://stackoverflow.com/questions/51674293/use-page-title-in-gutenberg-custom-banner-block</a></p>\n<pre class=\"lang-js prettyprint-override\"><code>const title = select("core/editor").getEditedPostAttribute( 'title' );\n</code></pre>\n"
},
{
"answer_id": 395197,
"author": "JonShipman",
"author_id": 121885,
"author_profile": "https://wordpress.stackexchange.com/users/121885",
"pm_score": 1,
"selected": false,
"text": "<p>Just updating this answer for 2021. You'll want to be familiar with node and optionally yarn (personal preference, but you can usually sub <code>npm run x</code> for <code>yarn x</code> scripts).</p>\n<p>Initialize the folder with <code>yarn init</code> it'll step you through some questions. Typically, the project name will be the same as your plugin or theme name and the version will be the same as the plugin or theme version. Afterwards you'll get a <code>package.json</code>. Now to add the packages.</p>\n<p>In a command prompt/terminal we'll want to <code>yarn add @wordpress/scripts @wordpress/data @wordpress/block-editor @wordpress/blocks</code>. If you want access to React components, there's also <code>@wordpress/element</code> you can add in.</p>\n<p>Next you'll want to create your source file that'll be the compilation start point. You can use one JS file or multiple via imports. Typically I go into it assuming multiple to avoid a refactor down the road.</p>\n<p>For grins, let's make our entrypoint <code>js/src/blocks.js</code>, relative to the project's root. Inside this file, let's import <code>registerBlockType</code> like so:</p>\n<p><code>import { registerBlockType } from '@wordpress/blocks';</code></p>\n<p>Next, let's create the directory for this SEO module, I'll go with <code>js/src/seo/</code>. These can be anything, I'm just going with the flow.</p>\n<p>We'll come back to that folder, but first lets finish the blocks.js.</p>\n<p>Import that directory's exports in blocks.js.</p>\n<p><code>import * as seo from './seo';</code></p>\n<p>And as I mentioned earlier about supporting multiple blocks in one project, we'll build an array and run registerBlockType over each import.</p>\n<pre><code>[ seo ].forEach( ( block ) => {\n if ( ! block ) {\n return;\n }\n\n const { settings, name } = block;\n registerBlockType( name, settings );\n} );\n</code></pre>\n<p>Now let's get into the actual block itself. Inside the seo folder create <code>index.js</code> and <code>block.json</code> files.</p>\n<p>Inside the <code>block.json</code> file you'll want to reference <a href=\"https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/</a>, but to get you started you need at least the following:</p>\n<pre><code>"apiVersion": 2,\n"name": "namespace/seo",\n"title": "Your SEO Block",\n"category": "widgets",\n"description": "SEO Classic Port",\n"textdomain": "namespace"\n</code></pre>\n<p>I could go on for days just talking about the blocks.json file. But this will get you started.</p>\n<p>Next is the index.js file. You'll want to start the file with the following imports:</p>\n<pre><code>import { useBlockProps } from '@wordpress/block-editor';\nimport { useSelect } from '@wordpress/data';\nimport metadata from './block.json';\n</code></pre>\n<p>Now lets use them.</p>\n<pre><code>const { name } = metadata;\nexport { name }\n\nexport const settings = {\n ...metadata,\n edit: function() {\n const { title, content } = useSelect(\n ( select ) => {\n return {\n title: select( 'core/editor' ).getEditedPostAttribute( 'title' ),\n content: select( 'core/editor' ).getEditedPostContent(),\n }\n },\n []\n );\n\n return (\n <div { ...useBlockProps() }>\n <div>Title: { title }</div>\n <div>Content: { content }</div>\n </div>\n );\n },\n save: () => null,\n};\n</code></pre>\n<p>We're exporting the name and settings objects referred in the <code>blocks.js</code> above. Also, we're doing nothing right now on save. Most of the time I use these "quick blocks" to edit a piece of post meta, so returning null is completely valid.</p>\n<p>We'll just need two more steps to round everything out. Adding our blocks.js to the package scripts and registering the script (optionally any styles as well if you import any css or sass).</p>\n<p>First the package scripts. Add the following:</p>\n<pre><code>"scripts": {\n "build": "wp-scripts build ./js/src/blocks.js --output-path=./js/build",\n "start": "wp-scripts start ./js/src/blocks.js --output-path=./js/build"\n}\n</code></pre>\n<p>With these scripts, running <code>yarn start</code> will create a development copy of your compiled JS in the src/build folder. Likewise <code>yarn build</code> will create a minified production ready compile.</p>\n<p>Finally we'll need to enqueue these files. Normally we'd use the <code>admin_enqueue_scripts</code> hook, however, you can enqueue public js with this blocks. So I like to use init. Another reason to use init, we're going to use <code>register_block_type_from_metadata</code>.</p>\n<p>Include this in your plugin file or your functions.php (for themes). I'm assuming plugin for the sake of verbosity. You'll need to change the plugin reference function for theme friendly ones.</p>\n<pre><code>function register_block_files() {\n $asset_file = include plugin_dir_path( __FILE__ ) . 'js/build/blocks.asset.php';\n\n wp_register_script(\n 'your-blocks',\n plugins_url( 'js/build/blocks.js', __FILE__ ),\n $asset_file['dependencies'],\n $asset_file['version'],\n false\n );\n\n $folders = array(\n 'seo',\n );\n\n foreach ( $folders as $folder ) {\n register_block_type_from_metadata(\n plugin_dir_path( __FILE__ ) . 'js/src/' . $folder . '/block.json',\n array(\n 'editor_script' => 'your-blocks',\n )\n );\n } \n}\n\nadd_action( 'init', 'register_block_files' );\n</code></pre>\n<p>That should be all that there's to it! You'll be creating a block that loads under the widgets and will print Title: The Post Title, and Content: The post's html content. Obviously you can do what you want inside the edit function. Usually I split save and import apart into separate files and import them.</p>\n"
}
] | 2019/11/04 | [
"https://wordpress.stackexchange.com/questions/351804",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147186/"
] | I'd like to hide the "add to cart" & price for WooCommerce products in the 'Services' category.
I've tried the following code in my child theme's functions.php, but <https://pureblissmoonhealer.com/product-category/services/> still displays "add to cart" & price.
Help appreciated.
```
function insight_hide_price_add_cart_not_logged_in() {
if (! is_user_logged_in()) {
if (is_product_category('Services')) {
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
add_action( 'woocommerce_single_product_summary', 'insight_print_register_to_see', 31 );
add_action( 'woocommerce_after_shop_loop_item', 'insight_print_register_to_see', 11 );
}
}
}
function insight_print_register_to_see() {
echo '<a href="' . get_permalink(wc_get_page_id('myaccount')) . '">' . __('Register to see prices', 'theme_name') . '</a>';
}
add_action( 'init', 'insight_hide_price_add_cart_not_logged_in' );
``` | If we do this in the browser dev tools console:
```js
var b = wp.data.select("core/editor");
```
We can then inspect the `b` variable to see what functions it exposes via autocomplete, or debugging tools.
Notice, I didn't call `getBlocks()`, the post title has never been a part of the post content, why would that change now?
A look around gave me this `a.getCurrentPost()`, which returns a post object with a post title, but this will be the original post title, not the current post title, and doesn't get updated as the user edits the title
A quick google however gave an identical Question with an indepth answer on stackoverflow: <https://stackoverflow.com/questions/51674293/use-page-title-in-gutenberg-custom-banner-block>
```js
const title = select("core/editor").getEditedPostAttribute( 'title' );
``` |
351,932 | <p>Last week I added WooCommerce and YITH (catalog mode). All seemed fine. Today, I log in and I no longer see (in the left admin sidebar) the following items/tools:</p>
<ul>
<li>‘Appearance’ (with theme and such)</li>
<li>Plugins</li>
<li>WooCommerce</li>
<li>user Admin</li>
<li>Theme admin </li>
<li>(maybe more, but those I remember using before and they are all gone). </li>
</ul>
<p>I fear the site/account was hacked and I’m no longer admin, only user. Is that possible??? Or is this related to WooCommerce or YITH?</p>
<p>How do I fix it?</p>
<p>(using GoDaddy managed WP hosting)</p>
| [
{
"answer_id": 351788,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>If we do this in the browser dev tools console:</p>\n<pre class=\"lang-js prettyprint-override\"><code>var b = wp.data.select("core/editor");\n</code></pre>\n<p>We can then inspect the <code>b</code> variable to see what functions it exposes via autocomplete, or debugging tools.</p>\n<p>Notice, I didn't call <code>getBlocks()</code>, the post title has never been a part of the post content, why would that change now?</p>\n<p>A look around gave me this <code>a.getCurrentPost()</code>, which returns a post object with a post title, but this will be the original post title, not the current post title, and doesn't get updated as the user edits the title</p>\n<p>A quick google however gave an identical Question with an indepth answer on stackoverflow: <a href=\"https://stackoverflow.com/questions/51674293/use-page-title-in-gutenberg-custom-banner-block\">https://stackoverflow.com/questions/51674293/use-page-title-in-gutenberg-custom-banner-block</a></p>\n<pre class=\"lang-js prettyprint-override\"><code>const title = select("core/editor").getEditedPostAttribute( 'title' );\n</code></pre>\n"
},
{
"answer_id": 395197,
"author": "JonShipman",
"author_id": 121885,
"author_profile": "https://wordpress.stackexchange.com/users/121885",
"pm_score": 1,
"selected": false,
"text": "<p>Just updating this answer for 2021. You'll want to be familiar with node and optionally yarn (personal preference, but you can usually sub <code>npm run x</code> for <code>yarn x</code> scripts).</p>\n<p>Initialize the folder with <code>yarn init</code> it'll step you through some questions. Typically, the project name will be the same as your plugin or theme name and the version will be the same as the plugin or theme version. Afterwards you'll get a <code>package.json</code>. Now to add the packages.</p>\n<p>In a command prompt/terminal we'll want to <code>yarn add @wordpress/scripts @wordpress/data @wordpress/block-editor @wordpress/blocks</code>. If you want access to React components, there's also <code>@wordpress/element</code> you can add in.</p>\n<p>Next you'll want to create your source file that'll be the compilation start point. You can use one JS file or multiple via imports. Typically I go into it assuming multiple to avoid a refactor down the road.</p>\n<p>For grins, let's make our entrypoint <code>js/src/blocks.js</code>, relative to the project's root. Inside this file, let's import <code>registerBlockType</code> like so:</p>\n<p><code>import { registerBlockType } from '@wordpress/blocks';</code></p>\n<p>Next, let's create the directory for this SEO module, I'll go with <code>js/src/seo/</code>. These can be anything, I'm just going with the flow.</p>\n<p>We'll come back to that folder, but first lets finish the blocks.js.</p>\n<p>Import that directory's exports in blocks.js.</p>\n<p><code>import * as seo from './seo';</code></p>\n<p>And as I mentioned earlier about supporting multiple blocks in one project, we'll build an array and run registerBlockType over each import.</p>\n<pre><code>[ seo ].forEach( ( block ) => {\n if ( ! block ) {\n return;\n }\n\n const { settings, name } = block;\n registerBlockType( name, settings );\n} );\n</code></pre>\n<p>Now let's get into the actual block itself. Inside the seo folder create <code>index.js</code> and <code>block.json</code> files.</p>\n<p>Inside the <code>block.json</code> file you'll want to reference <a href=\"https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/</a>, but to get you started you need at least the following:</p>\n<pre><code>"apiVersion": 2,\n"name": "namespace/seo",\n"title": "Your SEO Block",\n"category": "widgets",\n"description": "SEO Classic Port",\n"textdomain": "namespace"\n</code></pre>\n<p>I could go on for days just talking about the blocks.json file. But this will get you started.</p>\n<p>Next is the index.js file. You'll want to start the file with the following imports:</p>\n<pre><code>import { useBlockProps } from '@wordpress/block-editor';\nimport { useSelect } from '@wordpress/data';\nimport metadata from './block.json';\n</code></pre>\n<p>Now lets use them.</p>\n<pre><code>const { name } = metadata;\nexport { name }\n\nexport const settings = {\n ...metadata,\n edit: function() {\n const { title, content } = useSelect(\n ( select ) => {\n return {\n title: select( 'core/editor' ).getEditedPostAttribute( 'title' ),\n content: select( 'core/editor' ).getEditedPostContent(),\n }\n },\n []\n );\n\n return (\n <div { ...useBlockProps() }>\n <div>Title: { title }</div>\n <div>Content: { content }</div>\n </div>\n );\n },\n save: () => null,\n};\n</code></pre>\n<p>We're exporting the name and settings objects referred in the <code>blocks.js</code> above. Also, we're doing nothing right now on save. Most of the time I use these "quick blocks" to edit a piece of post meta, so returning null is completely valid.</p>\n<p>We'll just need two more steps to round everything out. Adding our blocks.js to the package scripts and registering the script (optionally any styles as well if you import any css or sass).</p>\n<p>First the package scripts. Add the following:</p>\n<pre><code>"scripts": {\n "build": "wp-scripts build ./js/src/blocks.js --output-path=./js/build",\n "start": "wp-scripts start ./js/src/blocks.js --output-path=./js/build"\n}\n</code></pre>\n<p>With these scripts, running <code>yarn start</code> will create a development copy of your compiled JS in the src/build folder. Likewise <code>yarn build</code> will create a minified production ready compile.</p>\n<p>Finally we'll need to enqueue these files. Normally we'd use the <code>admin_enqueue_scripts</code> hook, however, you can enqueue public js with this blocks. So I like to use init. Another reason to use init, we're going to use <code>register_block_type_from_metadata</code>.</p>\n<p>Include this in your plugin file or your functions.php (for themes). I'm assuming plugin for the sake of verbosity. You'll need to change the plugin reference function for theme friendly ones.</p>\n<pre><code>function register_block_files() {\n $asset_file = include plugin_dir_path( __FILE__ ) . 'js/build/blocks.asset.php';\n\n wp_register_script(\n 'your-blocks',\n plugins_url( 'js/build/blocks.js', __FILE__ ),\n $asset_file['dependencies'],\n $asset_file['version'],\n false\n );\n\n $folders = array(\n 'seo',\n );\n\n foreach ( $folders as $folder ) {\n register_block_type_from_metadata(\n plugin_dir_path( __FILE__ ) . 'js/src/' . $folder . '/block.json',\n array(\n 'editor_script' => 'your-blocks',\n )\n );\n } \n}\n\nadd_action( 'init', 'register_block_files' );\n</code></pre>\n<p>That should be all that there's to it! You'll be creating a block that loads under the widgets and will print Title: The Post Title, and Content: The post's html content. Obviously you can do what you want inside the edit function. Usually I split save and import apart into separate files and import them.</p>\n"
}
] | 2019/11/05 | [
"https://wordpress.stackexchange.com/questions/351932",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/177895/"
] | Last week I added WooCommerce and YITH (catalog mode). All seemed fine. Today, I log in and I no longer see (in the left admin sidebar) the following items/tools:
* ‘Appearance’ (with theme and such)
* Plugins
* WooCommerce
* user Admin
* Theme admin
* (maybe more, but those I remember using before and they are all gone).
I fear the site/account was hacked and I’m no longer admin, only user. Is that possible??? Or is this related to WooCommerce or YITH?
How do I fix it?
(using GoDaddy managed WP hosting) | If we do this in the browser dev tools console:
```js
var b = wp.data.select("core/editor");
```
We can then inspect the `b` variable to see what functions it exposes via autocomplete, or debugging tools.
Notice, I didn't call `getBlocks()`, the post title has never been a part of the post content, why would that change now?
A look around gave me this `a.getCurrentPost()`, which returns a post object with a post title, but this will be the original post title, not the current post title, and doesn't get updated as the user edits the title
A quick google however gave an identical Question with an indepth answer on stackoverflow: <https://stackoverflow.com/questions/51674293/use-page-title-in-gutenberg-custom-banner-block>
```js
const title = select("core/editor").getEditedPostAttribute( 'title' );
``` |
351,967 | <p>Im using this function to add button "Order again" in actions</p>
<pre><code>function cs_add_order_again_to_my_orders_actions( $actions, $order ) {
$payment_method = method_exists($order, 'get_payment_method') ? $order->get_payment_method() : $order->payment_method;
if ($payment_method === 'cod') {
$actions['order-again'] = array(
'url' => wp_nonce_url( add_query_arg( 'order_again', $order->id ) , 'woocommerce-order_again' ),
'name' => __( 'Transformer en commande', 'woocommerce' )
);
}
return $actions;
}
add_filter( 'woocommerce_my_account_my_orders_actions', 'cs_add_order_again_to_my_orders_actions', 50, 2 );
</code></pre>
<p>It works Fine but I want to display it also in View-order page</p>
<p>How I can extract a shortcode to display the button inside "View Order page"</p>
| [
{
"answer_id": 351788,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>If we do this in the browser dev tools console:</p>\n<pre class=\"lang-js prettyprint-override\"><code>var b = wp.data.select("core/editor");\n</code></pre>\n<p>We can then inspect the <code>b</code> variable to see what functions it exposes via autocomplete, or debugging tools.</p>\n<p>Notice, I didn't call <code>getBlocks()</code>, the post title has never been a part of the post content, why would that change now?</p>\n<p>A look around gave me this <code>a.getCurrentPost()</code>, which returns a post object with a post title, but this will be the original post title, not the current post title, and doesn't get updated as the user edits the title</p>\n<p>A quick google however gave an identical Question with an indepth answer on stackoverflow: <a href=\"https://stackoverflow.com/questions/51674293/use-page-title-in-gutenberg-custom-banner-block\">https://stackoverflow.com/questions/51674293/use-page-title-in-gutenberg-custom-banner-block</a></p>\n<pre class=\"lang-js prettyprint-override\"><code>const title = select("core/editor").getEditedPostAttribute( 'title' );\n</code></pre>\n"
},
{
"answer_id": 395197,
"author": "JonShipman",
"author_id": 121885,
"author_profile": "https://wordpress.stackexchange.com/users/121885",
"pm_score": 1,
"selected": false,
"text": "<p>Just updating this answer for 2021. You'll want to be familiar with node and optionally yarn (personal preference, but you can usually sub <code>npm run x</code> for <code>yarn x</code> scripts).</p>\n<p>Initialize the folder with <code>yarn init</code> it'll step you through some questions. Typically, the project name will be the same as your plugin or theme name and the version will be the same as the plugin or theme version. Afterwards you'll get a <code>package.json</code>. Now to add the packages.</p>\n<p>In a command prompt/terminal we'll want to <code>yarn add @wordpress/scripts @wordpress/data @wordpress/block-editor @wordpress/blocks</code>. If you want access to React components, there's also <code>@wordpress/element</code> you can add in.</p>\n<p>Next you'll want to create your source file that'll be the compilation start point. You can use one JS file or multiple via imports. Typically I go into it assuming multiple to avoid a refactor down the road.</p>\n<p>For grins, let's make our entrypoint <code>js/src/blocks.js</code>, relative to the project's root. Inside this file, let's import <code>registerBlockType</code> like so:</p>\n<p><code>import { registerBlockType } from '@wordpress/blocks';</code></p>\n<p>Next, let's create the directory for this SEO module, I'll go with <code>js/src/seo/</code>. These can be anything, I'm just going with the flow.</p>\n<p>We'll come back to that folder, but first lets finish the blocks.js.</p>\n<p>Import that directory's exports in blocks.js.</p>\n<p><code>import * as seo from './seo';</code></p>\n<p>And as I mentioned earlier about supporting multiple blocks in one project, we'll build an array and run registerBlockType over each import.</p>\n<pre><code>[ seo ].forEach( ( block ) => {\n if ( ! block ) {\n return;\n }\n\n const { settings, name } = block;\n registerBlockType( name, settings );\n} );\n</code></pre>\n<p>Now let's get into the actual block itself. Inside the seo folder create <code>index.js</code> and <code>block.json</code> files.</p>\n<p>Inside the <code>block.json</code> file you'll want to reference <a href=\"https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/</a>, but to get you started you need at least the following:</p>\n<pre><code>"apiVersion": 2,\n"name": "namespace/seo",\n"title": "Your SEO Block",\n"category": "widgets",\n"description": "SEO Classic Port",\n"textdomain": "namespace"\n</code></pre>\n<p>I could go on for days just talking about the blocks.json file. But this will get you started.</p>\n<p>Next is the index.js file. You'll want to start the file with the following imports:</p>\n<pre><code>import { useBlockProps } from '@wordpress/block-editor';\nimport { useSelect } from '@wordpress/data';\nimport metadata from './block.json';\n</code></pre>\n<p>Now lets use them.</p>\n<pre><code>const { name } = metadata;\nexport { name }\n\nexport const settings = {\n ...metadata,\n edit: function() {\n const { title, content } = useSelect(\n ( select ) => {\n return {\n title: select( 'core/editor' ).getEditedPostAttribute( 'title' ),\n content: select( 'core/editor' ).getEditedPostContent(),\n }\n },\n []\n );\n\n return (\n <div { ...useBlockProps() }>\n <div>Title: { title }</div>\n <div>Content: { content }</div>\n </div>\n );\n },\n save: () => null,\n};\n</code></pre>\n<p>We're exporting the name and settings objects referred in the <code>blocks.js</code> above. Also, we're doing nothing right now on save. Most of the time I use these "quick blocks" to edit a piece of post meta, so returning null is completely valid.</p>\n<p>We'll just need two more steps to round everything out. Adding our blocks.js to the package scripts and registering the script (optionally any styles as well if you import any css or sass).</p>\n<p>First the package scripts. Add the following:</p>\n<pre><code>"scripts": {\n "build": "wp-scripts build ./js/src/blocks.js --output-path=./js/build",\n "start": "wp-scripts start ./js/src/blocks.js --output-path=./js/build"\n}\n</code></pre>\n<p>With these scripts, running <code>yarn start</code> will create a development copy of your compiled JS in the src/build folder. Likewise <code>yarn build</code> will create a minified production ready compile.</p>\n<p>Finally we'll need to enqueue these files. Normally we'd use the <code>admin_enqueue_scripts</code> hook, however, you can enqueue public js with this blocks. So I like to use init. Another reason to use init, we're going to use <code>register_block_type_from_metadata</code>.</p>\n<p>Include this in your plugin file or your functions.php (for themes). I'm assuming plugin for the sake of verbosity. You'll need to change the plugin reference function for theme friendly ones.</p>\n<pre><code>function register_block_files() {\n $asset_file = include plugin_dir_path( __FILE__ ) . 'js/build/blocks.asset.php';\n\n wp_register_script(\n 'your-blocks',\n plugins_url( 'js/build/blocks.js', __FILE__ ),\n $asset_file['dependencies'],\n $asset_file['version'],\n false\n );\n\n $folders = array(\n 'seo',\n );\n\n foreach ( $folders as $folder ) {\n register_block_type_from_metadata(\n plugin_dir_path( __FILE__ ) . 'js/src/' . $folder . '/block.json',\n array(\n 'editor_script' => 'your-blocks',\n )\n );\n } \n}\n\nadd_action( 'init', 'register_block_files' );\n</code></pre>\n<p>That should be all that there's to it! You'll be creating a block that loads under the widgets and will print Title: The Post Title, and Content: The post's html content. Obviously you can do what you want inside the edit function. Usually I split save and import apart into separate files and import them.</p>\n"
}
] | 2019/11/05 | [
"https://wordpress.stackexchange.com/questions/351967",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75829/"
] | Im using this function to add button "Order again" in actions
```
function cs_add_order_again_to_my_orders_actions( $actions, $order ) {
$payment_method = method_exists($order, 'get_payment_method') ? $order->get_payment_method() : $order->payment_method;
if ($payment_method === 'cod') {
$actions['order-again'] = array(
'url' => wp_nonce_url( add_query_arg( 'order_again', $order->id ) , 'woocommerce-order_again' ),
'name' => __( 'Transformer en commande', 'woocommerce' )
);
}
return $actions;
}
add_filter( 'woocommerce_my_account_my_orders_actions', 'cs_add_order_again_to_my_orders_actions', 50, 2 );
```
It works Fine but I want to display it also in View-order page
How I can extract a shortcode to display the button inside "View Order page" | If we do this in the browser dev tools console:
```js
var b = wp.data.select("core/editor");
```
We can then inspect the `b` variable to see what functions it exposes via autocomplete, or debugging tools.
Notice, I didn't call `getBlocks()`, the post title has never been a part of the post content, why would that change now?
A look around gave me this `a.getCurrentPost()`, which returns a post object with a post title, but this will be the original post title, not the current post title, and doesn't get updated as the user edits the title
A quick google however gave an identical Question with an indepth answer on stackoverflow: <https://stackoverflow.com/questions/51674293/use-page-title-in-gutenberg-custom-banner-block>
```js
const title = select("core/editor").getEditedPostAttribute( 'title' );
``` |
351,985 | <p>I would like to ask how to remove < h1 class="page-title"> in the product page?</p>
<p><a href="https://i.stack.imgur.com/4JXDO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4JXDO.png" alt="h1 page title"></a></p>
<p>Here's my sample link: <a href="https://pwbackup.panelwallart.com/products/colorful-world-map-on-old-wall-canvas-prints-panel-wall-art/" rel="nofollow noreferrer">https://pwbackup.panelwallart.com/products/colorful-world-map-on-old-wall-canvas-prints-panel-wall-art/</a></p>
<p>It seems that two < h1> tags exist on product pages, the page title, and product title. </p>
<p>I'm using the Porto theme for my Woocommerce Site.</p>
| [
{
"answer_id": 351987,
"author": "entreprenerds",
"author_id": 177856,
"author_profile": "https://wordpress.stackexchange.com/users/177856",
"pm_score": 1,
"selected": false,
"text": "<p>There are two ways of doing this - with hooks, or by overriding the WooCommerce template file in your Child theme. First, let's look at the file override:</p>\n\n<p><strong>Method 1 - File Override</strong></p>\n\n<p>From the WooCommerce plugin folder, copy the <code>templates/single-product/title.php</code> file, and paste it into your active theme under <code>woocommerce/single-product/title.php</code></p>\n\n<p>Then, simply change this line:</p>\n\n<p><code>the_title( '<h1 itemprop=\"name\" class=\"product_title entry-title\">', '</h1>' );</code></p>\n\n<p>to:</p>\n\n<p><code>the_title( '<h2 itemprop=\"name\" class=\"product_title entry-title\">', '</h2>' );</code></p>\n\n<p><strong>Method 2 – Using Hooks</strong></p>\n\n<p>We find in the template file <code>content-single-product.php</code> that the function we need to override is called <code>woocommerce_template_single_title</code>:</p>\n\n<pre><code>/**\n * Hook: woocommerce_single_product_summary.\n *\n * @hooked woocommerce_template_single_title - 5\n * @hooked woocommerce_template_single_rating - 10\n * ...\n</code></pre>\n\n<p>WooCommerce template functions are defined in <code>includes/wc-template-functions.php</code>, and this function looks like:</p>\n\n<pre><code>if ( ! function_exists( 'woocommerce_template_single_title' ) ) {\n\n /**\n * Output the product title.\n */\n function woocommerce_template_single_title() {\n wc_get_template( 'single-product/title.php' );\n }\n}\n</code></pre>\n\n<p>What we're going to do is unhook that action, then hook in our own function - just add this code to your <code>functions.php</code> file and make any changes to the heading tags in the <code>the_title()</code> function:</p>\n\n<pre><code>remove_action( 'woocommerce_single_product_summary','woocommerce_template_single_title', 5 );\nadd_action('woocommerce_single_product_summary', 'your_custom_function_call', 5 );\nfunction your_custom_function_call() {\n the_title( '<h2 class=\"product_title entry-title\">', '</h2>' );\n}\n</code></pre>\n"
},
{
"answer_id": 352000,
"author": "James Daniel Esmatao",
"author_id": 177921,
"author_profile": "https://wordpress.stackexchange.com/users/177921",
"pm_score": 0,
"selected": false,
"text": "<p>Thank you for the response!</p>\n\n<p>I followed the first two methods, but it seems that the page title is still active on product pages. After looking for some files, I found out that there are actually \"Seven\" header file types (I chose 7 in my theme settings). I opened the file and found the culprit. Since I only want the extra h1 to be removed on the product page, I just put a condition in it.</p>\n\n<pre><code> <? php if(!is_product()){ ?>\n <div class=\"text-center<?php echo ! $hide_title ? '' : ' d-none'; ?>\">\n\n <h1 class=\"page-title<?php echo ! $sub_title ? '' : ' b-none'; ?>\"><?php echo porto_strip_script_tags( $title ); ?></h1>\n\n <?php\n if ( $sub_title ) :\n ?>\n <p class=\"page-sub-title\"><?php echo porto_strip_script_tags( $sub_title ); ?></p>\n <?php endif; ?>\n </div>\n <?php } ?>\n</code></pre>\n"
}
] | 2019/11/06 | [
"https://wordpress.stackexchange.com/questions/351985",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/177921/"
] | I would like to ask how to remove < h1 class="page-title"> in the product page?
[](https://i.stack.imgur.com/4JXDO.png)
Here's my sample link: <https://pwbackup.panelwallart.com/products/colorful-world-map-on-old-wall-canvas-prints-panel-wall-art/>
It seems that two < h1> tags exist on product pages, the page title, and product title.
I'm using the Porto theme for my Woocommerce Site. | There are two ways of doing this - with hooks, or by overriding the WooCommerce template file in your Child theme. First, let's look at the file override:
**Method 1 - File Override**
From the WooCommerce plugin folder, copy the `templates/single-product/title.php` file, and paste it into your active theme under `woocommerce/single-product/title.php`
Then, simply change this line:
`the_title( '<h1 itemprop="name" class="product_title entry-title">', '</h1>' );`
to:
`the_title( '<h2 itemprop="name" class="product_title entry-title">', '</h2>' );`
**Method 2 – Using Hooks**
We find in the template file `content-single-product.php` that the function we need to override is called `woocommerce_template_single_title`:
```
/**
* Hook: woocommerce_single_product_summary.
*
* @hooked woocommerce_template_single_title - 5
* @hooked woocommerce_template_single_rating - 10
* ...
```
WooCommerce template functions are defined in `includes/wc-template-functions.php`, and this function looks like:
```
if ( ! function_exists( 'woocommerce_template_single_title' ) ) {
/**
* Output the product title.
*/
function woocommerce_template_single_title() {
wc_get_template( 'single-product/title.php' );
}
}
```
What we're going to do is unhook that action, then hook in our own function - just add this code to your `functions.php` file and make any changes to the heading tags in the `the_title()` function:
```
remove_action( 'woocommerce_single_product_summary','woocommerce_template_single_title', 5 );
add_action('woocommerce_single_product_summary', 'your_custom_function_call', 5 );
function your_custom_function_call() {
the_title( '<h2 class="product_title entry-title">', '</h2>' );
}
``` |
351,989 | <p>I registered a custom post type "job" to create job board site. Without a plugin, how can I make the posts auto change status to pending after 90 days? I am new in WordPress & <code>PHP</code>. I tried some solutions found on the internet, but not working.</p>
<p>Sorry that I don't really good in <code>PHP</code>, I can't write code myself. For testing, do these solutions need to wait for 1 days if I change the code expired 1 day? Cos I paste the code in my <code>functions.php</code> and nothing happened.</p>
<p>Tried Solutions:
<a href="https://wordpress.stackexchange.com/questions/97031/code-to-auto-expire-posts-after-30-days">Code to auto expire posts after 30 days</a>
<a href="https://wordpress.stackexchange.com/questions/209989/automatically-move-pending-posts-after-30-days-and-update-the-post-date-when-u">Automatically move pending posts after 30 days and, update the post date, when users update the posts</a>
<a href="https://wordpress.stackexchange.com/questions/124875/set-post-to-draft-after-set-period-based-on-post-modified-date">Set post to draft after set period based on post_modified date</a>
<a href="https://wordpress.stackexchange.com/questions/152786/posts-to-expire-deleted-after-a-date">Posts to expire (deleted) after a date</a></p>
| [
{
"answer_id": 351996,
"author": "Pratikb.Simform",
"author_id": 173473,
"author_profile": "https://wordpress.stackexchange.com/users/173473",
"pm_score": 0,
"selected": false,
"text": "<p>Try Below code in your functions.php</p>\n\n<pre><code>function expire_posts() {\n global $wpdb;\n $daystogo = \"30\";\n $sql = \"UPDATE wp_posts SET `post_status` = 'draft' WHERE `post_type` = 'post' AND DATEDIFF(NOW(), `post_date`) > '$daystogo')\";\n $wpdb->query( $sql );\n}\n\nadd_action ('init' ,'expire_posts')\n</code></pre>\n"
},
{
"answer_id": 352007,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": true,
"text": "<p>This is one of those questions that seem easy enough, but are actually quite complicated. If you don't want to use an existing plugin, you'll have to write your own (and hence learn more <code>php</code> as this is not a please-write-my-code-for-free-site). Here's an outline.</p>\n\n<p>First you will need to <a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">select all the posts</a> of type job which are older than 90 days and which have status \"published\". Like this:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'job',\n 'date_query' => 'XXX',\n 'post_status' => 'published',\n 'nopaging' => true );\n$wpse251989_query = wp_query ($args);\n</code></pre>\n\n<p>At XXX you will need to write a query selecting the date 90 days ago (you cannot just subtract 90 from today, because that will get you a negative day if it is not yet april).</p>\n\n<p>Now, you must <a href=\"https://codex.wordpress.org/The%20Loop\" rel=\"nofollow noreferrer\">loop</a> through all posts you retrieve and change the status.</p>\n\n<pre><code>if ( $wpse251989_query->have_posts() ) {\n while ( $wpse251989_query->have_posts() ) {\n $wpse251989_query->the_post();\n wp_update_post(array ('post_status' => 'pending'));\n }\n }\n</code></pre>\n\n<p>If you dump this code in you <code>functions.php</code> it will be executed on every page load. You could get away with that if you have a powerful server. You could also put it behind a condition like <code>is_admin</code>, making sure it is only executed when an administrator is logged in. The safest way to make sure this is executed only once daily is using a <a href=\"https://developer.wordpress.org/reference/functions/wp_cron/\" rel=\"nofollow noreferrer\">cron job</a>, which brings you into advanced php territory.</p>\n"
}
] | 2019/11/06 | [
"https://wordpress.stackexchange.com/questions/351989",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155162/"
] | I registered a custom post type "job" to create job board site. Without a plugin, how can I make the posts auto change status to pending after 90 days? I am new in WordPress & `PHP`. I tried some solutions found on the internet, but not working.
Sorry that I don't really good in `PHP`, I can't write code myself. For testing, do these solutions need to wait for 1 days if I change the code expired 1 day? Cos I paste the code in my `functions.php` and nothing happened.
Tried Solutions:
[Code to auto expire posts after 30 days](https://wordpress.stackexchange.com/questions/97031/code-to-auto-expire-posts-after-30-days)
[Automatically move pending posts after 30 days and, update the post date, when users update the posts](https://wordpress.stackexchange.com/questions/209989/automatically-move-pending-posts-after-30-days-and-update-the-post-date-when-u)
[Set post to draft after set period based on post\_modified date](https://wordpress.stackexchange.com/questions/124875/set-post-to-draft-after-set-period-based-on-post-modified-date)
[Posts to expire (deleted) after a date](https://wordpress.stackexchange.com/questions/152786/posts-to-expire-deleted-after-a-date) | This is one of those questions that seem easy enough, but are actually quite complicated. If you don't want to use an existing plugin, you'll have to write your own (and hence learn more `php` as this is not a please-write-my-code-for-free-site). Here's an outline.
First you will need to [select all the posts](https://developer.wordpress.org/reference/classes/wp_query/) of type job which are older than 90 days and which have status "published". Like this:
```
$args = array(
'post_type' => 'job',
'date_query' => 'XXX',
'post_status' => 'published',
'nopaging' => true );
$wpse251989_query = wp_query ($args);
```
At XXX you will need to write a query selecting the date 90 days ago (you cannot just subtract 90 from today, because that will get you a negative day if it is not yet april).
Now, you must [loop](https://codex.wordpress.org/The%20Loop) through all posts you retrieve and change the status.
```
if ( $wpse251989_query->have_posts() ) {
while ( $wpse251989_query->have_posts() ) {
$wpse251989_query->the_post();
wp_update_post(array ('post_status' => 'pending'));
}
}
```
If you dump this code in you `functions.php` it will be executed on every page load. You could get away with that if you have a powerful server. You could also put it behind a condition like `is_admin`, making sure it is only executed when an administrator is logged in. The safest way to make sure this is executed only once daily is using a [cron job](https://developer.wordpress.org/reference/functions/wp_cron/), which brings you into advanced php territory. |
351,995 | <p>I am trying to load a CSS Stylesheet to ONLY the "about" page. </p>
<p>I think I am 99% correct but what is wrong is the <code>plugins_url</code> - to link to the theme folder where I keep my <code>CSS</code> can I just use simply:</p>
<pre><code>function testimonial_style() {
wp_enqueue_style( 'custom_tooltip_frontend_css', url('path-to-my.css') );
}
if(is_page( 42 )){
add_action('wp_enqueue_scripts', 'testimonial_style');
}
</code></pre>
<p>Is it ok that I reference it with <code>add_action</code> and then "scripts" which is is is really a style <strong>and not</strong> a script...</p>
| [
{
"answer_id": 351998,
"author": "Nitesh Moree",
"author_id": 148022,
"author_profile": "https://wordpress.stackexchange.com/users/148022",
"pm_score": 3,
"selected": true,
"text": "<p>Try this: \nI hope, It will works.</p>\n\n<p><strong>Explaination:</strong></p>\n\n<p>In below code in <strong>\"is_page( 42 )\"</strong> where 42 is page id of <strong>about page</strong>. So, if about page's id will be 42 then it's enqueue the stylesheet for that page only.</p>\n\n<p>Also I define particular path for this CSS file by using wordpress function <strong>get_template_directory_uri()</strong>.</p>\n\n<pre><code>function testimonial_style() {\n if ( is_page( 42 ) ) {\n wp_enqueue_style( 'custom_tooltip_frontend_css', get_template_directory_uri().'/path-to-my.css' ); \n }\n} \n\nadd_action('wp_enqueue_scripts', 'testimonial_style');\n</code></pre>\n\n<p>Let me know How it help you.</p>\n"
},
{
"answer_id": 352001,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>Your code is ok. If it doesn't work, there's probably something wrong with your hooking order.</p>\n\n<p>If you look at the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">list of hooks</a>, you will see that there is no <code>wp_enqueue_styles</code> hook. So, yes, it is the <code>wp_enqueue_scripts</code> hook that you are supposed to add your action to. (There is a <code>wp_enqueue_styles</code> function, but that is something different, read more about how hooks work <a href=\"https://wordpress.stackexchange.com/questions/265952/whats-the-difference-between-hooks-filters-and-actions\">here</a>).</p>\n\n<p>In your code it is not clear where the line <code>if(is_page( 42 )){ ... }</code> resides. Normally you would put it in your theme's <code>functions.php</code> in a function that is called with the <code>after_setup_theme</code> hook. Looking again at the list of hooks you will see that <code>after_setup_theme</code> comes before <code>wp_enqueue_scripts</code>. So, at this point you can still attach functions to the latter hook.</p>\n\n<p>Something in your question suggests that your are executing <code>if(is_page( 42 )){ ... }</code> in a plugin. That would still be fine (*) if it is in a function that hooks onto <code>init</code>. However, if you hook into <code>wp_head</code> you would be too late, because at that point functions hooked to <code>wp_enqueue_scripts</code> have already been executed.</p>\n\n<p>(*) but if the plugin is executed while the theme is inactive you will get an error</p>\n"
}
] | 2019/11/06 | [
"https://wordpress.stackexchange.com/questions/351995",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93691/"
] | I am trying to load a CSS Stylesheet to ONLY the "about" page.
I think I am 99% correct but what is wrong is the `plugins_url` - to link to the theme folder where I keep my `CSS` can I just use simply:
```
function testimonial_style() {
wp_enqueue_style( 'custom_tooltip_frontend_css', url('path-to-my.css') );
}
if(is_page( 42 )){
add_action('wp_enqueue_scripts', 'testimonial_style');
}
```
Is it ok that I reference it with `add_action` and then "scripts" which is is is really a style **and not** a script... | Try this:
I hope, It will works.
**Explaination:**
In below code in **"is\_page( 42 )"** where 42 is page id of **about page**. So, if about page's id will be 42 then it's enqueue the stylesheet for that page only.
Also I define particular path for this CSS file by using wordpress function **get\_template\_directory\_uri()**.
```
function testimonial_style() {
if ( is_page( 42 ) ) {
wp_enqueue_style( 'custom_tooltip_frontend_css', get_template_directory_uri().'/path-to-my.css' );
}
}
add_action('wp_enqueue_scripts', 'testimonial_style');
```
Let me know How it help you. |
352,030 | <p>I'm trying to modify the inbuilt WordPress category widget to only show categories if they have children. </p>
<p>I was using this code: </p>
<pre><code>function exclude_widget_subcategories($args){
$all_categories = get_all_category_ids();
$exclude_categories = array();
foreach($all_categories as $category_id){
$category = get_category($category_id);
if($category->parent!=0){
$exclude_categories[] = $category_id;
}
}
$exclude = implode(",",$exclude_categories); // The IDs of the excluding categories
$args["exclude"] = $exclude;
return $args;
}
add_filter("widget_categories_args","exclude_widget_subcategories");
</code></pre>
<p>Which works in that it only shows top-level categories, however my client has various child-categories which <em>also</em> have children themselves and she wants these to show up in the category widget. </p>
<p>Is there a way I can modify this code so that instead of excluding categories which aren't Parent categories it instead excludes categories that don't have children? </p>
| [
{
"answer_id": 352013,
"author": "Shadow",
"author_id": 174860,
"author_profile": "https://wordpress.stackexchange.com/users/174860",
"pm_score": 1,
"selected": false,
"text": "<p>It's not the right way to delete tables from the database when you deactivate the plugin because there are many reasons that users can deactivate the plugin, but you can use an alternate way <code>register_uninstall_hook</code> for more information you may check <a href=\"https://developer.wordpress.org/reference/functions/register_uninstall_hook/\" rel=\"nofollow noreferrer\">the documentation</a> for removing tables from database.</p>\n\n<p>Hope this may help to you!</p>\n"
},
{
"answer_id": 352015,
"author": "Cas Dekkers",
"author_id": 153884,
"author_profile": "https://wordpress.stackexchange.com/users/153884",
"pm_score": 2,
"selected": false,
"text": "<p>In my opinion, a best practice would be to clean everything on uninstallation. It's also mentioned as a best practice <a href=\"https://developer.wordpress.org/plugins/plugin-basics/uninstall-methods/\" rel=\"nofollow noreferrer\">in the docs</a>:</p>\n\n<blockquote>\n <p>When your plugin is uninstalled, you’ll want to clear out any plugin options and/or settings specific to to the plugin, and/or other database entities such as tables.</p>\n</blockquote>\n\n<p>However, if you're struggling to decide what's best for your plugin, why not let the user decide? You could always ask them whether they want to keep their data just after they have clicked the uninstall button. Take a look at <a href=\"https://wordpress.stackexchange.com/questions/65611/popup-asking-whether-data-should-be-removed-on-plugin-uninstall\">this similar question</a> for details.</p>\n"
}
] | 2019/11/06 | [
"https://wordpress.stackexchange.com/questions/352030",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132427/"
] | I'm trying to modify the inbuilt WordPress category widget to only show categories if they have children.
I was using this code:
```
function exclude_widget_subcategories($args){
$all_categories = get_all_category_ids();
$exclude_categories = array();
foreach($all_categories as $category_id){
$category = get_category($category_id);
if($category->parent!=0){
$exclude_categories[] = $category_id;
}
}
$exclude = implode(",",$exclude_categories); // The IDs of the excluding categories
$args["exclude"] = $exclude;
return $args;
}
add_filter("widget_categories_args","exclude_widget_subcategories");
```
Which works in that it only shows top-level categories, however my client has various child-categories which *also* have children themselves and she wants these to show up in the category widget.
Is there a way I can modify this code so that instead of excluding categories which aren't Parent categories it instead excludes categories that don't have children? | In my opinion, a best practice would be to clean everything on uninstallation. It's also mentioned as a best practice [in the docs](https://developer.wordpress.org/plugins/plugin-basics/uninstall-methods/):
>
> When your plugin is uninstalled, you’ll want to clear out any plugin options and/or settings specific to to the plugin, and/or other database entities such as tables.
>
>
>
However, if you're struggling to decide what's best for your plugin, why not let the user decide? You could always ask them whether they want to keep their data just after they have clicked the uninstall button. Take a look at [this similar question](https://wordpress.stackexchange.com/questions/65611/popup-asking-whether-data-should-be-removed-on-plugin-uninstall) for details. |
352,077 | <p>When you add a meta box to Gutenberg, it looks different than the other items in the editor. There is a HR, and the fonts are different.</p>
<p><a href="https://i.stack.imgur.com/DW1qe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DW1qe.png" alt="enter image description here"></a></p>
<p>Does anyone know how to fix this so it looks like a natural part of the site, and not "some junk Automattic didn't add".</p>
<p>Example code:</p>
<pre><code>function myMetaBox() {
add_meta_box(
'MyMetaBox',
"Why the odd font?",
'myBoxOutputCallback',
'post',
'side'
);
}
add_action( 'add_meta_boxes', 'myMetaBox' );
function myBoxOutputCallback(){
echo ("Gutenberg is a great addition! NOT!");
}
</code></pre>
| [
{
"answer_id": 352079,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>In your example, Discussion is not a meta box. Meta boxes are not a native part of the block editor, and are only supported for backwards compatibility. They are not the correct modern way to add these settings boxes to the block editor. This is why they have different styles.</p>\n\n<p>In the block editor, these sections are <a href=\"https://developer.wordpress.org/block-editor/components/panel/\" rel=\"nofollow noreferrer\">\"Panels\"</a>, that fit inside a <a href=\"https://developer.wordpress.org/block-editor/tutorials/plugin-sidebar-0/\" rel=\"nofollow noreferrer\">\"Sidebar\"</a>, and are React components, like the rest of the block editor.</p>\n\n<p>A full guide on creating these is beyond the scope of a single answer on this site, but essentially you need to:</p>\n\n<ol>\n<li>Use <a href=\"https://developer.wordpress.org/reference/functions/register_meta/\" rel=\"nofollow noreferrer\"><code>register_meta()</code></a> to register the fields that your panel will be working with.</li>\n<li>Creating a React component to manage the custom fields. Some documentation for this is available in the guide for creating a custom sidebar in the editor, which starts <a href=\"https://developer.wordpress.org/block-editor/tutorials/plugin-sidebar-0/\" rel=\"nofollow noreferrer\">here</a>, and CSS-Tricks has a useful article covering this in more detail <a href=\"https://css-tricks.com/managing-wordpress-metadata-in-gutenberg-using-a-sidebar-plugin/#article-header-id-7\" rel=\"nofollow noreferrer\">here</a>.</li>\n<li>If you want to add your panel to the existing \"Document\" sidebar, and not a custom sidebar, you'll need to use a <a href=\"https://developer.wordpress.org/block-editor/developers/slotfills/\" rel=\"nofollow noreferrer\">SlotFill</a>, specifically <a href=\"https://developer.wordpress.org/block-editor/developers/slotfills/plugin-document-setting-panel/\" rel=\"nofollow noreferrer\"><code>PluginDocumentSettingPanel</code></a>, to output your component as a panel in the existing sidebar (SlotFills are a bit like hooks, and allow you to add components to sections of the editor).</li>\n</ol>\n\n<p>You can continue to use meta boxes, but they will not visually match the native components that are the new correct way to add fields to the editor.</p>\n\n<p>It's also worth considering whether or not the field you intend to add would work better as a regular block anyway. The documentation for creating those is available <a href=\"https://developer.wordpress.org/block-editor/tutorials/block-tutorial/\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 385222,
"author": "ViliusL",
"author_id": 120665,
"author_profile": "https://wordpress.stackexchange.com/users/120665",
"pm_score": 2,
"selected": true,
"text": "<p>Bottom border (HR) can be removed using CSS:</p>\n<pre><code>#__BLOCK_ID__.postbox:not(.closed) .postbox-header{\n border-bottom: none;\n}\n</code></pre>\n<p>p.s. change <code>__BLOCK_ID__</code> to first parameter used in <code>add_meta_box()</code> function.</p>\n"
}
] | 2019/11/07 | [
"https://wordpress.stackexchange.com/questions/352077",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/131224/"
] | When you add a meta box to Gutenberg, it looks different than the other items in the editor. There is a HR, and the fonts are different.
[](https://i.stack.imgur.com/DW1qe.png)
Does anyone know how to fix this so it looks like a natural part of the site, and not "some junk Automattic didn't add".
Example code:
```
function myMetaBox() {
add_meta_box(
'MyMetaBox',
"Why the odd font?",
'myBoxOutputCallback',
'post',
'side'
);
}
add_action( 'add_meta_boxes', 'myMetaBox' );
function myBoxOutputCallback(){
echo ("Gutenberg is a great addition! NOT!");
}
``` | Bottom border (HR) can be removed using CSS:
```
#__BLOCK_ID__.postbox:not(.closed) .postbox-header{
border-bottom: none;
}
```
p.s. change `__BLOCK_ID__` to first parameter used in `add_meta_box()` function. |
352,087 | <p>In start of every month WP creating folder with month number, like /uploads/2019/11, and it's creating with ROOT, so I dont have permission to write it. If I delete it, and then it's creating when I uploading smth - it's ok.
So problem only in this AUTOCREATE folder every 1st day of month. How can I disable it? I cant configure server. So I need to disable this autocreating every month and leave the folder was created only with the media file upload.</p>
| [
{
"answer_id": 352079,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>In your example, Discussion is not a meta box. Meta boxes are not a native part of the block editor, and are only supported for backwards compatibility. They are not the correct modern way to add these settings boxes to the block editor. This is why they have different styles.</p>\n\n<p>In the block editor, these sections are <a href=\"https://developer.wordpress.org/block-editor/components/panel/\" rel=\"nofollow noreferrer\">\"Panels\"</a>, that fit inside a <a href=\"https://developer.wordpress.org/block-editor/tutorials/plugin-sidebar-0/\" rel=\"nofollow noreferrer\">\"Sidebar\"</a>, and are React components, like the rest of the block editor.</p>\n\n<p>A full guide on creating these is beyond the scope of a single answer on this site, but essentially you need to:</p>\n\n<ol>\n<li>Use <a href=\"https://developer.wordpress.org/reference/functions/register_meta/\" rel=\"nofollow noreferrer\"><code>register_meta()</code></a> to register the fields that your panel will be working with.</li>\n<li>Creating a React component to manage the custom fields. Some documentation for this is available in the guide for creating a custom sidebar in the editor, which starts <a href=\"https://developer.wordpress.org/block-editor/tutorials/plugin-sidebar-0/\" rel=\"nofollow noreferrer\">here</a>, and CSS-Tricks has a useful article covering this in more detail <a href=\"https://css-tricks.com/managing-wordpress-metadata-in-gutenberg-using-a-sidebar-plugin/#article-header-id-7\" rel=\"nofollow noreferrer\">here</a>.</li>\n<li>If you want to add your panel to the existing \"Document\" sidebar, and not a custom sidebar, you'll need to use a <a href=\"https://developer.wordpress.org/block-editor/developers/slotfills/\" rel=\"nofollow noreferrer\">SlotFill</a>, specifically <a href=\"https://developer.wordpress.org/block-editor/developers/slotfills/plugin-document-setting-panel/\" rel=\"nofollow noreferrer\"><code>PluginDocumentSettingPanel</code></a>, to output your component as a panel in the existing sidebar (SlotFills are a bit like hooks, and allow you to add components to sections of the editor).</li>\n</ol>\n\n<p>You can continue to use meta boxes, but they will not visually match the native components that are the new correct way to add fields to the editor.</p>\n\n<p>It's also worth considering whether or not the field you intend to add would work better as a regular block anyway. The documentation for creating those is available <a href=\"https://developer.wordpress.org/block-editor/tutorials/block-tutorial/\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 385222,
"author": "ViliusL",
"author_id": 120665,
"author_profile": "https://wordpress.stackexchange.com/users/120665",
"pm_score": 2,
"selected": true,
"text": "<p>Bottom border (HR) can be removed using CSS:</p>\n<pre><code>#__BLOCK_ID__.postbox:not(.closed) .postbox-header{\n border-bottom: none;\n}\n</code></pre>\n<p>p.s. change <code>__BLOCK_ID__</code> to first parameter used in <code>add_meta_box()</code> function.</p>\n"
}
] | 2019/11/07 | [
"https://wordpress.stackexchange.com/questions/352087",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/177998/"
] | In start of every month WP creating folder with month number, like /uploads/2019/11, and it's creating with ROOT, so I dont have permission to write it. If I delete it, and then it's creating when I uploading smth - it's ok.
So problem only in this AUTOCREATE folder every 1st day of month. How can I disable it? I cant configure server. So I need to disable this autocreating every month and leave the folder was created only with the media file upload. | Bottom border (HR) can be removed using CSS:
```
#__BLOCK_ID__.postbox:not(.closed) .postbox-header{
border-bottom: none;
}
```
p.s. change `__BLOCK_ID__` to first parameter used in `add_meta_box()` function. |
352,130 | <p>I had a drupal site for many years that crashed. I thought I lost all my files, but I was able to download an enormous amount from the Wayback Machine. Now the question is, how do I move those files and get the old articles live on my WordPress site? I did find a plugin for a Drupal to WordPress migration, but it seems to need live sites. Since I only have the files, what should I do?</p>
<p><a href="https://i.stack.imgur.com/lQaJd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lQaJd.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 352079,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>In your example, Discussion is not a meta box. Meta boxes are not a native part of the block editor, and are only supported for backwards compatibility. They are not the correct modern way to add these settings boxes to the block editor. This is why they have different styles.</p>\n\n<p>In the block editor, these sections are <a href=\"https://developer.wordpress.org/block-editor/components/panel/\" rel=\"nofollow noreferrer\">\"Panels\"</a>, that fit inside a <a href=\"https://developer.wordpress.org/block-editor/tutorials/plugin-sidebar-0/\" rel=\"nofollow noreferrer\">\"Sidebar\"</a>, and are React components, like the rest of the block editor.</p>\n\n<p>A full guide on creating these is beyond the scope of a single answer on this site, but essentially you need to:</p>\n\n<ol>\n<li>Use <a href=\"https://developer.wordpress.org/reference/functions/register_meta/\" rel=\"nofollow noreferrer\"><code>register_meta()</code></a> to register the fields that your panel will be working with.</li>\n<li>Creating a React component to manage the custom fields. Some documentation for this is available in the guide for creating a custom sidebar in the editor, which starts <a href=\"https://developer.wordpress.org/block-editor/tutorials/plugin-sidebar-0/\" rel=\"nofollow noreferrer\">here</a>, and CSS-Tricks has a useful article covering this in more detail <a href=\"https://css-tricks.com/managing-wordpress-metadata-in-gutenberg-using-a-sidebar-plugin/#article-header-id-7\" rel=\"nofollow noreferrer\">here</a>.</li>\n<li>If you want to add your panel to the existing \"Document\" sidebar, and not a custom sidebar, you'll need to use a <a href=\"https://developer.wordpress.org/block-editor/developers/slotfills/\" rel=\"nofollow noreferrer\">SlotFill</a>, specifically <a href=\"https://developer.wordpress.org/block-editor/developers/slotfills/plugin-document-setting-panel/\" rel=\"nofollow noreferrer\"><code>PluginDocumentSettingPanel</code></a>, to output your component as a panel in the existing sidebar (SlotFills are a bit like hooks, and allow you to add components to sections of the editor).</li>\n</ol>\n\n<p>You can continue to use meta boxes, but they will not visually match the native components that are the new correct way to add fields to the editor.</p>\n\n<p>It's also worth considering whether or not the field you intend to add would work better as a regular block anyway. The documentation for creating those is available <a href=\"https://developer.wordpress.org/block-editor/tutorials/block-tutorial/\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 385222,
"author": "ViliusL",
"author_id": 120665,
"author_profile": "https://wordpress.stackexchange.com/users/120665",
"pm_score": 2,
"selected": true,
"text": "<p>Bottom border (HR) can be removed using CSS:</p>\n<pre><code>#__BLOCK_ID__.postbox:not(.closed) .postbox-header{\n border-bottom: none;\n}\n</code></pre>\n<p>p.s. change <code>__BLOCK_ID__</code> to first parameter used in <code>add_meta_box()</code> function.</p>\n"
}
] | 2019/11/07 | [
"https://wordpress.stackexchange.com/questions/352130",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178031/"
] | I had a drupal site for many years that crashed. I thought I lost all my files, but I was able to download an enormous amount from the Wayback Machine. Now the question is, how do I move those files and get the old articles live on my WordPress site? I did find a plugin for a Drupal to WordPress migration, but it seems to need live sites. Since I only have the files, what should I do?
[](https://i.stack.imgur.com/lQaJd.png) | Bottom border (HR) can be removed using CSS:
```
#__BLOCK_ID__.postbox:not(.closed) .postbox-header{
border-bottom: none;
}
```
p.s. change `__BLOCK_ID__` to first parameter used in `add_meta_box()` function. |
352,134 | <p><strong>Note:</strong> I'm adding information I discover that seems to be leading to a resolution in the note.</p>
<h1>The Problem:</h1>
<p><strong>When pasting content from a source external to Gutenberg into Gutenberg some HTML/CSS formatting is lost.[1]</strong> While Gutenberg retains most HTML (semantic) elements it drops CSS (styling/non-semantic) elements. This means that properties such as font size, text alignment, text color, etc. are all removed during the paste event.</p>
<h1>Not the Problem:</h1>
<p>We could discuss the plugins, custom HTML blocks, etc. (e.g., Wordable, JetPack) available for converting external content sources (e.g., Google Docs) to WP friendly content but this question is decidedly not about those solutions. Instead, <strong>this question is exclusively focused on how to programmatically alter</strong> Gutenberg's paste handling behavior.</p>
<h1>Seeing the Problem in Action</h1>
<p>This problem occurs in many circumstances. For example, try pasting the following block of HTML into the paragraph block in Gutenberg:</p>
<p><code><p style="color:red">Hello WordPress StackExchange!</p></code></p>
<p>Then view the HTML for that paragraph block and you'll see:</p>
<p><code><p>Hello WordPress StackExchange!</p></code></p>
<p>The <code>style="color:red"</code> has been stripped out.</p>
<h1>Looking at the Paragraph Block</h1>
<p>One of the blocks that suffers from this stripping is the paragraph block (<code>/gutenberg/packages/block-library/src/paragraph</code>). This block[2] uses the <code>RichText</code> component (<code>/gutenberg/packages/block-editor/rich-text</code>) to implement its rich text editing functionality.</p>
<h1>Looking at the RichText Component</h1>
<p>In <code>/rich-text/index.js</code> we find the <code>onPaste</code> method which the paragraph block inherits. This function in turn calls the <code>pasteHandler</code> function (<code>/gutenberg/packages/blocks/src/api/raw-handling/paste-handler.js</code>).</p>
<h1>Looking at the Paste Handler</h1>
<p>The <code>pasteHandler</code> function "Converts an HTML string to known blocks. Strips everything else." according to the JSDoc.</p>
<p>This function takes five parameters:</p>
<ul>
<li><code>HTML</code> = The source content to convert if in HTML format</li>
<li><code>plainText</code> = The source content to convert if in text format</li>
<li><code>mode</code> = Whether to paste the content in as blocks or inline content in existing block.</li>
<li><code>tagName</code> = What tag we are inserting the content into.</li>
<li><code>canUserUseUnfilteredHTML</code> = Initially I thought this determined whether one could use any HTML/CSS one desired but it appears to be more limited, AFAIK it only determines whether the <code>iframeRemover</code> function is run against the pasted content, which is only tangentially relevant.</li>
</ul>
<p>We can see that <code>pasteHandler</code> is imported (<code>index.js</code>):</p>
<pre class="lang-js prettyprint-override"><code>import {
pasteHandler,
children as childrenSource,
getBlockTransforms,
findTransform,
isUnmodifiedDefaultBlock
} from '@wordpress/blocks';
</code></pre>
<p><code>pasteHandler</code> is then called from <code>onPaste</code>:</p>
<pre class="lang-js prettyprint-override"><code>onPaste( { value, onChange, html, plainText, files } ) {
...
if ( files && files.length && ! html ) {
const content = pasteHandler( {
HTML: filePasteHandler( files),
mode: 'BLOCKS',
tagName,
} );
...
const content = pasteHandler ( {
HTML: html,
plainText,
mode,
tagName,
canUserUseUnfilteredHTML,
} );
...
}
</code></pre>
<p>We are interested for our purposes only in a portion of the pasteHandler function:</p>
<pre class="lang-js prettyprint-override"><code>const rawTransforms = getRawTransformations();
const phrasingContentSchema = getPhrasingContentSchema( 'paste' );
const blockContentSchema = getBlockContentSchema( rawTransforms, phrasingContentSchema, true );
const blocks = compact( flatMap( pieces, ( piece ) => {
...
if ( ! canUserUseUnfilteredHTML ) {
// Should run before `figureContentReducer`.
filters.unshift( iframeRemover );
}
const schema = {
...blockContentSchema,
// Keep top-level phrasing content, normalised by `normaliseBlocks`.
...phrasingContentSchema,
};
piece = deepFilterHTML( piece, filters, blockContentSchema );
piece = removeInvalidHTML( piece, schema );
piece = normaliseBlocks( piece );
piece = deepFilterHTML( piece, [
htmlFormattingRemover,
brRemover,
emptyParagraphRemover,
], blockContentSchema );
...
return htmlToBlocks( { html: piece, rawTransforms } );
} ) );
</code></pre>
<p>Even here, most of what occurs is not relevant to our current issue. We don't care, for example, about Google Doc UIDs being removed or Word lists being converted.</p>
<p>Instead we are interested in:</p>
<ul>
<li><code>rawTransforms</code> - contains the results of a call to <code>getRawTransformations</code>, also defined in <code>paste-handler.js</code>.
<ul>
<li>I don't think this code is involved, but maybe someone can help me understand what it does? :)</li>
</ul></li>
<li><code>phrasingContentSchema</code> - contains the results of calling <code>getPhrasingContentSchema</code>, defined in <code>phrasing-content.js</code>.
<ul>
<li>This appears to remove a few invisible attributes (u, abbr, data, etc.) which could be part of this problem but the more likely issues folks will run into are with the CSS styles, not these attributes.</li>
</ul></li>
<li><code>blockContentSchema</code> - contains the results of a call to <code>getBlockContentSchema</code>, defined in <code>utils.js</code>.
<ul>
<li>Again,not entirely sure I understadn what it does, but I don't think it is involved.</li>
</ul></li>
<li><code>phrasingContentReducer</code> - one of the filters, defined in <code>phrasing-content-reducer.js</code>.
<ul>
<li>I'm unsure but I suspect this snippet may be involved:</li>
</ul></li>
</ul>
<pre class="lang-js prettyprint-override"><code>if ( node.nodeName === 'SPAN' && node.style ) {
const {
fontWeight,
fontStyle,
textDecorationLine,
textDecoration,
verticalAlign,
} = node.style;
</code></pre>
<ul>
<li><code>deepFilterHTML</code> - defined in <code>utils.js</code>, essentially a wrapper for <code>deepFilterNodeList</code>, also found in <code>utils.js</code>.
<ul>
<li>Again, not sure I understand this segment of code, could be involved.</li>
</ul></li>
<li><code>removeInvalidHTML</code> - defined in <code>utils.js</code>, essentially a wrapper for <code>cleanNodeList</code>, also found in <code>utils.js</code>.
<ul>
<li>Believe this is involved, <code>cleanNodeList</code> JSDoc states, "Given a schema, unwraps or removes nodes, attributes and classes on a node".</li>
</ul></li>
</ul>
<p>You'll notice several functions that did not make the list - after reviewing their code, I don't believe they are involved in the current problem (e.g., <code>normaliseBlocks</code>, <code>brRemover</code>, <code>emptyParagraphRemover</code>, etc).</p>
<h1>The Conclusion</h1>
<p>I just rewrote most of this question, I'll try to refine a bit later and share more on what specific snippets of code that I did not understand does when I have a chance to look at it. Hoping that this may be helpful to others / someone may be able to explain to me what I am missing...or I can keep slogging away. :)</p>
<p>[1] Technically, this isn't always true. Some blocks may accept most/all content pasted into them - for example the HTML block. But the retaining of pasted content is an exception to and not the rule.</p>
<p>[2] You can find the reference in <code>/paragraph/edit.js</code> in the <code>ParagraphBlock</code> function.</p>
| [
{
"answer_id": 352079,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>In your example, Discussion is not a meta box. Meta boxes are not a native part of the block editor, and are only supported for backwards compatibility. They are not the correct modern way to add these settings boxes to the block editor. This is why they have different styles.</p>\n\n<p>In the block editor, these sections are <a href=\"https://developer.wordpress.org/block-editor/components/panel/\" rel=\"nofollow noreferrer\">\"Panels\"</a>, that fit inside a <a href=\"https://developer.wordpress.org/block-editor/tutorials/plugin-sidebar-0/\" rel=\"nofollow noreferrer\">\"Sidebar\"</a>, and are React components, like the rest of the block editor.</p>\n\n<p>A full guide on creating these is beyond the scope of a single answer on this site, but essentially you need to:</p>\n\n<ol>\n<li>Use <a href=\"https://developer.wordpress.org/reference/functions/register_meta/\" rel=\"nofollow noreferrer\"><code>register_meta()</code></a> to register the fields that your panel will be working with.</li>\n<li>Creating a React component to manage the custom fields. Some documentation for this is available in the guide for creating a custom sidebar in the editor, which starts <a href=\"https://developer.wordpress.org/block-editor/tutorials/plugin-sidebar-0/\" rel=\"nofollow noreferrer\">here</a>, and CSS-Tricks has a useful article covering this in more detail <a href=\"https://css-tricks.com/managing-wordpress-metadata-in-gutenberg-using-a-sidebar-plugin/#article-header-id-7\" rel=\"nofollow noreferrer\">here</a>.</li>\n<li>If you want to add your panel to the existing \"Document\" sidebar, and not a custom sidebar, you'll need to use a <a href=\"https://developer.wordpress.org/block-editor/developers/slotfills/\" rel=\"nofollow noreferrer\">SlotFill</a>, specifically <a href=\"https://developer.wordpress.org/block-editor/developers/slotfills/plugin-document-setting-panel/\" rel=\"nofollow noreferrer\"><code>PluginDocumentSettingPanel</code></a>, to output your component as a panel in the existing sidebar (SlotFills are a bit like hooks, and allow you to add components to sections of the editor).</li>\n</ol>\n\n<p>You can continue to use meta boxes, but they will not visually match the native components that are the new correct way to add fields to the editor.</p>\n\n<p>It's also worth considering whether or not the field you intend to add would work better as a regular block anyway. The documentation for creating those is available <a href=\"https://developer.wordpress.org/block-editor/tutorials/block-tutorial/\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 385222,
"author": "ViliusL",
"author_id": 120665,
"author_profile": "https://wordpress.stackexchange.com/users/120665",
"pm_score": 2,
"selected": true,
"text": "<p>Bottom border (HR) can be removed using CSS:</p>\n<pre><code>#__BLOCK_ID__.postbox:not(.closed) .postbox-header{\n border-bottom: none;\n}\n</code></pre>\n<p>p.s. change <code>__BLOCK_ID__</code> to first parameter used in <code>add_meta_box()</code> function.</p>\n"
}
] | 2019/11/07 | [
"https://wordpress.stackexchange.com/questions/352134",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/43881/"
] | **Note:** I'm adding information I discover that seems to be leading to a resolution in the note.
The Problem:
============
**When pasting content from a source external to Gutenberg into Gutenberg some HTML/CSS formatting is lost.[1]** While Gutenberg retains most HTML (semantic) elements it drops CSS (styling/non-semantic) elements. This means that properties such as font size, text alignment, text color, etc. are all removed during the paste event.
Not the Problem:
================
We could discuss the plugins, custom HTML blocks, etc. (e.g., Wordable, JetPack) available for converting external content sources (e.g., Google Docs) to WP friendly content but this question is decidedly not about those solutions. Instead, **this question is exclusively focused on how to programmatically alter** Gutenberg's paste handling behavior.
Seeing the Problem in Action
============================
This problem occurs in many circumstances. For example, try pasting the following block of HTML into the paragraph block in Gutenberg:
`<p style="color:red">Hello WordPress StackExchange!</p>`
Then view the HTML for that paragraph block and you'll see:
`<p>Hello WordPress StackExchange!</p>`
The `style="color:red"` has been stripped out.
Looking at the Paragraph Block
==============================
One of the blocks that suffers from this stripping is the paragraph block (`/gutenberg/packages/block-library/src/paragraph`). This block[2] uses the `RichText` component (`/gutenberg/packages/block-editor/rich-text`) to implement its rich text editing functionality.
Looking at the RichText Component
=================================
In `/rich-text/index.js` we find the `onPaste` method which the paragraph block inherits. This function in turn calls the `pasteHandler` function (`/gutenberg/packages/blocks/src/api/raw-handling/paste-handler.js`).
Looking at the Paste Handler
============================
The `pasteHandler` function "Converts an HTML string to known blocks. Strips everything else." according to the JSDoc.
This function takes five parameters:
* `HTML` = The source content to convert if in HTML format
* `plainText` = The source content to convert if in text format
* `mode` = Whether to paste the content in as blocks or inline content in existing block.
* `tagName` = What tag we are inserting the content into.
* `canUserUseUnfilteredHTML` = Initially I thought this determined whether one could use any HTML/CSS one desired but it appears to be more limited, AFAIK it only determines whether the `iframeRemover` function is run against the pasted content, which is only tangentially relevant.
We can see that `pasteHandler` is imported (`index.js`):
```js
import {
pasteHandler,
children as childrenSource,
getBlockTransforms,
findTransform,
isUnmodifiedDefaultBlock
} from '@wordpress/blocks';
```
`pasteHandler` is then called from `onPaste`:
```js
onPaste( { value, onChange, html, plainText, files } ) {
...
if ( files && files.length && ! html ) {
const content = pasteHandler( {
HTML: filePasteHandler( files),
mode: 'BLOCKS',
tagName,
} );
...
const content = pasteHandler ( {
HTML: html,
plainText,
mode,
tagName,
canUserUseUnfilteredHTML,
} );
...
}
```
We are interested for our purposes only in a portion of the pasteHandler function:
```js
const rawTransforms = getRawTransformations();
const phrasingContentSchema = getPhrasingContentSchema( 'paste' );
const blockContentSchema = getBlockContentSchema( rawTransforms, phrasingContentSchema, true );
const blocks = compact( flatMap( pieces, ( piece ) => {
...
if ( ! canUserUseUnfilteredHTML ) {
// Should run before `figureContentReducer`.
filters.unshift( iframeRemover );
}
const schema = {
...blockContentSchema,
// Keep top-level phrasing content, normalised by `normaliseBlocks`.
...phrasingContentSchema,
};
piece = deepFilterHTML( piece, filters, blockContentSchema );
piece = removeInvalidHTML( piece, schema );
piece = normaliseBlocks( piece );
piece = deepFilterHTML( piece, [
htmlFormattingRemover,
brRemover,
emptyParagraphRemover,
], blockContentSchema );
...
return htmlToBlocks( { html: piece, rawTransforms } );
} ) );
```
Even here, most of what occurs is not relevant to our current issue. We don't care, for example, about Google Doc UIDs being removed or Word lists being converted.
Instead we are interested in:
* `rawTransforms` - contains the results of a call to `getRawTransformations`, also defined in `paste-handler.js`.
+ I don't think this code is involved, but maybe someone can help me understand what it does? :)
* `phrasingContentSchema` - contains the results of calling `getPhrasingContentSchema`, defined in `phrasing-content.js`.
+ This appears to remove a few invisible attributes (u, abbr, data, etc.) which could be part of this problem but the more likely issues folks will run into are with the CSS styles, not these attributes.
* `blockContentSchema` - contains the results of a call to `getBlockContentSchema`, defined in `utils.js`.
+ Again,not entirely sure I understadn what it does, but I don't think it is involved.
* `phrasingContentReducer` - one of the filters, defined in `phrasing-content-reducer.js`.
+ I'm unsure but I suspect this snippet may be involved:
```js
if ( node.nodeName === 'SPAN' && node.style ) {
const {
fontWeight,
fontStyle,
textDecorationLine,
textDecoration,
verticalAlign,
} = node.style;
```
* `deepFilterHTML` - defined in `utils.js`, essentially a wrapper for `deepFilterNodeList`, also found in `utils.js`.
+ Again, not sure I understand this segment of code, could be involved.
* `removeInvalidHTML` - defined in `utils.js`, essentially a wrapper for `cleanNodeList`, also found in `utils.js`.
+ Believe this is involved, `cleanNodeList` JSDoc states, "Given a schema, unwraps or removes nodes, attributes and classes on a node".
You'll notice several functions that did not make the list - after reviewing their code, I don't believe they are involved in the current problem (e.g., `normaliseBlocks`, `brRemover`, `emptyParagraphRemover`, etc).
The Conclusion
==============
I just rewrote most of this question, I'll try to refine a bit later and share more on what specific snippets of code that I did not understand does when I have a chance to look at it. Hoping that this may be helpful to others / someone may be able to explain to me what I am missing...or I can keep slogging away. :)
[1] Technically, this isn't always true. Some blocks may accept most/all content pasted into them - for example the HTML block. But the retaining of pasted content is an exception to and not the rule.
[2] You can find the reference in `/paragraph/edit.js` in the `ParagraphBlock` function. | Bottom border (HR) can be removed using CSS:
```
#__BLOCK_ID__.postbox:not(.closed) .postbox-header{
border-bottom: none;
}
```
p.s. change `__BLOCK_ID__` to first parameter used in `add_meta_box()` function. |
352,140 | <p>I am developing a plugin by using classes and object oriented programming.</p>
<p>Within my plugin I have included another object as I need to use the functionality of this other object.</p>
<p>I am instantiating the included object within my plugin's constructor.</p>
<pre><code>require_once ('path/to/my/IncludedObject');
class MyPlugin
{
private $IncludedObject;
public function __construct()
{
$this->IncludedObject = new IncludedObject();
}
}
class IncludedObject
{
public $instanceVar = 'defaultValue';
public function getInstanceVar()
{
return $this->instanceVar();
}
public function setInstanceVar($instanceVar)
{
$this->instanceVar = $instanceVar;
}
}
</code></pre>
<p>The $instaceVar is updated after an ajax action within my HTML form commanded by my plugin. So, from the handler within my plugin I call setInstanceVar($_REQUEST['newValue']);</p>
<p>The problem I am facing is that $instanceVar never gets updated and always have the 'defaultValue'.</p>
<p>Can anyone shed some light on this issue?</p>
<p>Thanks</p>
| [
{
"answer_id": 352141,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 4,
"selected": true,
"text": "<p>The root of your problem is not object oriented programming, but a fundamental misunderstanding about how PHP handles requests.</p>\n\n<p>If this were a Java or a Node application for example, you would start the application on the server, and it would recieve requests, and respond. It's a continuous active program. As a result, you can store things in memory and they're still there when you make another request as they never went away.</p>\n\n<p>That's not how PHP works.</p>\n\n<p>PHP requests have more in common with AWS Lamda, each request spawns a brand new PHP lifecycle. You can set things in memory but they dissapear at the end of the request, all your objects, your functions, your variables, all of it.</p>\n\n<p>Every new request loads the entire PHP application from scratch. All your plugins, WordPress, your theme, get reloaded every time, then vanish from memory when the request finishes.</p>\n\n<h2>So How Do You Persist Things?</h2>\n\n<p>The only way to persist things is to use persistent storage, such as a database, files, cookies, object caches, etc</p>\n\n<p>Alternatives include:</p>\n\n<ul>\n<li>For logged in user specific data use user meta</li>\n<li>For logged out user specific data, use cookies if the server needs access, and JS based local storage for everything else</li>\n<li>For persisting information across multi-page forms, use hidden inputs, there's no need to persist anything server side until it's submitted</li>\n<li>For site wide information, use options and transients</li>\n<li>For post specific data use post meta and taxonomy terms</li>\n<li>For term specific data, use term meta</li>\n</ul>\n\n<p>Note that it might be tempting to make use of <code>$_SESSION</code> PHP session variables, but:</p>\n\n<ul>\n<li>these are vulnerable to session hijacking</li>\n<li>aren't used by WordPress ( WP uses cookies )</li>\n<li>have to be manually set up and cleaned up</li>\n<li>don't work with a lot of hosts</li>\n<li>are incompatible with a lot of CDN and caching systems, e.g. Cloudflare</li>\n<li>That data has to be stored somewhere in memory on the server, so this could cause problems with high traffic situations</li>\n</ul>\n\n<h2>Some Follow up Notes on OO</h2>\n\n<ol>\n<li>Use dependency injection! Your object has no business creating other objects in its constructor. Pass them in as arguments. It'll make your objects more flexible, easier to test, easier to debug, and save a lot of headaches.</li>\n<li>1 class per file, don't piledrive your PHP files. Keep it nice and simple</li>\n<li>Your <code>IncludedObject</code> might as well just have the public variable, there's no point in having a getter and a setter if you can just access it directly. Either make that variable private or get rid of those getter/setters</li>\n<li>Don't call things \"->setXYZ()\" etc. Just call it <code>->xyz()</code>, call it what it is. Why write <code>$person->getName()</code> when you can have <code>$person->name()</code>? Much simpler.</li>\n<li>The same goes for setters, why have <code>$person->setName()</code> when you can have <code>$person->rename()</code>?</li>\n</ol>\n\n<p>But most importantly, do you really need objects here? Making things OO doesn't mean that you're writing better code, it just means you're trying OO. If your objects have no internal state, and don't implement any abstract interfaces, then you gain nothing from using classes, and it's not OO.</p>\n\n<p>Don't make a huge mess of functions and wrap them in a class and pretend it's OO, it isn't, it's just extra typing for you. So save yourself the hassle. It's ok for the entry point of your plugin to be a function. It's ok to put quick filters as plain functions, you don't have to put everything in a class.</p>\n\n<p>You might be learning, but don't force yourself to use classes under the guise of \"OO\", it isn't OO, and you'll just be learning bad habits.</p>\n"
},
{
"answer_id": 352143,
"author": "Jess_Pinkman",
"author_id": 171161,
"author_profile": "https://wordpress.stackexchange.com/users/171161",
"pm_score": 0,
"selected": false,
"text": "<p>EDIT: As pointed, this is not a prefered solution on wordpress as wordpress is stateless.</p>\n\n<p>Your problem is not external objects, it is about data persistency. I am presuming you want to have data persistency through a user session, so you could use something like $_SESSION ( if what you want is persistency through a user session )</p>\n\n<p>So, your plugin could have something like that</p>\n\n<pre><code>add_action( 'init', 'instanciate_object' );\n\n//Check if object already instanciated, if not, instanciate.\nfunction instanciate_object()\n{\n if ( !isset( $_SESSION['myObject']) {\n $_SESSION['myObject'] = new includedObject();\n }\n}\n</code></pre>\n\n<p>and then your ajax handler would do that:</p>\n\n<pre><code>function ajax_handler()\n{\n if ( isset( $_SESSION['myObject'] ) {\n $object = $_SESSION['myObject'];\n $object->setInstanceVar( $_REQUEST['newValue']);\n $_SESSION['myObject'] = $object;\n }\n}\n</code></pre>\n\n<p>Make sure that the file with the ajax_handler does have access to the class definition.</p>\n"
}
] | 2019/11/08 | [
"https://wordpress.stackexchange.com/questions/352140",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63540/"
] | I am developing a plugin by using classes and object oriented programming.
Within my plugin I have included another object as I need to use the functionality of this other object.
I am instantiating the included object within my plugin's constructor.
```
require_once ('path/to/my/IncludedObject');
class MyPlugin
{
private $IncludedObject;
public function __construct()
{
$this->IncludedObject = new IncludedObject();
}
}
class IncludedObject
{
public $instanceVar = 'defaultValue';
public function getInstanceVar()
{
return $this->instanceVar();
}
public function setInstanceVar($instanceVar)
{
$this->instanceVar = $instanceVar;
}
}
```
The $instaceVar is updated after an ajax action within my HTML form commanded by my plugin. So, from the handler within my plugin I call setInstanceVar($\_REQUEST['newValue']);
The problem I am facing is that $instanceVar never gets updated and always have the 'defaultValue'.
Can anyone shed some light on this issue?
Thanks | The root of your problem is not object oriented programming, but a fundamental misunderstanding about how PHP handles requests.
If this were a Java or a Node application for example, you would start the application on the server, and it would recieve requests, and respond. It's a continuous active program. As a result, you can store things in memory and they're still there when you make another request as they never went away.
That's not how PHP works.
PHP requests have more in common with AWS Lamda, each request spawns a brand new PHP lifecycle. You can set things in memory but they dissapear at the end of the request, all your objects, your functions, your variables, all of it.
Every new request loads the entire PHP application from scratch. All your plugins, WordPress, your theme, get reloaded every time, then vanish from memory when the request finishes.
So How Do You Persist Things?
-----------------------------
The only way to persist things is to use persistent storage, such as a database, files, cookies, object caches, etc
Alternatives include:
* For logged in user specific data use user meta
* For logged out user specific data, use cookies if the server needs access, and JS based local storage for everything else
* For persisting information across multi-page forms, use hidden inputs, there's no need to persist anything server side until it's submitted
* For site wide information, use options and transients
* For post specific data use post meta and taxonomy terms
* For term specific data, use term meta
Note that it might be tempting to make use of `$_SESSION` PHP session variables, but:
* these are vulnerable to session hijacking
* aren't used by WordPress ( WP uses cookies )
* have to be manually set up and cleaned up
* don't work with a lot of hosts
* are incompatible with a lot of CDN and caching systems, e.g. Cloudflare
* That data has to be stored somewhere in memory on the server, so this could cause problems with high traffic situations
Some Follow up Notes on OO
--------------------------
1. Use dependency injection! Your object has no business creating other objects in its constructor. Pass them in as arguments. It'll make your objects more flexible, easier to test, easier to debug, and save a lot of headaches.
2. 1 class per file, don't piledrive your PHP files. Keep it nice and simple
3. Your `IncludedObject` might as well just have the public variable, there's no point in having a getter and a setter if you can just access it directly. Either make that variable private or get rid of those getter/setters
4. Don't call things "->setXYZ()" etc. Just call it `->xyz()`, call it what it is. Why write `$person->getName()` when you can have `$person->name()`? Much simpler.
5. The same goes for setters, why have `$person->setName()` when you can have `$person->rename()`?
But most importantly, do you really need objects here? Making things OO doesn't mean that you're writing better code, it just means you're trying OO. If your objects have no internal state, and don't implement any abstract interfaces, then you gain nothing from using classes, and it's not OO.
Don't make a huge mess of functions and wrap them in a class and pretend it's OO, it isn't, it's just extra typing for you. So save yourself the hassle. It's ok for the entry point of your plugin to be a function. It's ok to put quick filters as plain functions, you don't have to put everything in a class.
You might be learning, but don't force yourself to use classes under the guise of "OO", it isn't OO, and you'll just be learning bad habits. |
352,142 | <p>I'm testing WordPress 5.3 (<em>5.3-RC4-46673</em>) with my theme. I have <code>WP_DEBUG</code> enabled. I notice the following error in the dashboard now:</p>
<blockquote>
<p>Notice: add_submenu_page was called incorrectly. The seventh parameter passed to add_submenu_page() should be an integer representing menu position. Please see Debugging in WordPress for more information. (This message was added in version 5.3.0.) in /app/wp-includes/functions.php on line 4903</p>
</blockquote>
<p>There's a related ticket for this error here: <a href="https://core.trac.wordpress.org/ticket/48249" rel="nofollow noreferrer">Trac Ticket #48249</a></p>
<p><strong>Troubleshooting</strong>
The theme I'm using is a child theme.</p>
<ul>
<li>Disabled all plugins, issue persists.</li>
<li>Issue happens with child them active and parent theme active.</li>
<li>Issue goes away with twentynineteen.</li>
</ul>
<p>So it's definitely within the theme. Just not sure how to go about tracking this down. </p>
| [
{
"answer_id": 352147,
"author": "yannibmbr",
"author_id": 56791,
"author_profile": "https://wordpress.stackexchange.com/users/56791",
"pm_score": 2,
"selected": false,
"text": "<p>I was able to track this down to the culprit function <code>add_theme_page()</code>. There</p>\n<p>There was an additional parameter, per <a href=\"https://developer.wordpress.org/reference/functions/add_theme_page/\" rel=\"nofollow noreferrer\">the codex for add_theme_page()</a> that needed to be removed. Removing that seemed to help.</p>\n<pre><code>function fivehundred_register_admin_menu() {\n add_theme_page(\n '500 Settings',\n '500 Settings',\n 'manage_options',\n 'theme-settings',\n 'fivehundred_admin_menu',\n plugins_url( '/ignitiondeck/images/ignitiondeck-menu.png' )\n );\n}\n\nadd_action(\n 'admin_menu',\n 'fivehundred_register_admin_menu'\n);\n</code></pre>\n<p>Fixed code</p>\n<pre><code>function fivehundred_register_admin_menu() {\n add_theme_page(\n '500 Settings',\n '500 Settings',\n 'manage_options',\n 'theme-settings',\n 'fivehundred_admin_menu'\n );\n}\n\nadd_action(\n 'admin_menu',\n 'fivehundred_register_admin_menu'\n);\n\n</code></pre>\n"
},
{
"answer_id": 355942,
"author": "jogesh_pi",
"author_id": 13331,
"author_profile": "https://wordpress.stackexchange.com/users/13331",
"pm_score": 0,
"selected": false,
"text": "<p>You could avoid the warning by adding the seventh parameter as <code>null</code>.</p>\n<pre><code>function fivehundred_register_admin_menu() {\n add_theme_page(\n '500 Settings',\n '500 Settings',\n 'manage_options',\n 'theme-settings',\n 'fivehundred_admin_menu',\n plugins_url( '/ignitiondeck/images/ignitiondeck-menu.png' ),\n null\n );\n}\n\nadd_action(\n 'admin_menu',\n 'fivehundred_register_admin_menu'\n);\n</code></pre>\n"
},
{
"answer_id": 356799,
"author": "Christopher S.",
"author_id": 127679,
"author_profile": "https://wordpress.stackexchange.com/users/127679",
"pm_score": 0,
"selected": false,
"text": "<p><em>This same error is also being applied to argument issues in the add_pages_page() function.</em> </p>\n\n<p>For anyone else not using add_theme_page() or add_submenu_page() functions look for your usage of add_pages_page() and correct the arguments.</p>\n\n<p>In my case I needed to remove the first argument which was null and give the page a title.</p>\n"
},
{
"answer_id": 395142,
"author": "alo Malbarez",
"author_id": 62765,
"author_profile": "https://wordpress.stackexchange.com/users/62765",
"pm_score": 0,
"selected": false,
"text": "<p>This Notice can be triggered by several variations/wrappers of the function <code>add_submenu_page</code>.</p>\n<p>as of WP v5.8</p>\n<ul>\n<li>add_plugins_page</li>\n<li>add_users_page</li>\n<li>add_dashboard_page</li>\n<li>add_posts_page</li>\n<li>add_media_page</li>\n<li>add_links_page</li>\n<li>add_pages_page</li>\n<li>add_comments_page</li>\n<li>add_management_page</li>\n<li>add_options_page</li>\n<li>add_theme_page</li>\n</ul>\n<p>To narrow the scope looking for the right function, we can modify the core file <code>./wp-admin/includes/plugin.php</code> ( around line 1420 ) to be more verbose about it.</p>\n<pre><code>_doing_it_wrong(\n __FUNCTION__,\n sprintf(\n /* translators: %s: add_submenu_page() */\n __( 'The seventh parameter passed to %s should be an integer representing menu position. %s' ),\n '<code>add_submenu_page()</code>',\n print_r( $new_sub_menu, true )\n ),\n '5.3.0'\n);\n\n</code></pre>\n<p>In my case the offending function was <code>add_dashboard_page</code></p>\n<pre><code>add_dashboard_page(\n 'Link Builder',\n 'Link Builder',\n 'manage_options',\n 'mytheme-woocommerce-helper',\n array( $this, 'mytheme_woocommerce_helper_create_admin_page' ),\n 'dashicons-admin-generic',\n 2\n);\n</code></pre>\n<p>Notice before edit core file:</p>\n<pre><code>PHP Notice: add_submenu_page was called <strong>incorrectly</strong>. \nThe seventh parameter passed to <code>add_submenu_page()</code> \nshould be an integer representing menu position. \nPlease see <a href="https://wordpress.org/support/article/debugging-in-wordpress/">Debugging in WordPress</a> for more information. \n(This message was added in version 5.3.0.) in wp-includes/functions.php on line 5535\n</code></pre>\n<p>Notice after edit core file:</p>\n<pre><code>PHP Notice: add_submenu_page was called <strong>incorrectly</strong>. \nThe seventh parameter passed to <code>add_submenu_page()</code> \nshould be an integer representing menu position. \nArray\n(\n [0] => Link Builder\n [1] => manage_options\n [2] => mytheme-woocommerce-helper\n [3] => Link Builder\n)\n</code></pre>\n<p><strong>warning/disclaimer/notes</strong></p>\n<p>Do this edit only in a development instance. WP core updates or upgrades will revert the changes. Plugins like wordfence will emit a warning and maybe revert the changes.</p>\n"
}
] | 2019/11/08 | [
"https://wordpress.stackexchange.com/questions/352142",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/56791/"
] | I'm testing WordPress 5.3 (*5.3-RC4-46673*) with my theme. I have `WP_DEBUG` enabled. I notice the following error in the dashboard now:
>
> Notice: add\_submenu\_page was called incorrectly. The seventh parameter passed to add\_submenu\_page() should be an integer representing menu position. Please see Debugging in WordPress for more information. (This message was added in version 5.3.0.) in /app/wp-includes/functions.php on line 4903
>
>
>
There's a related ticket for this error here: [Trac Ticket #48249](https://core.trac.wordpress.org/ticket/48249)
**Troubleshooting**
The theme I'm using is a child theme.
* Disabled all plugins, issue persists.
* Issue happens with child them active and parent theme active.
* Issue goes away with twentynineteen.
So it's definitely within the theme. Just not sure how to go about tracking this down. | I was able to track this down to the culprit function `add_theme_page()`. There
There was an additional parameter, per [the codex for add\_theme\_page()](https://developer.wordpress.org/reference/functions/add_theme_page/) that needed to be removed. Removing that seemed to help.
```
function fivehundred_register_admin_menu() {
add_theme_page(
'500 Settings',
'500 Settings',
'manage_options',
'theme-settings',
'fivehundred_admin_menu',
plugins_url( '/ignitiondeck/images/ignitiondeck-menu.png' )
);
}
add_action(
'admin_menu',
'fivehundred_register_admin_menu'
);
```
Fixed code
```
function fivehundred_register_admin_menu() {
add_theme_page(
'500 Settings',
'500 Settings',
'manage_options',
'theme-settings',
'fivehundred_admin_menu'
);
}
add_action(
'admin_menu',
'fivehundred_register_admin_menu'
);
``` |
352,198 | <p>I have added an acf image gallery for archive terms and I would like to take those images and insert one image from the gallery every 3 posts in the term archive. This is what I have so far but I am not yet getting them to distribute sequentially every 3 posts. </p>
<p>1-2-3 posts<br>
Image 1<br>
4-5-6 posts<br>
Image 2<br>
7-8-9 posts<br>
Image 3<br></p>
<pre><code>// get the current taxonomy term
$queried_object = get_queried_object();
$taxonomy = $queried_object->taxonomy;
$term_id = $queried_object->term_id;
$images = get_field('term_gallery', $taxonomy .'_' . $term_id); //image ids
$size = 'full'; // (thumbnail, medium, large, full or custom size)
$counter = 1;
if ( have_posts() ) :
while ( have_posts() ) : the_post();
get_template_part( 'template-parts/content', get_post_type() );
?>
<?php /*//////////////////INSERT IMAGE///////////*/?>
<?php if($counter % 3 == 0): ?>
<?php if( $images ): ?>
<?php foreach( $images as $image_id ): ?>
<div class="image-<?php echo $counter;?>">
<?php echo wp_get_attachment_image( $image_id, $size ); ?>
</div>
<?php endforeach; ?>
<?php endif;?>
<?php endif;?>
<?php /*/////////////////INSERT IMAGE///////////*/?>
<?php
$counter++;
endwhile;
endif;
</code></pre>
<p>With the above the entire gallery is shown every 3 posts. As in</p>
<p>1-2-3 posts<br>
Image 1 + Image 2 + Image 3<br>
4-5-6 posts<br>
Image 1 + Image 2 + Image 3<br></p>
<p><strong>UPDATE</strong> don't know how i got this but it works partly, it just doesn't work with pagination after first page? No images at all show on the next page when I expected to get the next 3 images of the gallery.</p>
<pre><code>// get the current taxonomy term
$queried_object = get_queried_object();
$taxonomy = $queried_object->taxonomy;
$term_id = $queried_object->term_id;
$images = get_field('term_gallery', $taxonomy .'_' . $term_id);
$size = 'full'; // (thumbnail, medium, large, full or custom size)
$images_len = count($images); // max
$counter = 1;
$img_ct = 0;
if ( have_posts() ) :
while ( have_posts() ) : the_post();
get_template_part( 'template-parts/content', get_post_type() );
?>
<?php /*//////////////////INSERT IMAGE///////////*/?>
<?php if( $images ): ?>
<?php if($counter % 3 == 0): ?>
<?php if($img_ct == $images_len ) $img_ct = 0;?>
<div class="image-<?php echo $img_ct;?>">
<?php echo wp_get_attachment_image( $images[$img_ct], $size ); ?>
</div>
<?php $img_ct++;?>
<?php endif;?>
<?php endif;?>
<?php /*//////////////////INSERT IMAGE///////////*/?>
<?php
$counter++;
endwhile;
endif;
</code></pre>
| [
{
"answer_id": 352147,
"author": "yannibmbr",
"author_id": 56791,
"author_profile": "https://wordpress.stackexchange.com/users/56791",
"pm_score": 2,
"selected": false,
"text": "<p>I was able to track this down to the culprit function <code>add_theme_page()</code>. There</p>\n<p>There was an additional parameter, per <a href=\"https://developer.wordpress.org/reference/functions/add_theme_page/\" rel=\"nofollow noreferrer\">the codex for add_theme_page()</a> that needed to be removed. Removing that seemed to help.</p>\n<pre><code>function fivehundred_register_admin_menu() {\n add_theme_page(\n '500 Settings',\n '500 Settings',\n 'manage_options',\n 'theme-settings',\n 'fivehundred_admin_menu',\n plugins_url( '/ignitiondeck/images/ignitiondeck-menu.png' )\n );\n}\n\nadd_action(\n 'admin_menu',\n 'fivehundred_register_admin_menu'\n);\n</code></pre>\n<p>Fixed code</p>\n<pre><code>function fivehundred_register_admin_menu() {\n add_theme_page(\n '500 Settings',\n '500 Settings',\n 'manage_options',\n 'theme-settings',\n 'fivehundred_admin_menu'\n );\n}\n\nadd_action(\n 'admin_menu',\n 'fivehundred_register_admin_menu'\n);\n\n</code></pre>\n"
},
{
"answer_id": 355942,
"author": "jogesh_pi",
"author_id": 13331,
"author_profile": "https://wordpress.stackexchange.com/users/13331",
"pm_score": 0,
"selected": false,
"text": "<p>You could avoid the warning by adding the seventh parameter as <code>null</code>.</p>\n<pre><code>function fivehundred_register_admin_menu() {\n add_theme_page(\n '500 Settings',\n '500 Settings',\n 'manage_options',\n 'theme-settings',\n 'fivehundred_admin_menu',\n plugins_url( '/ignitiondeck/images/ignitiondeck-menu.png' ),\n null\n );\n}\n\nadd_action(\n 'admin_menu',\n 'fivehundred_register_admin_menu'\n);\n</code></pre>\n"
},
{
"answer_id": 356799,
"author": "Christopher S.",
"author_id": 127679,
"author_profile": "https://wordpress.stackexchange.com/users/127679",
"pm_score": 0,
"selected": false,
"text": "<p><em>This same error is also being applied to argument issues in the add_pages_page() function.</em> </p>\n\n<p>For anyone else not using add_theme_page() or add_submenu_page() functions look for your usage of add_pages_page() and correct the arguments.</p>\n\n<p>In my case I needed to remove the first argument which was null and give the page a title.</p>\n"
},
{
"answer_id": 395142,
"author": "alo Malbarez",
"author_id": 62765,
"author_profile": "https://wordpress.stackexchange.com/users/62765",
"pm_score": 0,
"selected": false,
"text": "<p>This Notice can be triggered by several variations/wrappers of the function <code>add_submenu_page</code>.</p>\n<p>as of WP v5.8</p>\n<ul>\n<li>add_plugins_page</li>\n<li>add_users_page</li>\n<li>add_dashboard_page</li>\n<li>add_posts_page</li>\n<li>add_media_page</li>\n<li>add_links_page</li>\n<li>add_pages_page</li>\n<li>add_comments_page</li>\n<li>add_management_page</li>\n<li>add_options_page</li>\n<li>add_theme_page</li>\n</ul>\n<p>To narrow the scope looking for the right function, we can modify the core file <code>./wp-admin/includes/plugin.php</code> ( around line 1420 ) to be more verbose about it.</p>\n<pre><code>_doing_it_wrong(\n __FUNCTION__,\n sprintf(\n /* translators: %s: add_submenu_page() */\n __( 'The seventh parameter passed to %s should be an integer representing menu position. %s' ),\n '<code>add_submenu_page()</code>',\n print_r( $new_sub_menu, true )\n ),\n '5.3.0'\n);\n\n</code></pre>\n<p>In my case the offending function was <code>add_dashboard_page</code></p>\n<pre><code>add_dashboard_page(\n 'Link Builder',\n 'Link Builder',\n 'manage_options',\n 'mytheme-woocommerce-helper',\n array( $this, 'mytheme_woocommerce_helper_create_admin_page' ),\n 'dashicons-admin-generic',\n 2\n);\n</code></pre>\n<p>Notice before edit core file:</p>\n<pre><code>PHP Notice: add_submenu_page was called <strong>incorrectly</strong>. \nThe seventh parameter passed to <code>add_submenu_page()</code> \nshould be an integer representing menu position. \nPlease see <a href="https://wordpress.org/support/article/debugging-in-wordpress/">Debugging in WordPress</a> for more information. \n(This message was added in version 5.3.0.) in wp-includes/functions.php on line 5535\n</code></pre>\n<p>Notice after edit core file:</p>\n<pre><code>PHP Notice: add_submenu_page was called <strong>incorrectly</strong>. \nThe seventh parameter passed to <code>add_submenu_page()</code> \nshould be an integer representing menu position. \nArray\n(\n [0] => Link Builder\n [1] => manage_options\n [2] => mytheme-woocommerce-helper\n [3] => Link Builder\n)\n</code></pre>\n<p><strong>warning/disclaimer/notes</strong></p>\n<p>Do this edit only in a development instance. WP core updates or upgrades will revert the changes. Plugins like wordfence will emit a warning and maybe revert the changes.</p>\n"
}
] | 2019/11/08 | [
"https://wordpress.stackexchange.com/questions/352198",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178078/"
] | I have added an acf image gallery for archive terms and I would like to take those images and insert one image from the gallery every 3 posts in the term archive. This is what I have so far but I am not yet getting them to distribute sequentially every 3 posts.
1-2-3 posts
Image 1
4-5-6 posts
Image 2
7-8-9 posts
Image 3
```
// get the current taxonomy term
$queried_object = get_queried_object();
$taxonomy = $queried_object->taxonomy;
$term_id = $queried_object->term_id;
$images = get_field('term_gallery', $taxonomy .'_' . $term_id); //image ids
$size = 'full'; // (thumbnail, medium, large, full or custom size)
$counter = 1;
if ( have_posts() ) :
while ( have_posts() ) : the_post();
get_template_part( 'template-parts/content', get_post_type() );
?>
<?php /*//////////////////INSERT IMAGE///////////*/?>
<?php if($counter % 3 == 0): ?>
<?php if( $images ): ?>
<?php foreach( $images as $image_id ): ?>
<div class="image-<?php echo $counter;?>">
<?php echo wp_get_attachment_image( $image_id, $size ); ?>
</div>
<?php endforeach; ?>
<?php endif;?>
<?php endif;?>
<?php /*/////////////////INSERT IMAGE///////////*/?>
<?php
$counter++;
endwhile;
endif;
```
With the above the entire gallery is shown every 3 posts. As in
1-2-3 posts
Image 1 + Image 2 + Image 3
4-5-6 posts
Image 1 + Image 2 + Image 3
**UPDATE** don't know how i got this but it works partly, it just doesn't work with pagination after first page? No images at all show on the next page when I expected to get the next 3 images of the gallery.
```
// get the current taxonomy term
$queried_object = get_queried_object();
$taxonomy = $queried_object->taxonomy;
$term_id = $queried_object->term_id;
$images = get_field('term_gallery', $taxonomy .'_' . $term_id);
$size = 'full'; // (thumbnail, medium, large, full or custom size)
$images_len = count($images); // max
$counter = 1;
$img_ct = 0;
if ( have_posts() ) :
while ( have_posts() ) : the_post();
get_template_part( 'template-parts/content', get_post_type() );
?>
<?php /*//////////////////INSERT IMAGE///////////*/?>
<?php if( $images ): ?>
<?php if($counter % 3 == 0): ?>
<?php if($img_ct == $images_len ) $img_ct = 0;?>
<div class="image-<?php echo $img_ct;?>">
<?php echo wp_get_attachment_image( $images[$img_ct], $size ); ?>
</div>
<?php $img_ct++;?>
<?php endif;?>
<?php endif;?>
<?php /*//////////////////INSERT IMAGE///////////*/?>
<?php
$counter++;
endwhile;
endif;
``` | I was able to track this down to the culprit function `add_theme_page()`. There
There was an additional parameter, per [the codex for add\_theme\_page()](https://developer.wordpress.org/reference/functions/add_theme_page/) that needed to be removed. Removing that seemed to help.
```
function fivehundred_register_admin_menu() {
add_theme_page(
'500 Settings',
'500 Settings',
'manage_options',
'theme-settings',
'fivehundred_admin_menu',
plugins_url( '/ignitiondeck/images/ignitiondeck-menu.png' )
);
}
add_action(
'admin_menu',
'fivehundred_register_admin_menu'
);
```
Fixed code
```
function fivehundred_register_admin_menu() {
add_theme_page(
'500 Settings',
'500 Settings',
'manage_options',
'theme-settings',
'fivehundred_admin_menu'
);
}
add_action(
'admin_menu',
'fivehundred_register_admin_menu'
);
``` |
352,323 | <p>This method for @SE <a href="https://wordpress.stackexchange.com/questions/319035/how-would-i-get-a-taxonomy-category-list-inside-a-gutenberg-block/336924#336924">How would I get a taxonomy/category list inside a Gutenberg block?</a> does NOT work for custom taxonomies, e.g.:</p>
<pre><code>wp.data.select('core').getEntityRecords('taxonomy', 'my-custom-taxonomy', {per_page: -1})
</code></pre>
<p>and only returns null, whereas the core category, i.e. "category", returns:</p>
<pre><code>wp.data.select('core').getEntityRecords('taxonomy', 'category', {per_page: -1})
</code></pre>
<p>returns an entire array of taxonomy term data such as:</p>
<ul>
<li>count</li>
<li>description</li>
<li>id</li>
<li>link</li>
<li>meta []</li>
<li>name</li>
<li>parent</li>
<li>slug</li>
<li>taxonomy
etc.</li>
</ul>
<p>The official docs at: <a href="https://developer.wordpress.org/block-editor/data/data-core/#getEntityRecords" rel="nofollow noreferrer">https://developer.wordpress.org/block-editor/data/data-core/#getEntityRecords</a> are woefully lacking, and whilst there are references to the "getEntityRecords" in GitHub at e.g.: <a href="https://github.com/WordPress/gutenberg/blob/04e142e9cbd06a45c4ea297ec573d389955c13be/packages/core-data/src/entities.js" rel="nofollow noreferrer">https://github.com/WordPress/gutenberg/blob/04e142e9cbd06a45c4ea297ec573d389955c13be/packages/core-data/src/entities.js</a> there is little in the way of documentation to help!</p>
<p>So here is the question:</p>
<p><strong>How can you return the list of custom taxonomies using the wp.data.select('core').getEntityRecords method?</strong></p>
<p>OR do you need to create a custom store, or use the wp.data Backbone JS?</p>
| [
{
"answer_id": 352331,
"author": "Digitalle",
"author_id": 124083,
"author_profile": "https://wordpress.stackexchange.com/users/124083",
"pm_score": 1,
"selected": false,
"text": "<p><strong>ANSWER UPDATE:</strong> IF you have a large number of terms within your taxonomy, i.e. more than 100, you will need to add a {per_page: 100} args limiter in order NOT to get an empty array back, as you will if you try getting ALL results back, i.e. per_page: -1</p>\n\n<p>so you will need something like:</p>\n\n<pre><code>wp.data.select('core').getEntityRecords('taxonomy', 'my-custom-taxonomy', {per_page: 100})\n</code></pre>\n\n<p>and that is the maximum on a single API call, although you can then append a \"paging\" arg, e.g.:</p>\n\n<p><code>{per_page: 100, page: 2}</code></p>\n"
},
{
"answer_id": 352365,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li><p>The <code>getEntityRecords()</code> method <a href=\"https://github.com/WordPress/gutenberg/blob/04e142e9cbd06a45c4ea297ec573d389955c13be/packages/core-data/src/resolvers.js#L60\" rel=\"nofollow noreferrer\">uses the REST API</a>, so make sure the taxonomy is enabled for the REST API. You can enable it via the <code>show_in_rest</code> parameter when registering the taxonomy using <a href=\"https://developer.wordpress.org/reference/functions/register_taxonomy/\" rel=\"nofollow noreferrer\"><code>register_taxonomy()</code></a>.</p></li>\n<li><p>With <code>getEntityRecords()</code>, if you set <code>per_page</code> to <code>-1</code>, it will actually be changed to <code>100</code>, which as you've figured it out, is the max number of results returned for a single API request (details <a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/#pagination-parameters\" rel=\"nofollow noreferrer\">here</a>). Hence that's why <code>per_page: -1</code> <em>should</em> work <em>with <code>getEntityRecords()</code></em>.</p></li>\n<li><p>Any AJAX/remote requests would not give you <em>immediate</em> results and we would need to wait a moment until the browser receives the response from the server. So this is probably the actual reason to why you're not getting any results immediately upon first call to <code>getEntityRecords()</code>.</p></li>\n</ol>\n\n<p>With that said, on subsequent calls (for the same query), you should get immediate results because <code>getEntityRecords()</code> cache the results (for performance reasons — you wouldn't want each call to <code>getEntityRecords()</code> takes several <em>seconds</em> to give you the results, would you?).</p>\n\n<p>So try:</p>\n\n<ol>\n<li><p><a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/api-fetch\" rel=\"nofollow noreferrer\"><code>wp.apiFetch()</code></a> which is used by <code>getEntityRecords()</code>: Both these work; <code>apiFetch()</code> makes request to <code>http://example.com/wp-json/wp/v2/your_tax?per_page=100</code>:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>wp.apiFetch( { path: '/wp/v2/your_tax?per_page=-1' } )\n // 'terms' contains valid term objects\n .then( terms => console.log( terms ) );\n\nwp.apiFetch( { path: '/wp/v2/your_tax?per_page=100' } )\n // 'terms' contains valid term objects\n .then( terms => console.log( terms ) );\n</code></pre></li>\n<li><p><a href=\"https://developer.mozilla.org/en/docs/Web/API/Fetch_API\" rel=\"nofollow noreferrer\"><code>fetch()</code></a> which is used internally by <code>wp.apiFetch()</code>:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>fetch( '/wp-json/wp/v2/your_tax?per_page=-1' )\n .then( res => res.json() )\n // 'terms' contains an error about per_page should be between 1 and 100\n .then( terms => console.log( terms ) );\n\nfetch( '/wp-json/wp/v2/your_tax?per_page=100' )\n .then( res => res.json() )\n // 'terms' contains valid term objects\n .then( terms => console.log( terms ) );\n</code></pre></li>\n</ol>\n\n<p>So if you make manual requests to <code>/wp-json/wp/v2/your_tax</code> (i.e. a taxonomy terms REST API), then you should not set the <code>per_page</code> to <code>-1</code>. But with <code>wp.apiFetch()</code> and functions which uses <code>apiFetch()</code> like <code>getEntityRecords()</code>, you <em>can</em> use that <code>-1</code> although you should <em>not</em>…</p>\n"
}
] | 2019/11/11 | [
"https://wordpress.stackexchange.com/questions/352323",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124083/"
] | This method for @SE [How would I get a taxonomy/category list inside a Gutenberg block?](https://wordpress.stackexchange.com/questions/319035/how-would-i-get-a-taxonomy-category-list-inside-a-gutenberg-block/336924#336924) does NOT work for custom taxonomies, e.g.:
```
wp.data.select('core').getEntityRecords('taxonomy', 'my-custom-taxonomy', {per_page: -1})
```
and only returns null, whereas the core category, i.e. "category", returns:
```
wp.data.select('core').getEntityRecords('taxonomy', 'category', {per_page: -1})
```
returns an entire array of taxonomy term data such as:
* count
* description
* id
* link
* meta []
* name
* parent
* slug
* taxonomy
etc.
The official docs at: <https://developer.wordpress.org/block-editor/data/data-core/#getEntityRecords> are woefully lacking, and whilst there are references to the "getEntityRecords" in GitHub at e.g.: <https://github.com/WordPress/gutenberg/blob/04e142e9cbd06a45c4ea297ec573d389955c13be/packages/core-data/src/entities.js> there is little in the way of documentation to help!
So here is the question:
**How can you return the list of custom taxonomies using the wp.data.select('core').getEntityRecords method?**
OR do you need to create a custom store, or use the wp.data Backbone JS? | 1. The `getEntityRecords()` method [uses the REST API](https://github.com/WordPress/gutenberg/blob/04e142e9cbd06a45c4ea297ec573d389955c13be/packages/core-data/src/resolvers.js#L60), so make sure the taxonomy is enabled for the REST API. You can enable it via the `show_in_rest` parameter when registering the taxonomy using [`register_taxonomy()`](https://developer.wordpress.org/reference/functions/register_taxonomy/).
2. With `getEntityRecords()`, if you set `per_page` to `-1`, it will actually be changed to `100`, which as you've figured it out, is the max number of results returned for a single API request (details [here](https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/#pagination-parameters)). Hence that's why `per_page: -1` *should* work *with `getEntityRecords()`*.
3. Any AJAX/remote requests would not give you *immediate* results and we would need to wait a moment until the browser receives the response from the server. So this is probably the actual reason to why you're not getting any results immediately upon first call to `getEntityRecords()`.
With that said, on subsequent calls (for the same query), you should get immediate results because `getEntityRecords()` cache the results (for performance reasons — you wouldn't want each call to `getEntityRecords()` takes several *seconds* to give you the results, would you?).
So try:
1. [`wp.apiFetch()`](https://github.com/WordPress/gutenberg/tree/master/packages/api-fetch) which is used by `getEntityRecords()`: Both these work; `apiFetch()` makes request to `http://example.com/wp-json/wp/v2/your_tax?per_page=100`:
```js
wp.apiFetch( { path: '/wp/v2/your_tax?per_page=-1' } )
// 'terms' contains valid term objects
.then( terms => console.log( terms ) );
wp.apiFetch( { path: '/wp/v2/your_tax?per_page=100' } )
// 'terms' contains valid term objects
.then( terms => console.log( terms ) );
```
2. [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) which is used internally by `wp.apiFetch()`:
```js
fetch( '/wp-json/wp/v2/your_tax?per_page=-1' )
.then( res => res.json() )
// 'terms' contains an error about per_page should be between 1 and 100
.then( terms => console.log( terms ) );
fetch( '/wp-json/wp/v2/your_tax?per_page=100' )
.then( res => res.json() )
// 'terms' contains valid term objects
.then( terms => console.log( terms ) );
```
So if you make manual requests to `/wp-json/wp/v2/your_tax` (i.e. a taxonomy terms REST API), then you should not set the `per_page` to `-1`. But with `wp.apiFetch()` and functions which uses `apiFetch()` like `getEntityRecords()`, you *can* use that `-1` although you should *not*… |
352,354 | <p>Hello would anybody be able to help my situation? at this point I'm wondering if it is a database issue because when i try the alternative to drag and drop an image into my media library i get this error-" could not insert post into the database". the hello? i have the permissions set up correct upload folder set to 744 as are the inner folders, the files set to 644. </p>
<p>also have set my wp-config.php file to direct to the correct table for my .sql database so not I'm stumped</p>
<p>thanks for the help</p>
| [
{
"answer_id": 352331,
"author": "Digitalle",
"author_id": 124083,
"author_profile": "https://wordpress.stackexchange.com/users/124083",
"pm_score": 1,
"selected": false,
"text": "<p><strong>ANSWER UPDATE:</strong> IF you have a large number of terms within your taxonomy, i.e. more than 100, you will need to add a {per_page: 100} args limiter in order NOT to get an empty array back, as you will if you try getting ALL results back, i.e. per_page: -1</p>\n\n<p>so you will need something like:</p>\n\n<pre><code>wp.data.select('core').getEntityRecords('taxonomy', 'my-custom-taxonomy', {per_page: 100})\n</code></pre>\n\n<p>and that is the maximum on a single API call, although you can then append a \"paging\" arg, e.g.:</p>\n\n<p><code>{per_page: 100, page: 2}</code></p>\n"
},
{
"answer_id": 352365,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li><p>The <code>getEntityRecords()</code> method <a href=\"https://github.com/WordPress/gutenberg/blob/04e142e9cbd06a45c4ea297ec573d389955c13be/packages/core-data/src/resolvers.js#L60\" rel=\"nofollow noreferrer\">uses the REST API</a>, so make sure the taxonomy is enabled for the REST API. You can enable it via the <code>show_in_rest</code> parameter when registering the taxonomy using <a href=\"https://developer.wordpress.org/reference/functions/register_taxonomy/\" rel=\"nofollow noreferrer\"><code>register_taxonomy()</code></a>.</p></li>\n<li><p>With <code>getEntityRecords()</code>, if you set <code>per_page</code> to <code>-1</code>, it will actually be changed to <code>100</code>, which as you've figured it out, is the max number of results returned for a single API request (details <a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/#pagination-parameters\" rel=\"nofollow noreferrer\">here</a>). Hence that's why <code>per_page: -1</code> <em>should</em> work <em>with <code>getEntityRecords()</code></em>.</p></li>\n<li><p>Any AJAX/remote requests would not give you <em>immediate</em> results and we would need to wait a moment until the browser receives the response from the server. So this is probably the actual reason to why you're not getting any results immediately upon first call to <code>getEntityRecords()</code>.</p></li>\n</ol>\n\n<p>With that said, on subsequent calls (for the same query), you should get immediate results because <code>getEntityRecords()</code> cache the results (for performance reasons — you wouldn't want each call to <code>getEntityRecords()</code> takes several <em>seconds</em> to give you the results, would you?).</p>\n\n<p>So try:</p>\n\n<ol>\n<li><p><a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/api-fetch\" rel=\"nofollow noreferrer\"><code>wp.apiFetch()</code></a> which is used by <code>getEntityRecords()</code>: Both these work; <code>apiFetch()</code> makes request to <code>http://example.com/wp-json/wp/v2/your_tax?per_page=100</code>:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>wp.apiFetch( { path: '/wp/v2/your_tax?per_page=-1' } )\n // 'terms' contains valid term objects\n .then( terms => console.log( terms ) );\n\nwp.apiFetch( { path: '/wp/v2/your_tax?per_page=100' } )\n // 'terms' contains valid term objects\n .then( terms => console.log( terms ) );\n</code></pre></li>\n<li><p><a href=\"https://developer.mozilla.org/en/docs/Web/API/Fetch_API\" rel=\"nofollow noreferrer\"><code>fetch()</code></a> which is used internally by <code>wp.apiFetch()</code>:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>fetch( '/wp-json/wp/v2/your_tax?per_page=-1' )\n .then( res => res.json() )\n // 'terms' contains an error about per_page should be between 1 and 100\n .then( terms => console.log( terms ) );\n\nfetch( '/wp-json/wp/v2/your_tax?per_page=100' )\n .then( res => res.json() )\n // 'terms' contains valid term objects\n .then( terms => console.log( terms ) );\n</code></pre></li>\n</ol>\n\n<p>So if you make manual requests to <code>/wp-json/wp/v2/your_tax</code> (i.e. a taxonomy terms REST API), then you should not set the <code>per_page</code> to <code>-1</code>. But with <code>wp.apiFetch()</code> and functions which uses <code>apiFetch()</code> like <code>getEntityRecords()</code>, you <em>can</em> use that <code>-1</code> although you should <em>not</em>…</p>\n"
}
] | 2019/11/12 | [
"https://wordpress.stackexchange.com/questions/352354",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178184/"
] | Hello would anybody be able to help my situation? at this point I'm wondering if it is a database issue because when i try the alternative to drag and drop an image into my media library i get this error-" could not insert post into the database". the hello? i have the permissions set up correct upload folder set to 744 as are the inner folders, the files set to 644.
also have set my wp-config.php file to direct to the correct table for my .sql database so not I'm stumped
thanks for the help | 1. The `getEntityRecords()` method [uses the REST API](https://github.com/WordPress/gutenberg/blob/04e142e9cbd06a45c4ea297ec573d389955c13be/packages/core-data/src/resolvers.js#L60), so make sure the taxonomy is enabled for the REST API. You can enable it via the `show_in_rest` parameter when registering the taxonomy using [`register_taxonomy()`](https://developer.wordpress.org/reference/functions/register_taxonomy/).
2. With `getEntityRecords()`, if you set `per_page` to `-1`, it will actually be changed to `100`, which as you've figured it out, is the max number of results returned for a single API request (details [here](https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/#pagination-parameters)). Hence that's why `per_page: -1` *should* work *with `getEntityRecords()`*.
3. Any AJAX/remote requests would not give you *immediate* results and we would need to wait a moment until the browser receives the response from the server. So this is probably the actual reason to why you're not getting any results immediately upon first call to `getEntityRecords()`.
With that said, on subsequent calls (for the same query), you should get immediate results because `getEntityRecords()` cache the results (for performance reasons — you wouldn't want each call to `getEntityRecords()` takes several *seconds* to give you the results, would you?).
So try:
1. [`wp.apiFetch()`](https://github.com/WordPress/gutenberg/tree/master/packages/api-fetch) which is used by `getEntityRecords()`: Both these work; `apiFetch()` makes request to `http://example.com/wp-json/wp/v2/your_tax?per_page=100`:
```js
wp.apiFetch( { path: '/wp/v2/your_tax?per_page=-1' } )
// 'terms' contains valid term objects
.then( terms => console.log( terms ) );
wp.apiFetch( { path: '/wp/v2/your_tax?per_page=100' } )
// 'terms' contains valid term objects
.then( terms => console.log( terms ) );
```
2. [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) which is used internally by `wp.apiFetch()`:
```js
fetch( '/wp-json/wp/v2/your_tax?per_page=-1' )
.then( res => res.json() )
// 'terms' contains an error about per_page should be between 1 and 100
.then( terms => console.log( terms ) );
fetch( '/wp-json/wp/v2/your_tax?per_page=100' )
.then( res => res.json() )
// 'terms' contains valid term objects
.then( terms => console.log( terms ) );
```
So if you make manual requests to `/wp-json/wp/v2/your_tax` (i.e. a taxonomy terms REST API), then you should not set the `per_page` to `-1`. But with `wp.apiFetch()` and functions which uses `apiFetch()` like `getEntityRecords()`, you *can* use that `-1` although you should *not*… |
352,413 | <p>I'm trying to override this Dokan plugin file in a child theme:</p>
<pre><code>wp-content/plugins/dokan-pro/includes/modules/vendor-verification/templates/verification-new.php
</code></pre>
<p>I can successfully override files in the normal Dokan templates folder:</p>
<pre><code>wp-content/plugins/dokan-pro/templates/path-to-file.php
</code></pre>
<p>by using</p>
<pre><code>wp-content/themes/theme-child/dokan/path-to-file.php
</code></pre>
<p>However, because the file I wish to override is in the includes folder, I'm having trouble finding the correct file path to override the verification-new.php file.</p>
<p>Any ideas?</p>
<p><em>P.S. The reason why I wish to override the file in a child theme rather than simply edit the original is so I can update Dokan and not lose the changes.</em></p>
| [
{
"answer_id": 352415,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>Child themes let you override templates, but these are not templates you're attempting to override. You can't drop in arbitrary files and override the parent theme, and WordPress can't do it's magic when <code>include</code> or <code>require</code> are used to load files.</p>\n\n<p>The reason this works for templates, is because WordPress doesn't load them with <code>include</code>, instead it uses filterable functions with custom logic, such as <code>get_template_part</code>.</p>\n\n<p>So there is no way to use the child theme method to swap out that file.\nYou do have the advantage that the child themes <code>functions.php</code> loads first.</p>\n\n<p>Instead, you're going to have to look at how the code in that theme loads itself, if it provides filters and actions, etc, much like you would when trying to override plugin code.</p>\n\n<p><strong>You'll need to contact the vendor for documentation and support</strong>, afterall you're a paying customer.</p>\n"
},
{
"answer_id": 382959,
"author": "Jo Kolov",
"author_id": 183334,
"author_profile": "https://wordpress.stackexchange.com/users/183334",
"pm_score": 2,
"selected": false,
"text": "<p>I was atttempting the same purpose.</p>\n<p>Dokan support has confirmed that only files contained in the dokan templates/ directory can be overriden in your theme.</p>\n<p>If you need to override modules's templates, I suggest to use this filter provided by dokan : <code>'dokan_locate_template'</code></p>\n<p>You can use it in your child-theme functions.php like this :</p>\n<pre><code>add_filter('dokan_locate_template', 'childtheme_dokan_locate_template', 20, 3);\nfunction childtheme_dokan_locate_template($template, $template_name, $template_path) {\n if ( preg_match('/\\/modules\\//i', $template) ) {\n $theme_template = str_replace(DOKAN_PRO_DIR . "/", get_stylesheet_directory() . '/' . dokan()->template_path(), $template);\n if ($template != $template_name && file_exists($theme_template)) {\n $template = $theme_template;\n }\n }\n return $template;\n}\n</code></pre>\n<p>This code allows to override Dokan PRO modules templates in your child theme.</p>\n<pre><code>wp-content/plugins/dokan-pro/includes/modules/vendor-verification/templates/verification-new.php\n</code></pre>\n<p>is overriden by this one</p>\n<pre><code>wp-content/themes/your-child-theme/dokan/modules/vendor-verification/templates/verification-new.php\n</code></pre>\n<p>Hope it helps.</p>\n"
},
{
"answer_id": 405252,
"author": "JerKlein",
"author_id": 221719,
"author_profile": "https://wordpress.stackexchange.com/users/221719",
"pm_score": 0,
"selected": false,
"text": "<p>To update Jo Kolov's answer, it almost works.\nBut you have to change this line :</p>\n<pre><code>add_filter('dokan_locate_template', 'childtheme_dokan_locate_template', 20, 3);\n</code></pre>\n<p>To :</p>\n<pre><code>add_filter('dokan_get_template_part', 'childtheme_dokan_locate_template', 20, 3);\n</code></pre>\n"
}
] | 2019/11/12 | [
"https://wordpress.stackexchange.com/questions/352413",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/174394/"
] | I'm trying to override this Dokan plugin file in a child theme:
```
wp-content/plugins/dokan-pro/includes/modules/vendor-verification/templates/verification-new.php
```
I can successfully override files in the normal Dokan templates folder:
```
wp-content/plugins/dokan-pro/templates/path-to-file.php
```
by using
```
wp-content/themes/theme-child/dokan/path-to-file.php
```
However, because the file I wish to override is in the includes folder, I'm having trouble finding the correct file path to override the verification-new.php file.
Any ideas?
*P.S. The reason why I wish to override the file in a child theme rather than simply edit the original is so I can update Dokan and not lose the changes.* | Child themes let you override templates, but these are not templates you're attempting to override. You can't drop in arbitrary files and override the parent theme, and WordPress can't do it's magic when `include` or `require` are used to load files.
The reason this works for templates, is because WordPress doesn't load them with `include`, instead it uses filterable functions with custom logic, such as `get_template_part`.
So there is no way to use the child theme method to swap out that file.
You do have the advantage that the child themes `functions.php` loads first.
Instead, you're going to have to look at how the code in that theme loads itself, if it provides filters and actions, etc, much like you would when trying to override plugin code.
**You'll need to contact the vendor for documentation and support**, afterall you're a paying customer. |
352,429 | <p>Specifically, I'm trying to get get the 'Layout Group' of a given ThemeREX Custom Layout (which as I understand is just a Custom Post Type), but am also interested in seeing what other properties are available for that post.</p>
<p>I tried</p>
<pre><code>print_r(get_post_meta(get_post(1738, 'ARRAY_A', 'display'),"",true));
</code></pre>
<p>but all that was returned was the number 1.</p>
<p>I'm guessing the meta is not what I'm looking for. Is there a way to iterate through all the custom properties that are registered with that post's CPT?</p>
| [
{
"answer_id": 352431,
"author": "Cas Dekkers",
"author_id": 153884,
"author_profile": "https://wordpress.stackexchange.com/users/153884",
"pm_score": 0,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>print_r( get_post_type_object( ( get_post( 1738 ) )->post_type ) );\n</code></pre>\n\n<p>It should print an object of class <a href=\"https://developer.wordpress.org/reference/classes/wp_post_type/\" rel=\"nofollow noreferrer\"><code>WP_Post_Type</code></a>.</p>\n"
},
{
"answer_id": 352449,
"author": "WP Updoot",
"author_id": 173692,
"author_profile": "https://wordpress.stackexchange.com/users/173692",
"pm_score": 1,
"selected": false,
"text": "<p>To get <strong>all</strong> the <code>post_meta</code> for a post, use:</p>\n\n<pre><code>$postmeta = get_post_meta(1738);\nprint_r($postmeta);\n</code></pre>\n\n<p>...which will give you a nested array of values that you can explore.</p>\n\n<p>Once you've worked out what you need, you can get the individual setting / property / meta with:</p>\n\n<pre><code>$mySetting = get_post_meta(1738, \"my-post-meta-key\", true);\n</code></pre>\n\n<p>Take a look at the <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\">relevant entry on the WordPress Codex</a> for a bit more detail.</p>\n"
}
] | 2019/11/12 | [
"https://wordpress.stackexchange.com/questions/352429",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118789/"
] | Specifically, I'm trying to get get the 'Layout Group' of a given ThemeREX Custom Layout (which as I understand is just a Custom Post Type), but am also interested in seeing what other properties are available for that post.
I tried
```
print_r(get_post_meta(get_post(1738, 'ARRAY_A', 'display'),"",true));
```
but all that was returned was the number 1.
I'm guessing the meta is not what I'm looking for. Is there a way to iterate through all the custom properties that are registered with that post's CPT? | To get **all** the `post_meta` for a post, use:
```
$postmeta = get_post_meta(1738);
print_r($postmeta);
```
...which will give you a nested array of values that you can explore.
Once you've worked out what you need, you can get the individual setting / property / meta with:
```
$mySetting = get_post_meta(1738, "my-post-meta-key", true);
```
Take a look at the [relevant entry on the WordPress Codex](https://developer.wordpress.org/reference/functions/get_post_meta/) for a bit more detail. |
352,442 | <p>If I run this code I get the desired result</p>
<pre><code><?php
$terms = get_terms( 'call-type' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
echo '\'' . $term->name . '\', ';
}
}
?>
</code></pre>
<p><strong>result</strong></p>
<p>'All', 'Completed', 'In progress', 'New',</p>
<p>But if I put the same code into an option all the select box it adds slashes to the results.</p>
<pre><code><select class="w-100" name="mf_term">
<option value="
<?php
$terms = get_terms( 'call-type' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
echo '\'' . $term->name . '\', ';
}
}
?>
">All</option>
</code></pre>
<p><strong>result</strong></p>
<p>\'All\', \'Completed\', \'In progress\', \'New\',</p>
<p><strong>How can I remove the slashes from the option in the select box</strong> </p>
<p><strong><em>Update Code</em></strong></p>
<pre><code><main>
<section id="" class="py-3">
<div id="" class="container-fuild">
<!-- Start User Level Report -->
<div id="" class="row mx-0 my-0">
<div class="col-lg-12">
<form action="" method="POST">
<div class="table-responsive ">
<table id="" class="table table-striped table-bordered text-center">
<tbody>
<tr>
<td class="align-middle">
Select Status<br />
<?php
$terms = get_terms( 'call-type' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
$term_option = '';
$sep = '';
foreach ( $terms as $term ) {
$term_option .= $sep."'".$term->name."'";
$sep = ",";
}
if(!empty($term_option))
{
?>
<select class="w-100" name="mf_term">
<option value=""></option>
<option value="<?php echo $term_option ;?>">All</option>
<?php
$mf_term_args = array(
'taxonomy' => 'call-type',
);
// Get Trems as array
$term2s = get_categories( $mf_term_args );
foreach ( $term2s as $term2 ) :
?>
<option value="<?php echo $term2->name ?>"><?php echo $term2->name ?></option>
<?php endforeach; ?>
</select>
<?php
}
}
?>
<?php
$mf_term = $_POST['mf_term'];
$mf_term = str_replace("\\\"", "\"", $mf_term);
$mf_term = str_replace("\\'", "'", $mf_term);
$mf_term = str_replace("\\\\", "\\", $mf_term);
?>
</td>
<td class="align-middle">
Select Department<br />
<!-- Script Starts here -->
<?php
$user_id = get_user_meta($user->ID);
$args = array(
'post_type' => 'department',
'posts_per_page' => -1,
);
$query = new WP_Query($args);
?>
<select class="w-100" name="mf_department">Select Department</p>
<option value=""></option>
<option value="'Marketing', 'Maintenance'">
All
</option>
<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<option value="<?php the_title(); ?>">
<?php the_title(); ?>
</option>
<?php endwhile; endif; ?>
</select>
<?php
$mf_department = $_POST['mf_department'];
$mf_department = str_replace("\\\"", "\"", $mf_department);
$mf_department = str_replace("\\'", "'", $mf_department);
$mf_department = str_replace("\\\\", "\\", $mf_department);
?>
<!-- Script Starts here -->
</td>
<td class="align-middle">
Start Date<br />
<input name="mf_start_date" type="date">
<?php
$mf_start_date = $_POST['mf_start_date'];
?>
</td>
<td class="align-middle">
End Date<br />
<input name="mf_end_date" type="date">
<?php
$mf_end_date = $_POST['mf_end_date'];
?>
</td>
<td class="align-middle">
By Store
</td>
<td class="align-middle">
By Area
</td>
<td class="align-middle">
By Region
</td>
<td class="align-middle">
<button class="btn btn-lg btn-primary btn-block" type="submit">Run Query</button>
</td>
</tr>
<tr class="">
<td colspan="8">
You have Selected Status: <strong class="text-danger"><?php echo $mf_term;?></strong> in the Department: <strong class="text-danger"><?php echo $mf_department;?></strong> from Starting Date: <strong class="text-danger"><?php echo $mf_start_date;?></strong> to Ending Date: <strong class="text-danger"><?php echo $mf_end_date;?></strong>.
</td>
</tr>
</tbody>
</table>
</div>
</form>
</div>
<div id="" class="col-lg-12">
<div class="table-responsive ">
<table id="data-table-1" class="table table-striped table-bordered">
<thead>
<tr>
<th>Call Ref#</th>
<th>Department</th>
<th>Type of Call</th>
<th></th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Call Ref#</th>
<th>Department</th>
<th>Col 3</th>
<th>Col 4</th>
<th>Col 5</th>
</tr>
</tfoot>
<tbody class="text-center">
<?php $query = new WP_Query(array(
'posts_per_page' => -1,
'post-type' => 'call',
'date_query' => array(
array(
'after' => $mf_start_date,
'before' => $mf_end_date,
'inclusive' => true,
),
),
//'terms' => 'All, New',
'tax_query' => array(
array(
'taxonomy' => 'call-type',
'field' => 'name',
'terms' => array( $mf_term ),
),
),
'author' => $current_user->ID,
'meta_query' => array(
array(
'key' => '_call_44',
'value' => [ $mf_department ],
),
)
) ); ?>
<?php if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?>
<tr>
<td class="align-middle">
<?php echo $data = get_post_meta(get_the_ID(), '_call_22', true); ?>
</td>
<td class="align-middle">
<?php echo $data = get_post_meta(get_the_ID(), '_call_44', true); ?>
</td>
<td class="align-middle">
<?php echo $data = get_post_meta(get_the_ID(), '_call_45', true); ?>
</td>
<td class="align-middle">
</td>
<td class="align-middle">
</td>
</tr>
<?php endwhile; endif; ?>
</tbody>
</table>
</div>
</div>
</div>
<!-- End User Level Report -->
</div>
</section>
</main>
</code></pre>
| [
{
"answer_id": 352447,
"author": "WP Updoot",
"author_id": 173692,
"author_profile": "https://wordpress.stackexchange.com/users/173692",
"pm_score": 1,
"selected": false,
"text": "<p>What you'd need to do is double-escape, so change <code>echo '\\'' . $term->name . '\\', ';</code> to <code>echo '\\\\\\'' . $term->name . '\\\\\\', ';</code></p>\n\n<p>...but, you'd be much better off just using different encapsulators:</p>\n\n<pre><code><select class=\"w-100\" name=\"mf_term\">\n<option value=\"\n<?php\n$terms = get_terms( 'call-type' );\nif ( ! empty( $terms ) && ! is_wp_error( $terms ) ){\n foreach ( $terms as $term ) {\n echo \"'{$term->name}', \";\n }\n}\n?>\n\">All</option>\n</code></pre>\n\n<p>As you're echo'ing a string that, not directly appending content to the HTML, you can use the double-quotes to encapsulate the output without having to worry about accidentlly exiting your select object early.</p>\n\n<p>In addition, when using double-quotes with a standard PHP variable (<code>$myVariable</code>) or class / object property (<code>$myClass->myProperty</code> / <code>$myObject->myProperty</code>) you can just shove it in, and PHP will assess it correctly (I like to add curly braces for good measure, but it's not absolutely required); meaning you don't have to escape the string at all.</p>\n\n<p>Finally; the code you've submitted will only create a single option in your dropdown, with the value of <code>'All', 'Completed', 'In progress', 'New',</code>. If you're looking to have a list of options in your select box (so you can select <code>All</code>, <code>Completed</code>, <code>In progress</code> <strong>or</strong> <code>New</code>), the following may be more effective:</p>\n\n<pre><code><select class=\"w-100\" name=\"mf_term\">\n\n<?php\n$terms = get_terms( 'call-type' );\nif ( ! empty( $terms ) && ! is_wp_error( $terms ) ){\n foreach ( $terms as $term ) {\n echo \"<option value='{$term->name}'>{$term->name}</option>\";\n }\n}\n?>\n\n</select>\n</code></pre>\n"
},
{
"answer_id": 352448,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a clean way to achieve your need. below code return option value like : </p>\n\n<blockquote>\n <p>'All', 'Completed', 'In progress', 'New'</p>\n</blockquote>\n\n<pre><code>$terms = get_terms( 'call-type' );\nif ( ! empty( $terms ) && ! is_wp_error( $terms ) ){\n $term_option = '';\n $sep = '';\n foreach ( $terms as $term ) {\n $term_option .= $sep.\"'\".$term->name.\"'\";\n $sep = \",\"; \n }\n if(!empty($term_option))\n {\n ?>\n <select class=\"w-100\" name=\"mf_term\">\n <option value=\"<?php echo $term_option ;?>\">All</option>\n </select>\n <?php\n }\n }\n}\n</code></pre>\n"
}
] | 2019/11/13 | [
"https://wordpress.stackexchange.com/questions/352442",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/151521/"
] | If I run this code I get the desired result
```
<?php
$terms = get_terms( 'call-type' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
echo '\'' . $term->name . '\', ';
}
}
?>
```
**result**
'All', 'Completed', 'In progress', 'New',
But if I put the same code into an option all the select box it adds slashes to the results.
```
<select class="w-100" name="mf_term">
<option value="
<?php
$terms = get_terms( 'call-type' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
echo '\'' . $term->name . '\', ';
}
}
?>
">All</option>
```
**result**
\'All\', \'Completed\', \'In progress\', \'New\',
**How can I remove the slashes from the option in the select box**
***Update Code***
```
<main>
<section id="" class="py-3">
<div id="" class="container-fuild">
<!-- Start User Level Report -->
<div id="" class="row mx-0 my-0">
<div class="col-lg-12">
<form action="" method="POST">
<div class="table-responsive ">
<table id="" class="table table-striped table-bordered text-center">
<tbody>
<tr>
<td class="align-middle">
Select Status<br />
<?php
$terms = get_terms( 'call-type' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
$term_option = '';
$sep = '';
foreach ( $terms as $term ) {
$term_option .= $sep."'".$term->name."'";
$sep = ",";
}
if(!empty($term_option))
{
?>
<select class="w-100" name="mf_term">
<option value=""></option>
<option value="<?php echo $term_option ;?>">All</option>
<?php
$mf_term_args = array(
'taxonomy' => 'call-type',
);
// Get Trems as array
$term2s = get_categories( $mf_term_args );
foreach ( $term2s as $term2 ) :
?>
<option value="<?php echo $term2->name ?>"><?php echo $term2->name ?></option>
<?php endforeach; ?>
</select>
<?php
}
}
?>
<?php
$mf_term = $_POST['mf_term'];
$mf_term = str_replace("\\\"", "\"", $mf_term);
$mf_term = str_replace("\\'", "'", $mf_term);
$mf_term = str_replace("\\\\", "\\", $mf_term);
?>
</td>
<td class="align-middle">
Select Department<br />
<!-- Script Starts here -->
<?php
$user_id = get_user_meta($user->ID);
$args = array(
'post_type' => 'department',
'posts_per_page' => -1,
);
$query = new WP_Query($args);
?>
<select class="w-100" name="mf_department">Select Department</p>
<option value=""></option>
<option value="'Marketing', 'Maintenance'">
All
</option>
<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<option value="<?php the_title(); ?>">
<?php the_title(); ?>
</option>
<?php endwhile; endif; ?>
</select>
<?php
$mf_department = $_POST['mf_department'];
$mf_department = str_replace("\\\"", "\"", $mf_department);
$mf_department = str_replace("\\'", "'", $mf_department);
$mf_department = str_replace("\\\\", "\\", $mf_department);
?>
<!-- Script Starts here -->
</td>
<td class="align-middle">
Start Date<br />
<input name="mf_start_date" type="date">
<?php
$mf_start_date = $_POST['mf_start_date'];
?>
</td>
<td class="align-middle">
End Date<br />
<input name="mf_end_date" type="date">
<?php
$mf_end_date = $_POST['mf_end_date'];
?>
</td>
<td class="align-middle">
By Store
</td>
<td class="align-middle">
By Area
</td>
<td class="align-middle">
By Region
</td>
<td class="align-middle">
<button class="btn btn-lg btn-primary btn-block" type="submit">Run Query</button>
</td>
</tr>
<tr class="">
<td colspan="8">
You have Selected Status: <strong class="text-danger"><?php echo $mf_term;?></strong> in the Department: <strong class="text-danger"><?php echo $mf_department;?></strong> from Starting Date: <strong class="text-danger"><?php echo $mf_start_date;?></strong> to Ending Date: <strong class="text-danger"><?php echo $mf_end_date;?></strong>.
</td>
</tr>
</tbody>
</table>
</div>
</form>
</div>
<div id="" class="col-lg-12">
<div class="table-responsive ">
<table id="data-table-1" class="table table-striped table-bordered">
<thead>
<tr>
<th>Call Ref#</th>
<th>Department</th>
<th>Type of Call</th>
<th></th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Call Ref#</th>
<th>Department</th>
<th>Col 3</th>
<th>Col 4</th>
<th>Col 5</th>
</tr>
</tfoot>
<tbody class="text-center">
<?php $query = new WP_Query(array(
'posts_per_page' => -1,
'post-type' => 'call',
'date_query' => array(
array(
'after' => $mf_start_date,
'before' => $mf_end_date,
'inclusive' => true,
),
),
//'terms' => 'All, New',
'tax_query' => array(
array(
'taxonomy' => 'call-type',
'field' => 'name',
'terms' => array( $mf_term ),
),
),
'author' => $current_user->ID,
'meta_query' => array(
array(
'key' => '_call_44',
'value' => [ $mf_department ],
),
)
) ); ?>
<?php if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?>
<tr>
<td class="align-middle">
<?php echo $data = get_post_meta(get_the_ID(), '_call_22', true); ?>
</td>
<td class="align-middle">
<?php echo $data = get_post_meta(get_the_ID(), '_call_44', true); ?>
</td>
<td class="align-middle">
<?php echo $data = get_post_meta(get_the_ID(), '_call_45', true); ?>
</td>
<td class="align-middle">
</td>
<td class="align-middle">
</td>
</tr>
<?php endwhile; endif; ?>
</tbody>
</table>
</div>
</div>
</div>
<!-- End User Level Report -->
</div>
</section>
</main>
``` | What you'd need to do is double-escape, so change `echo '\'' . $term->name . '\', ';` to `echo '\\\'' . $term->name . '\\\', ';`
...but, you'd be much better off just using different encapsulators:
```
<select class="w-100" name="mf_term">
<option value="
<?php
$terms = get_terms( 'call-type' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
echo "'{$term->name}', ";
}
}
?>
">All</option>
```
As you're echo'ing a string that, not directly appending content to the HTML, you can use the double-quotes to encapsulate the output without having to worry about accidentlly exiting your select object early.
In addition, when using double-quotes with a standard PHP variable (`$myVariable`) or class / object property (`$myClass->myProperty` / `$myObject->myProperty`) you can just shove it in, and PHP will assess it correctly (I like to add curly braces for good measure, but it's not absolutely required); meaning you don't have to escape the string at all.
Finally; the code you've submitted will only create a single option in your dropdown, with the value of `'All', 'Completed', 'In progress', 'New',`. If you're looking to have a list of options in your select box (so you can select `All`, `Completed`, `In progress` **or** `New`), the following may be more effective:
```
<select class="w-100" name="mf_term">
<?php
$terms = get_terms( 'call-type' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
echo "<option value='{$term->name}'>{$term->name}</option>";
}
}
?>
</select>
``` |
352,472 | <p>Good day . So today i've updated my wordpress version to 5.3 and after that i started to see this error at the top of all my pages . </p>
<blockquote>
<p>Warning: Declaration of QuietSkin::feedback($string) should be compatible with WP_Upgrader_Skin::feedback($string, ...$args) in /home/.../domains/.../public_html/wp-content/plugins/ocean-extra/includes/wizard/classes/QuietSkin.php on line 12</p>
</blockquote>
<p>Does anyone know what this is ? If you do please provide some assistance :) Thank you</p>
| [
{
"answer_id": 352479,
"author": "Ben",
"author_id": 178276,
"author_profile": "https://wordpress.stackexchange.com/users/178276",
"pm_score": 1,
"selected": false,
"text": "<p>If anyone encounters this warning and cannot hide it with changing the line in wp-config.php from true to false , replace <code>define('WP_DEBUG', false);</code> or <code>define('WP_DEBUG', true);</code>\nwith this : </p>\n\n<pre><code>ini_set('display_errors','Off');\nini_set('error_reporting', E_ALL );\ndefine('WP_DEBUG', false);\ndefine('WP_DEBUG_DISPLAY', false);\n</code></pre>\n\n<p>It helped me, so I hope it will help you also ;)</p>\n"
},
{
"answer_id": 355532,
"author": "muhammad ali",
"author_id": 180458,
"author_profile": "https://wordpress.stackexchange.com/users/180458",
"pm_score": 0,
"selected": false,
"text": "<p>If you’re using oceanwp theme its probable that you are getting this error after the recent update of WordPress. I am using the oceanwp theme and got the same error just after updating my WordPress and i somehow fixed it. Now i want to share the same with you guy’s so that you can fix your website.</p>\n\n<p>So first login to your hosting account. Yes you will need to fix it from your hosting account. Then go to file manager under your hosting account. Once you are inside file manager just follow this path.</p>\n\n<pre><code>public_html/wp-content/plugins/ocean-extra/includes/wizard/classes/QuietSkin.php\n</code></pre>\n\n<p>And then double click on quietskin.php it will download so that you can edit it.</p>\n\n<p>Now open it with notepad++ or any other editor.</p>\n\n<p>Scroll down to bottom and you will see a code like this</p>\n\n<pre><code>public function feedback($string) { /* no output */ }\n</code></pre>\n\n<p>Just change it to this :</p>\n\n<pre><code>public function feedback($string, …$args) { /* no output */ }\n</code></pre>\n\n<p>And save the file.</p>\n\n<p>Now go back to your browser and reload</p>\n"
}
] | 2019/11/13 | [
"https://wordpress.stackexchange.com/questions/352472",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178273/"
] | Good day . So today i've updated my wordpress version to 5.3 and after that i started to see this error at the top of all my pages .
>
> Warning: Declaration of QuietSkin::feedback($string) should be compatible with WP\_Upgrader\_Skin::feedback($string, ...$args) in /home/.../domains/.../public\_html/wp-content/plugins/ocean-extra/includes/wizard/classes/QuietSkin.php on line 12
>
>
>
Does anyone know what this is ? If you do please provide some assistance :) Thank you | If anyone encounters this warning and cannot hide it with changing the line in wp-config.php from true to false , replace `define('WP_DEBUG', false);` or `define('WP_DEBUG', true);`
with this :
```
ini_set('display_errors','Off');
ini_set('error_reporting', E_ALL );
define('WP_DEBUG', false);
define('WP_DEBUG_DISPLAY', false);
```
It helped me, so I hope it will help you also ;) |
352,512 | <p>I am trying to hide the comments form if a user has left a comment on that particular post, otherwise display the comment form. </p>
<p>I added a code snippet to a hook which hides the form, but reverts to the WordPress comment form. I'm unable to figure out how to hide that form! I would also be open to hiding that entire column if need be.</p>
<p>Thanks to @squints for <a href="https://wordpress.stackexchange.com/questions/246668/use-hooks-to-limit-one-comment-per-user-per-post-hide-form-if-already-commente">his post</a></p>
<pre><code>function hide_review_form( $review_form ) {
global $current_user, $post;
$usercomment = get_comments(array('user_id' => $current_user->ID,'post_id' => $post->ID) );
if (! $usercomment) {
return $review_form;
}
}
add_filter( 'woocommerce_product_review_comment_form_args', 'hide_review_form' );
</code></pre>
| [
{
"answer_id": 352479,
"author": "Ben",
"author_id": 178276,
"author_profile": "https://wordpress.stackexchange.com/users/178276",
"pm_score": 1,
"selected": false,
"text": "<p>If anyone encounters this warning and cannot hide it with changing the line in wp-config.php from true to false , replace <code>define('WP_DEBUG', false);</code> or <code>define('WP_DEBUG', true);</code>\nwith this : </p>\n\n<pre><code>ini_set('display_errors','Off');\nini_set('error_reporting', E_ALL );\ndefine('WP_DEBUG', false);\ndefine('WP_DEBUG_DISPLAY', false);\n</code></pre>\n\n<p>It helped me, so I hope it will help you also ;)</p>\n"
},
{
"answer_id": 355532,
"author": "muhammad ali",
"author_id": 180458,
"author_profile": "https://wordpress.stackexchange.com/users/180458",
"pm_score": 0,
"selected": false,
"text": "<p>If you’re using oceanwp theme its probable that you are getting this error after the recent update of WordPress. I am using the oceanwp theme and got the same error just after updating my WordPress and i somehow fixed it. Now i want to share the same with you guy’s so that you can fix your website.</p>\n\n<p>So first login to your hosting account. Yes you will need to fix it from your hosting account. Then go to file manager under your hosting account. Once you are inside file manager just follow this path.</p>\n\n<pre><code>public_html/wp-content/plugins/ocean-extra/includes/wizard/classes/QuietSkin.php\n</code></pre>\n\n<p>And then double click on quietskin.php it will download so that you can edit it.</p>\n\n<p>Now open it with notepad++ or any other editor.</p>\n\n<p>Scroll down to bottom and you will see a code like this</p>\n\n<pre><code>public function feedback($string) { /* no output */ }\n</code></pre>\n\n<p>Just change it to this :</p>\n\n<pre><code>public function feedback($string, …$args) { /* no output */ }\n</code></pre>\n\n<p>And save the file.</p>\n\n<p>Now go back to your browser and reload</p>\n"
}
] | 2019/11/13 | [
"https://wordpress.stackexchange.com/questions/352512",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178299/"
] | I am trying to hide the comments form if a user has left a comment on that particular post, otherwise display the comment form.
I added a code snippet to a hook which hides the form, but reverts to the WordPress comment form. I'm unable to figure out how to hide that form! I would also be open to hiding that entire column if need be.
Thanks to @squints for [his post](https://wordpress.stackexchange.com/questions/246668/use-hooks-to-limit-one-comment-per-user-per-post-hide-form-if-already-commente)
```
function hide_review_form( $review_form ) {
global $current_user, $post;
$usercomment = get_comments(array('user_id' => $current_user->ID,'post_id' => $post->ID) );
if (! $usercomment) {
return $review_form;
}
}
add_filter( 'woocommerce_product_review_comment_form_args', 'hide_review_form' );
``` | If anyone encounters this warning and cannot hide it with changing the line in wp-config.php from true to false , replace `define('WP_DEBUG', false);` or `define('WP_DEBUG', true);`
with this :
```
ini_set('display_errors','Off');
ini_set('error_reporting', E_ALL );
define('WP_DEBUG', false);
define('WP_DEBUG_DISPLAY', false);
```
It helped me, so I hope it will help you also ;) |
352,526 | <p>Is there a built-in Wordpress function that will allow you to enqueue all stylesheets for a particular theme?</p>
<p>I have a directory structure that looks like:</p>
<pre><code>-my-custom-theme
-css
-header.css
-footer.css
-functions.php
</code></pre>
<p>I want to load all CSS files found in the <code>my-custom-theme/css</code> folder</p>
| [
{
"answer_id": 352479,
"author": "Ben",
"author_id": 178276,
"author_profile": "https://wordpress.stackexchange.com/users/178276",
"pm_score": 1,
"selected": false,
"text": "<p>If anyone encounters this warning and cannot hide it with changing the line in wp-config.php from true to false , replace <code>define('WP_DEBUG', false);</code> or <code>define('WP_DEBUG', true);</code>\nwith this : </p>\n\n<pre><code>ini_set('display_errors','Off');\nini_set('error_reporting', E_ALL );\ndefine('WP_DEBUG', false);\ndefine('WP_DEBUG_DISPLAY', false);\n</code></pre>\n\n<p>It helped me, so I hope it will help you also ;)</p>\n"
},
{
"answer_id": 355532,
"author": "muhammad ali",
"author_id": 180458,
"author_profile": "https://wordpress.stackexchange.com/users/180458",
"pm_score": 0,
"selected": false,
"text": "<p>If you’re using oceanwp theme its probable that you are getting this error after the recent update of WordPress. I am using the oceanwp theme and got the same error just after updating my WordPress and i somehow fixed it. Now i want to share the same with you guy’s so that you can fix your website.</p>\n\n<p>So first login to your hosting account. Yes you will need to fix it from your hosting account. Then go to file manager under your hosting account. Once you are inside file manager just follow this path.</p>\n\n<pre><code>public_html/wp-content/plugins/ocean-extra/includes/wizard/classes/QuietSkin.php\n</code></pre>\n\n<p>And then double click on quietskin.php it will download so that you can edit it.</p>\n\n<p>Now open it with notepad++ or any other editor.</p>\n\n<p>Scroll down to bottom and you will see a code like this</p>\n\n<pre><code>public function feedback($string) { /* no output */ }\n</code></pre>\n\n<p>Just change it to this :</p>\n\n<pre><code>public function feedback($string, …$args) { /* no output */ }\n</code></pre>\n\n<p>And save the file.</p>\n\n<p>Now go back to your browser and reload</p>\n"
}
] | 2019/11/14 | [
"https://wordpress.stackexchange.com/questions/352526",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/167796/"
] | Is there a built-in Wordpress function that will allow you to enqueue all stylesheets for a particular theme?
I have a directory structure that looks like:
```
-my-custom-theme
-css
-header.css
-footer.css
-functions.php
```
I want to load all CSS files found in the `my-custom-theme/css` folder | If anyone encounters this warning and cannot hide it with changing the line in wp-config.php from true to false , replace `define('WP_DEBUG', false);` or `define('WP_DEBUG', true);`
with this :
```
ini_set('display_errors','Off');
ini_set('error_reporting', E_ALL );
define('WP_DEBUG', false);
define('WP_DEBUG_DISPLAY', false);
```
It helped me, so I hope it will help you also ;) |
352,543 | <p>I'm pretty new to PHP however have managed to put together a site I'm happy with.
Once small issue I am having is that I would like to add content for users with specific roles, this means adding an if statement in the middle of a pre existing one for me.</p>
<p>Below is my current code:</p>
<pre><code><?php global $current_user; wp_get_current_user(); ?>
<?php if ( is_user_logged_in() ) {
echo '<ul style="padding: 0; margin: 0;">
<li class="adminBar" style="float: left; line-height: 60px; border-left: 1px solid #555555; border-right: 1px solid #555555;"><a href="#" target="_blank"><img src="#" height="40px" style="padding-left: 15px; padding-right: 15px;"></a></li>
<li class="adminBar" style="float: left; line-height: 60px; border-right: 1px solid #555555;"><a href="#" target="_blank"><img src="#" height="40px" style="padding-left: 15px; padding-right: 15px;"></a></li>
<li class="adminBar" style="float: left; line-height: 60px; border-right: 1px solid #555555;"><a href="#" target="_blank"><img src="#" height="40px" style="padding-left: 15px; padding-right: 15px;"></a></li>
<li class="adminBar" style="float: left; line-height: 60px; border-right: 1px solid #555555;"><a href="#" target="_blank"><img src="#" height="40px" style="padding-left: 15px; padding-right: 15px;"></a></li>
<li class="adminBar" style="float: left; line-height: 60px; border-right: 1px solid #555555;"><a href="#" target="_blank"><img src="#" height="40px" style="padding-left: 15px; padding-right: 15px;"></a></li>
<li id="logoutDrop" class="loginBtn" style="background-color: #27618d; float: right;"><a style="text-decoration: none; text-transform: none; line-height: 60px; color: #fff; padding: 15px 20px 15px 20px;" href=""' . wp_logout_url() . '">Logout</a>' . '
<li id="logoutDrop" style="border-right: 1px solid #555; padding: 0 15px 0 15px; float: right;"><a style="text-transform: none; text-decoration: none; line-height: 60px; color: #fff;">Hi, ' . $current_user->user_login . '</a>' . '
<ul style="display: none;">
<li><a href="#" style="">Logout</a></li>
</ul>
</li>' .
'</ul>' . "\n";}
else { echo '
<div id="stmposTitle">
<a href="/" style="text-decoration: none; float: left; text-transform: none; line-height: 35px; color: #fff;">
<img src="#" style="margin-top: 2px; float:left; padding-right: 10px;">Name</a></div>
<a class="loginBtn" style="float: right; line-height: 35px; color: #fff; background-color: #27618d; padding: 0 15px; 0 15px; text-decoration: none;" href="' . wp_login_url() . '">Login</a>' ;} ?>
</code></pre>
<p>I essentially want to allow it so that there is a part of this menu that logged in users with only specific roles can see. Something like the below although it is not quite right as it stops the site from loading:</p>
<pre><code><?php global $current_user; wp_get_current_user(); ?>
<?php if ( is_user_logged_in() ) {
echo '<ul style="padding: 0; margin: 0;">
<li class="adminBar" style="float: left; line-height: 60px; border-left: 1px solid #555555; border-right: 1px solid #555555;"><a href="#" target="_blank"><img src="#" height="40px" style="padding-left: 15px; padding-right: 15px;"></a></li>
<li class="adminBar" style="float: left; line-height: 60px; border-right: 1px solid #555555;"><a href="#" target="_blank"><img src="#" height="40px" style="padding-left: 15px; padding-right: 15px;"></a></li>
<li class="adminBar" style="float: left; line-height: 60px; border-right: 1px solid #555555;"><a href="#" target="_blank"><img src="#" height="40px" style="padding-left: 15px; padding-right: 15px;"></a></li>
<li class="adminBar" style="float: left; line-height: 60px; border-right: 1px solid #555555;"><a href="#" target="_blank"><img src="#" height="40px" style="padding-left: 15px; padding-right: 15px;"></a></li>
<li class="adminBar" style="float: left; line-height: 60px; border-right: 1px solid #555555;"><a href="#" target="_blank"><img src="#" height="40px" style="padding-left: 15px; padding-right: 15px;"></a></li>'
<?php if( current_user_can('editor') || current_user_can('administrator') ) { ?>
content
<?php } ?>
'
<li id="logoutDrop" class="loginBtn" style="background-color: #27618d; float: right;"><a style="text-decoration: none; text-transform: none; line-height: 60px; color: #fff; padding: 15px 20px 15px 20px;" href=""' . wp_logout_url() . '">Logout</a>' . '
<li id="logoutDrop" style="border-right: 1px solid #555; padding: 0 15px 0 15px; float: right;"><a style="text-transform: none; text-decoration: none; line-height: 60px; color: #fff;">Hi, ' . $current_user->user_login . '</a>' . '
<ul style="display: none;">
<li><a href="#" style="">Logout</a></li>
</ul>
</li>' .
'</ul>' . "\n";}
else { echo '
<div id="stmposTitle">
<a href="/" style="text-decoration: none; float: left; text-transform: none; line-height: 35px; color: #fff;">
<img src="#" style="margin-top: 2px; float:left; padding-right: 10px;">Name</a></div>
<a class="loginBtn" style="float: right; line-height: 35px; color: #fff; background-color: #27618d; padding: 0 15px; 0 15px; text-decoration: none;" href="' . wp_login_url() . '">Login</a>' ;} ?>
</code></pre>
<p>Thanks in advance for your help!</p>
| [
{
"answer_id": 352542,
"author": "Siddhesh Shirodkar",
"author_id": 163787,
"author_profile": "https://wordpress.stackexchange.com/users/163787",
"pm_score": 2,
"selected": false,
"text": "<p>It is always best to avoid the use of plugins as it is simply an overhead on server resources. I strongly recommend that you use header.php or functions.php for adding the code.</p>\n\n<p>It also depends on what are the things you are looking for when it comes to meta descriptions. There are many tools that are available in YOAST SEO which can reduce your efforts but if you are familiar with WP and webmaster tools than sure go ahead with custom code.</p>\n"
},
{
"answer_id": 352546,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 2,
"selected": true,
"text": "<blockquote>\n <p>It is always best to avoid the use of plugins as it is simply an overhead on server resources. I strongly recommend that you use header.php or functions.php for adding the code.</p>\n</blockquote>\n\n<p>This is not true.</p>\n\n<p>In the end, it all comes down to PHP code. If the code lives in a plugin, a theme, functions.php or you manually edit a core file doesn't really matter for performance.</p>\n\n<p>A problem can arise, when you install plugin X and that plugin brings with it a lot of functionality that you do not need. This can really slow down your site because there exists lots of code that is not needed.</p>\n\n<p>But when you use (almost) all the functionality a plugin provides, why should your custom implementation be any faster? Additionally, I think you're missing one very important part for this specific case: With proper (page) caching, for a visitor, the page is just as fast in any case.</p>\n\n<p>One very important aspect you're missing, as you're only asking for performance, is <strong>maintainability</strong>.</p>\n\n<p>Yoast has a team of developers, constantly working on their plugin. They can do much more than a single developer can, just because of numbers. Now say, Google changes something in their ruleset, for example the description must not be longer than X.</p>\n\n<p>How long does it take a single developer to know this change happened and take the time to implement the changes?</p>\n\n<p>When using Yoast, you don't have to worry about that, someone else does. And you just need to click one button.</p>\n"
}
] | 2019/11/14 | [
"https://wordpress.stackexchange.com/questions/352543",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178319/"
] | I'm pretty new to PHP however have managed to put together a site I'm happy with.
Once small issue I am having is that I would like to add content for users with specific roles, this means adding an if statement in the middle of a pre existing one for me.
Below is my current code:
```
<?php global $current_user; wp_get_current_user(); ?>
<?php if ( is_user_logged_in() ) {
echo '<ul style="padding: 0; margin: 0;">
<li class="adminBar" style="float: left; line-height: 60px; border-left: 1px solid #555555; border-right: 1px solid #555555;"><a href="#" target="_blank"><img src="#" height="40px" style="padding-left: 15px; padding-right: 15px;"></a></li>
<li class="adminBar" style="float: left; line-height: 60px; border-right: 1px solid #555555;"><a href="#" target="_blank"><img src="#" height="40px" style="padding-left: 15px; padding-right: 15px;"></a></li>
<li class="adminBar" style="float: left; line-height: 60px; border-right: 1px solid #555555;"><a href="#" target="_blank"><img src="#" height="40px" style="padding-left: 15px; padding-right: 15px;"></a></li>
<li class="adminBar" style="float: left; line-height: 60px; border-right: 1px solid #555555;"><a href="#" target="_blank"><img src="#" height="40px" style="padding-left: 15px; padding-right: 15px;"></a></li>
<li class="adminBar" style="float: left; line-height: 60px; border-right: 1px solid #555555;"><a href="#" target="_blank"><img src="#" height="40px" style="padding-left: 15px; padding-right: 15px;"></a></li>
<li id="logoutDrop" class="loginBtn" style="background-color: #27618d; float: right;"><a style="text-decoration: none; text-transform: none; line-height: 60px; color: #fff; padding: 15px 20px 15px 20px;" href=""' . wp_logout_url() . '">Logout</a>' . '
<li id="logoutDrop" style="border-right: 1px solid #555; padding: 0 15px 0 15px; float: right;"><a style="text-transform: none; text-decoration: none; line-height: 60px; color: #fff;">Hi, ' . $current_user->user_login . '</a>' . '
<ul style="display: none;">
<li><a href="#" style="">Logout</a></li>
</ul>
</li>' .
'</ul>' . "\n";}
else { echo '
<div id="stmposTitle">
<a href="/" style="text-decoration: none; float: left; text-transform: none; line-height: 35px; color: #fff;">
<img src="#" style="margin-top: 2px; float:left; padding-right: 10px;">Name</a></div>
<a class="loginBtn" style="float: right; line-height: 35px; color: #fff; background-color: #27618d; padding: 0 15px; 0 15px; text-decoration: none;" href="' . wp_login_url() . '">Login</a>' ;} ?>
```
I essentially want to allow it so that there is a part of this menu that logged in users with only specific roles can see. Something like the below although it is not quite right as it stops the site from loading:
```
<?php global $current_user; wp_get_current_user(); ?>
<?php if ( is_user_logged_in() ) {
echo '<ul style="padding: 0; margin: 0;">
<li class="adminBar" style="float: left; line-height: 60px; border-left: 1px solid #555555; border-right: 1px solid #555555;"><a href="#" target="_blank"><img src="#" height="40px" style="padding-left: 15px; padding-right: 15px;"></a></li>
<li class="adminBar" style="float: left; line-height: 60px; border-right: 1px solid #555555;"><a href="#" target="_blank"><img src="#" height="40px" style="padding-left: 15px; padding-right: 15px;"></a></li>
<li class="adminBar" style="float: left; line-height: 60px; border-right: 1px solid #555555;"><a href="#" target="_blank"><img src="#" height="40px" style="padding-left: 15px; padding-right: 15px;"></a></li>
<li class="adminBar" style="float: left; line-height: 60px; border-right: 1px solid #555555;"><a href="#" target="_blank"><img src="#" height="40px" style="padding-left: 15px; padding-right: 15px;"></a></li>
<li class="adminBar" style="float: left; line-height: 60px; border-right: 1px solid #555555;"><a href="#" target="_blank"><img src="#" height="40px" style="padding-left: 15px; padding-right: 15px;"></a></li>'
<?php if( current_user_can('editor') || current_user_can('administrator') ) { ?>
content
<?php } ?>
'
<li id="logoutDrop" class="loginBtn" style="background-color: #27618d; float: right;"><a style="text-decoration: none; text-transform: none; line-height: 60px; color: #fff; padding: 15px 20px 15px 20px;" href=""' . wp_logout_url() . '">Logout</a>' . '
<li id="logoutDrop" style="border-right: 1px solid #555; padding: 0 15px 0 15px; float: right;"><a style="text-transform: none; text-decoration: none; line-height: 60px; color: #fff;">Hi, ' . $current_user->user_login . '</a>' . '
<ul style="display: none;">
<li><a href="#" style="">Logout</a></li>
</ul>
</li>' .
'</ul>' . "\n";}
else { echo '
<div id="stmposTitle">
<a href="/" style="text-decoration: none; float: left; text-transform: none; line-height: 35px; color: #fff;">
<img src="#" style="margin-top: 2px; float:left; padding-right: 10px;">Name</a></div>
<a class="loginBtn" style="float: right; line-height: 35px; color: #fff; background-color: #27618d; padding: 0 15px; 0 15px; text-decoration: none;" href="' . wp_login_url() . '">Login</a>' ;} ?>
```
Thanks in advance for your help! | >
> It is always best to avoid the use of plugins as it is simply an overhead on server resources. I strongly recommend that you use header.php or functions.php for adding the code.
>
>
>
This is not true.
In the end, it all comes down to PHP code. If the code lives in a plugin, a theme, functions.php or you manually edit a core file doesn't really matter for performance.
A problem can arise, when you install plugin X and that plugin brings with it a lot of functionality that you do not need. This can really slow down your site because there exists lots of code that is not needed.
But when you use (almost) all the functionality a plugin provides, why should your custom implementation be any faster? Additionally, I think you're missing one very important part for this specific case: With proper (page) caching, for a visitor, the page is just as fast in any case.
One very important aspect you're missing, as you're only asking for performance, is **maintainability**.
Yoast has a team of developers, constantly working on their plugin. They can do much more than a single developer can, just because of numbers. Now say, Google changes something in their ruleset, for example the description must not be longer than X.
How long does it take a single developer to know this change happened and take the time to implement the changes?
When using Yoast, you don't have to worry about that, someone else does. And you just need to click one button. |
352,559 | <p>The Block Editor recently introduced block styles as seen below:</p>
<p><a href="https://i.stack.imgur.com/Nglqs.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Nglqs.png" alt="Block Styles"></a></p>
<p>How do we disable these?</p>
| [
{
"answer_id": 352560,
"author": "Christine Cooper",
"author_id": 24875,
"author_profile": "https://wordpress.stackexchange.com/users/24875",
"pm_score": 5,
"selected": true,
"text": "<p>We start off by finding out which block styles exists via <code>.getBlockTypes()</code>. This will dump it into the console:</p>\n<pre><code>wp.domReady(() => {\n // find blocks styles\n wp.blocks.getBlockTypes().forEach((block) => {\n if (_.isArray(block['styles'])) {\n console.log(block.name, _.pluck(block['styles'], 'name'));\n }\n });\n});\n</code></pre>\n<p>Example output:</p>\n<pre><code>core/image (2) ["default", "rounded"]\ncore/quote (2) ["default", "large"]\ncore/button (2) ["fill", "outline"]\ncore/pullquote (2) ["default", "solid-color"]\ncore/separator (3) ["default", "wide", "dots"]\ncore/table (2) ["regular", "stripes"]\ncore/social-links (3) ["default", "logos-only", "pill-shape"]\n</code></pre>\n<p>With this information, we can deactivate the block styles as desired. For example, if we want to remove the <code>large</code> quote style, we can use the following in our <code>remove-block-styles.js</code>:</p>\n<pre><code>wp.domReady(() => {\n wp.blocks.unregisterBlockStyle('core/quote', 'large');\n} );\n</code></pre>\n<p>We can load the <code>remove-block-styles.js</code> in the themes <code>functions.php</code>:</p>\n<pre><code>function remove_block_style() {\n // Register the block editor script.\n wp_register_script( 'remove-block-style', get_stylesheet_directory_uri() . '/remove-block-styles.js', [ 'wp-blocks', 'wp-edit-post' ] );\n // register block editor script.\n register_block_type( 'remove/block-style', [\n 'editor_script' => 'remove-block-style',\n ] );\n}\nadd_action( 'init', 'remove_block_style' );\n</code></pre>\n<p>If we want to remove all block styles (as listed above), we can use:</p>\n<pre><code>wp.domReady(() => {\n // image\n wp.blocks.unregisterBlockStyle('core/image', 'rounded');\n wp.blocks.unregisterBlockStyle('core/image', 'default');\n // quote\n wp.blocks.unregisterBlockStyle('core/quote', 'default');\n wp.blocks.unregisterBlockStyle('core/quote', 'large');\n // button\n wp.blocks.unregisterBlockStyle('core/button', 'fill');\n wp.blocks.unregisterBlockStyle('core/button', 'outline');\n // pullquote\n wp.blocks.unregisterBlockStyle('core/pullquote', 'default');\n wp.blocks.unregisterBlockStyle('core/pullquote', 'solid-color');\n // separator\n wp.blocks.unregisterBlockStyle('core/separator', 'default');\n wp.blocks.unregisterBlockStyle('core/separator', 'wide');\n wp.blocks.unregisterBlockStyle('core/separator', 'dots');\n // table\n wp.blocks.unregisterBlockStyle('core/table', 'regular');\n wp.blocks.unregisterBlockStyle('core/table', 'stripes');\n // social-links\n wp.blocks.unregisterBlockStyle('core/social-links', 'default');\n wp.blocks.unregisterBlockStyle('core/social-links', 'logos-only');\n wp.blocks.unregisterBlockStyle('core/social-links', 'pill-shape');\n} );\n</code></pre>\n<p>Major credits to <a href=\"https://soderlind.no/hide-block-styles-in-gutenberg/\" rel=\"noreferrer\">Per Søderlind</a> for the snippets.</p>\n"
},
{
"answer_id": 377655,
"author": "benpalmer",
"author_id": 6123,
"author_profile": "https://wordpress.stackexchange.com/users/6123",
"pm_score": 2,
"selected": false,
"text": "<p>This has now changed to</p>\n<pre><code>wp.blocks.unregisterBlockStyle('core/image', 'rounded');\n</code></pre>\n<p>Gotta love those guys in core ;)</p>\n"
},
{
"answer_id": 378134,
"author": "kraftner",
"author_id": 47733,
"author_profile": "https://wordpress.stackexchange.com/users/47733",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://wordpress.stackexchange.com/a/352560/47733\">The answer from Christine</a> already gets you quite far but I saw two ways to still improve it:</p>\n<ol>\n<li>The snippet that helps you get the list of block styles only lists the default styles of blocks, not the currently registered ones. So if some other plugin/code has added further styles they will be missed.</li>\n<li>It makes you manually unregister the styles after you got the list.</li>\n</ol>\n<p>Let's fix this. :)</p>\n<h2>1. Getting the real, current list of block styles:</h2>\n<pre><code>_.forEach(wp.blocks.getBlockTypes(), function(blockType){\n let blockStyles = wp.data.select('core/blocks').getBlockStyles(blockType.name);\n if(!_.isEmpty(blockStyles)){\n console.log(blockType.name, _.pluck(blockStyles, 'name'));\n }\n});\n</code></pre>\n<h2>2. Remove them all</h2>\n<pre><code>_.forEach(wp.blocks.getBlockTypes(), function(blockType){\n let blockStyles = wp.data.select('core/blocks').getBlockStyles(blockType.name);\n if(!_.isEmpty(blockStyles)){\n _.forEach(_.pluck(blockStyles, 'name'), function(blockStyle){\n wp.blocks.unregisterBlockStyle(blockType.name, blockStyle);\n }); \n }\n});\n\n</code></pre>\n<hr />\n<p>Of course you can get more creative from here with an allow/disallow list or whatever other logic you need, but I'll leave this as an exercise to the reader. :)</p>\n"
}
] | 2019/11/14 | [
"https://wordpress.stackexchange.com/questions/352559",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24875/"
] | The Block Editor recently introduced block styles as seen below:
[](https://i.stack.imgur.com/Nglqs.png)
How do we disable these? | We start off by finding out which block styles exists via `.getBlockTypes()`. This will dump it into the console:
```
wp.domReady(() => {
// find blocks styles
wp.blocks.getBlockTypes().forEach((block) => {
if (_.isArray(block['styles'])) {
console.log(block.name, _.pluck(block['styles'], 'name'));
}
});
});
```
Example output:
```
core/image (2) ["default", "rounded"]
core/quote (2) ["default", "large"]
core/button (2) ["fill", "outline"]
core/pullquote (2) ["default", "solid-color"]
core/separator (3) ["default", "wide", "dots"]
core/table (2) ["regular", "stripes"]
core/social-links (3) ["default", "logos-only", "pill-shape"]
```
With this information, we can deactivate the block styles as desired. For example, if we want to remove the `large` quote style, we can use the following in our `remove-block-styles.js`:
```
wp.domReady(() => {
wp.blocks.unregisterBlockStyle('core/quote', 'large');
} );
```
We can load the `remove-block-styles.js` in the themes `functions.php`:
```
function remove_block_style() {
// Register the block editor script.
wp_register_script( 'remove-block-style', get_stylesheet_directory_uri() . '/remove-block-styles.js', [ 'wp-blocks', 'wp-edit-post' ] );
// register block editor script.
register_block_type( 'remove/block-style', [
'editor_script' => 'remove-block-style',
] );
}
add_action( 'init', 'remove_block_style' );
```
If we want to remove all block styles (as listed above), we can use:
```
wp.domReady(() => {
// image
wp.blocks.unregisterBlockStyle('core/image', 'rounded');
wp.blocks.unregisterBlockStyle('core/image', 'default');
// quote
wp.blocks.unregisterBlockStyle('core/quote', 'default');
wp.blocks.unregisterBlockStyle('core/quote', 'large');
// button
wp.blocks.unregisterBlockStyle('core/button', 'fill');
wp.blocks.unregisterBlockStyle('core/button', 'outline');
// pullquote
wp.blocks.unregisterBlockStyle('core/pullquote', 'default');
wp.blocks.unregisterBlockStyle('core/pullquote', 'solid-color');
// separator
wp.blocks.unregisterBlockStyle('core/separator', 'default');
wp.blocks.unregisterBlockStyle('core/separator', 'wide');
wp.blocks.unregisterBlockStyle('core/separator', 'dots');
// table
wp.blocks.unregisterBlockStyle('core/table', 'regular');
wp.blocks.unregisterBlockStyle('core/table', 'stripes');
// social-links
wp.blocks.unregisterBlockStyle('core/social-links', 'default');
wp.blocks.unregisterBlockStyle('core/social-links', 'logos-only');
wp.blocks.unregisterBlockStyle('core/social-links', 'pill-shape');
} );
```
Major credits to [Per Søderlind](https://soderlind.no/hide-block-styles-in-gutenberg/) for the snippets. |
352,584 | <p>A plugin created lots of posts that I now need to delete.
They are targetable by category (e.g. <code>Tweet</code>). Many also have attached images.</p>
<p>I wrote a php script for it*, but without pagination it gets hung up, as it does a lot of work (deletes the posts one by one). - And with pagination (say 1000 per page) it still takes multiple seconds and I'd have to refresh >50 times...</p>
<p>I figure a good database query could select and delete multiple posts at the same time - however I also want to delete all attached media, both in the database and the actual files.</p>
<p>Alternatively, handling the deletions in batches (i.e. using pagination) and maybe flush output in between to show update on whether it's working could work.</p>
<hr>
<p>*here's what I have so far:</p>
<pre class="lang-php prettyprint-override"><code>$twitter = get_cat_ID( 'Tweet' );
$instagram = get_cat_ID( 'Instagram' );
$args = array(
'category__in' => array(
$twitter,
$instagram
),
'post_status' => 'any',
'posts_per_page' => 1000
);
$social_posts = new WP_Query( $args );
if ( $social_posts->have_posts() ) : ?>
<h1>Deleting the following:</h1>
<ul>
<?php while ( $social_posts->have_posts() ) :
$social_posts->the_post();
?>
<li>
<h5><?php the_title() ?></h5>
<div class='post-content'><?php the_content(); ?></div>
</li>
<?php
$post_id = get_the_ID();
$attachments = get_attached_media( '', $post_id ); // '' => all attachment Mime types
foreach ( $attachments as $attachment ) {
wp_delete_attachment( $attachment->ID, true );
}
wp_delete_post( $post_id, true );
endwhile;
else: ?>
<p>Oops, there are no posts.</p>
<?php
endif;
</code></pre>
<p>(Testing this locally, put it in <code>page-uninstall-social.php</code> and created a page for it so it runs when I visit that page)</p>
| [
{
"answer_id": 352560,
"author": "Christine Cooper",
"author_id": 24875,
"author_profile": "https://wordpress.stackexchange.com/users/24875",
"pm_score": 5,
"selected": true,
"text": "<p>We start off by finding out which block styles exists via <code>.getBlockTypes()</code>. This will dump it into the console:</p>\n<pre><code>wp.domReady(() => {\n // find blocks styles\n wp.blocks.getBlockTypes().forEach((block) => {\n if (_.isArray(block['styles'])) {\n console.log(block.name, _.pluck(block['styles'], 'name'));\n }\n });\n});\n</code></pre>\n<p>Example output:</p>\n<pre><code>core/image (2) ["default", "rounded"]\ncore/quote (2) ["default", "large"]\ncore/button (2) ["fill", "outline"]\ncore/pullquote (2) ["default", "solid-color"]\ncore/separator (3) ["default", "wide", "dots"]\ncore/table (2) ["regular", "stripes"]\ncore/social-links (3) ["default", "logos-only", "pill-shape"]\n</code></pre>\n<p>With this information, we can deactivate the block styles as desired. For example, if we want to remove the <code>large</code> quote style, we can use the following in our <code>remove-block-styles.js</code>:</p>\n<pre><code>wp.domReady(() => {\n wp.blocks.unregisterBlockStyle('core/quote', 'large');\n} );\n</code></pre>\n<p>We can load the <code>remove-block-styles.js</code> in the themes <code>functions.php</code>:</p>\n<pre><code>function remove_block_style() {\n // Register the block editor script.\n wp_register_script( 'remove-block-style', get_stylesheet_directory_uri() . '/remove-block-styles.js', [ 'wp-blocks', 'wp-edit-post' ] );\n // register block editor script.\n register_block_type( 'remove/block-style', [\n 'editor_script' => 'remove-block-style',\n ] );\n}\nadd_action( 'init', 'remove_block_style' );\n</code></pre>\n<p>If we want to remove all block styles (as listed above), we can use:</p>\n<pre><code>wp.domReady(() => {\n // image\n wp.blocks.unregisterBlockStyle('core/image', 'rounded');\n wp.blocks.unregisterBlockStyle('core/image', 'default');\n // quote\n wp.blocks.unregisterBlockStyle('core/quote', 'default');\n wp.blocks.unregisterBlockStyle('core/quote', 'large');\n // button\n wp.blocks.unregisterBlockStyle('core/button', 'fill');\n wp.blocks.unregisterBlockStyle('core/button', 'outline');\n // pullquote\n wp.blocks.unregisterBlockStyle('core/pullquote', 'default');\n wp.blocks.unregisterBlockStyle('core/pullquote', 'solid-color');\n // separator\n wp.blocks.unregisterBlockStyle('core/separator', 'default');\n wp.blocks.unregisterBlockStyle('core/separator', 'wide');\n wp.blocks.unregisterBlockStyle('core/separator', 'dots');\n // table\n wp.blocks.unregisterBlockStyle('core/table', 'regular');\n wp.blocks.unregisterBlockStyle('core/table', 'stripes');\n // social-links\n wp.blocks.unregisterBlockStyle('core/social-links', 'default');\n wp.blocks.unregisterBlockStyle('core/social-links', 'logos-only');\n wp.blocks.unregisterBlockStyle('core/social-links', 'pill-shape');\n} );\n</code></pre>\n<p>Major credits to <a href=\"https://soderlind.no/hide-block-styles-in-gutenberg/\" rel=\"noreferrer\">Per Søderlind</a> for the snippets.</p>\n"
},
{
"answer_id": 377655,
"author": "benpalmer",
"author_id": 6123,
"author_profile": "https://wordpress.stackexchange.com/users/6123",
"pm_score": 2,
"selected": false,
"text": "<p>This has now changed to</p>\n<pre><code>wp.blocks.unregisterBlockStyle('core/image', 'rounded');\n</code></pre>\n<p>Gotta love those guys in core ;)</p>\n"
},
{
"answer_id": 378134,
"author": "kraftner",
"author_id": 47733,
"author_profile": "https://wordpress.stackexchange.com/users/47733",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://wordpress.stackexchange.com/a/352560/47733\">The answer from Christine</a> already gets you quite far but I saw two ways to still improve it:</p>\n<ol>\n<li>The snippet that helps you get the list of block styles only lists the default styles of blocks, not the currently registered ones. So if some other plugin/code has added further styles they will be missed.</li>\n<li>It makes you manually unregister the styles after you got the list.</li>\n</ol>\n<p>Let's fix this. :)</p>\n<h2>1. Getting the real, current list of block styles:</h2>\n<pre><code>_.forEach(wp.blocks.getBlockTypes(), function(blockType){\n let blockStyles = wp.data.select('core/blocks').getBlockStyles(blockType.name);\n if(!_.isEmpty(blockStyles)){\n console.log(blockType.name, _.pluck(blockStyles, 'name'));\n }\n});\n</code></pre>\n<h2>2. Remove them all</h2>\n<pre><code>_.forEach(wp.blocks.getBlockTypes(), function(blockType){\n let blockStyles = wp.data.select('core/blocks').getBlockStyles(blockType.name);\n if(!_.isEmpty(blockStyles)){\n _.forEach(_.pluck(blockStyles, 'name'), function(blockStyle){\n wp.blocks.unregisterBlockStyle(blockType.name, blockStyle);\n }); \n }\n});\n\n</code></pre>\n<hr />\n<p>Of course you can get more creative from here with an allow/disallow list or whatever other logic you need, but I'll leave this as an exercise to the reader. :)</p>\n"
}
] | 2019/11/14 | [
"https://wordpress.stackexchange.com/questions/352584",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/117836/"
] | A plugin created lots of posts that I now need to delete.
They are targetable by category (e.g. `Tweet`). Many also have attached images.
I wrote a php script for it\*, but without pagination it gets hung up, as it does a lot of work (deletes the posts one by one). - And with pagination (say 1000 per page) it still takes multiple seconds and I'd have to refresh >50 times...
I figure a good database query could select and delete multiple posts at the same time - however I also want to delete all attached media, both in the database and the actual files.
Alternatively, handling the deletions in batches (i.e. using pagination) and maybe flush output in between to show update on whether it's working could work.
---
\*here's what I have so far:
```php
$twitter = get_cat_ID( 'Tweet' );
$instagram = get_cat_ID( 'Instagram' );
$args = array(
'category__in' => array(
$twitter,
$instagram
),
'post_status' => 'any',
'posts_per_page' => 1000
);
$social_posts = new WP_Query( $args );
if ( $social_posts->have_posts() ) : ?>
<h1>Deleting the following:</h1>
<ul>
<?php while ( $social_posts->have_posts() ) :
$social_posts->the_post();
?>
<li>
<h5><?php the_title() ?></h5>
<div class='post-content'><?php the_content(); ?></div>
</li>
<?php
$post_id = get_the_ID();
$attachments = get_attached_media( '', $post_id ); // '' => all attachment Mime types
foreach ( $attachments as $attachment ) {
wp_delete_attachment( $attachment->ID, true );
}
wp_delete_post( $post_id, true );
endwhile;
else: ?>
<p>Oops, there are no posts.</p>
<?php
endif;
```
(Testing this locally, put it in `page-uninstall-social.php` and created a page for it so it runs when I visit that page) | We start off by finding out which block styles exists via `.getBlockTypes()`. This will dump it into the console:
```
wp.domReady(() => {
// find blocks styles
wp.blocks.getBlockTypes().forEach((block) => {
if (_.isArray(block['styles'])) {
console.log(block.name, _.pluck(block['styles'], 'name'));
}
});
});
```
Example output:
```
core/image (2) ["default", "rounded"]
core/quote (2) ["default", "large"]
core/button (2) ["fill", "outline"]
core/pullquote (2) ["default", "solid-color"]
core/separator (3) ["default", "wide", "dots"]
core/table (2) ["regular", "stripes"]
core/social-links (3) ["default", "logos-only", "pill-shape"]
```
With this information, we can deactivate the block styles as desired. For example, if we want to remove the `large` quote style, we can use the following in our `remove-block-styles.js`:
```
wp.domReady(() => {
wp.blocks.unregisterBlockStyle('core/quote', 'large');
} );
```
We can load the `remove-block-styles.js` in the themes `functions.php`:
```
function remove_block_style() {
// Register the block editor script.
wp_register_script( 'remove-block-style', get_stylesheet_directory_uri() . '/remove-block-styles.js', [ 'wp-blocks', 'wp-edit-post' ] );
// register block editor script.
register_block_type( 'remove/block-style', [
'editor_script' => 'remove-block-style',
] );
}
add_action( 'init', 'remove_block_style' );
```
If we want to remove all block styles (as listed above), we can use:
```
wp.domReady(() => {
// image
wp.blocks.unregisterBlockStyle('core/image', 'rounded');
wp.blocks.unregisterBlockStyle('core/image', 'default');
// quote
wp.blocks.unregisterBlockStyle('core/quote', 'default');
wp.blocks.unregisterBlockStyle('core/quote', 'large');
// button
wp.blocks.unregisterBlockStyle('core/button', 'fill');
wp.blocks.unregisterBlockStyle('core/button', 'outline');
// pullquote
wp.blocks.unregisterBlockStyle('core/pullquote', 'default');
wp.blocks.unregisterBlockStyle('core/pullquote', 'solid-color');
// separator
wp.blocks.unregisterBlockStyle('core/separator', 'default');
wp.blocks.unregisterBlockStyle('core/separator', 'wide');
wp.blocks.unregisterBlockStyle('core/separator', 'dots');
// table
wp.blocks.unregisterBlockStyle('core/table', 'regular');
wp.blocks.unregisterBlockStyle('core/table', 'stripes');
// social-links
wp.blocks.unregisterBlockStyle('core/social-links', 'default');
wp.blocks.unregisterBlockStyle('core/social-links', 'logos-only');
wp.blocks.unregisterBlockStyle('core/social-links', 'pill-shape');
} );
```
Major credits to [Per Søderlind](https://soderlind.no/hide-block-styles-in-gutenberg/) for the snippets. |
352,616 | <p>So after updating to WP 5.3 I can no longer use the file upload to choose files to add. I get the following error:</p>
<pre><code>Uncaught TypeError: Cannot convert undefined or null to object
at g.cleanup (backbone.min.js:1)
</code></pre>
<p>Error in console:
<a href="https://i.stack.imgur.com/fIz2r.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fIz2r.png" alt="enter image description here"></a></p>
<p>How it shows when I try to choose an image:
<a href="https://i.stack.imgur.com/FXKgd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FXKgd.png" alt="enter image description here"></a></p>
<p>I have the Classic Editor plugin installed so I can use it the classic way. I have disabled all other unnecessary plugins but the problem still persists. It's only happened since the new WP core update to 5.3 yesterday.</p>
<p>Any ideas what's going on here?</p>
| [
{
"answer_id": 352618,
"author": "user3574492",
"author_id": 97479,
"author_profile": "https://wordpress.stackexchange.com/users/97479",
"pm_score": 2,
"selected": true,
"text": "<p>Right, so what worked for me was upgrading my PHP version to 7.2 and that did the job.</p>\n\n<p>I was using 7.0 before.</p>\n"
},
{
"answer_id": 353325,
"author": "joakland",
"author_id": 81159,
"author_profile": "https://wordpress.stackexchange.com/users/81159",
"pm_score": 4,
"selected": false,
"text": "<p>I had the same problem. In my case it was the Enhanced Media Library plugin, which looks as though it has not been updated in some time. I deactivated it, and all is good.</p>\n"
},
{
"answer_id": 371649,
"author": "Pablo Demier",
"author_id": 192130,
"author_profile": "https://wordpress.stackexchange.com/users/192130",
"pm_score": -1,
"selected": false,
"text": "<p>My problem was with ŧhe Enhanced Media Library plugin and this solution worked for me <a href=\"https://wordpress.org/support/topic/quick-fix-for-upload-breakage-after-wp-5-3/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/topic/quick-fix-for-upload-breakage-after-wp-5-3/</a></p>\n"
}
] | 2019/11/15 | [
"https://wordpress.stackexchange.com/questions/352616",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97479/"
] | So after updating to WP 5.3 I can no longer use the file upload to choose files to add. I get the following error:
```
Uncaught TypeError: Cannot convert undefined or null to object
at g.cleanup (backbone.min.js:1)
```
Error in console:
[](https://i.stack.imgur.com/fIz2r.png)
How it shows when I try to choose an image:
[](https://i.stack.imgur.com/FXKgd.png)
I have the Classic Editor plugin installed so I can use it the classic way. I have disabled all other unnecessary plugins but the problem still persists. It's only happened since the new WP core update to 5.3 yesterday.
Any ideas what's going on here? | Right, so what worked for me was upgrading my PHP version to 7.2 and that did the job.
I was using 7.0 before. |
352,621 | <p>I am working on a webinar plugin that uses a custom post type to display the webinar pages. Those pages could be register, thank you, countdown, live etc. depending on the visitors registration status and the current webinar status.</p>
<p>The plugin uses the <code>template_include</code> action to render content based on the current post status and the visitors status (if they are registered or not).</p>
<p>The plugin lets users choose a custom page for one of those webinar pages, like a custom registration page or a custom thank you page. It shows the user a list of their WordPress pages and lets them choose one, then it saves the <code>post_id</code> in <code>wp_post_meta</code>.</p>
<p>In <code>template_include</code> I'm getting the <code>$custom_page_id</code> from <code>wp_post_meta</code> and if it is set, I redirect the visitor to that page in <code>template_include</code> using something like this:</p>
<pre class="lang-php prettyprint-override"><code>$redirect_url = get_permalink($custom_page_id);
wp_redirect($redirect_url);
</code></pre>
<p>So the visitor accesses my custom post url:</p>
<p><code>https://example.com/my-post-type/mypost</code></p>
<p>And is then redirected to:</p>
<p><code>https://example.com/some-other-post</code></p>
<p>What I really want to do is render the entire contents of <code>$custom_page_id</code> without redirecting and ideally pass in some meta data like the original post ID.</p>
<p>Is there any way I can render the full contents of <code>$custom_page_id</code> (including theme header & footer) without having to redirect so the visitor stays on <code>https://example.com/my-post-type/mypost</code> but sees exactly the same content as if they had redirected?</p>
| [
{
"answer_id": 353213,
"author": "Kudratullah",
"author_id": 62726,
"author_profile": "https://wordpress.stackexchange.com/users/62726",
"pm_score": 3,
"selected": true,
"text": "<p>This was a bit tricky to solve your problem.\nthe <code>template_include</code> filter executed after the main query processed the current request. If you can filter the current request (query_vars) and update it accordingly then WordPress will display any post/page you wanted to... Simply filter the <code>query_vars</code> with the <code>request</code> filter. Check the following snippet. But doing this might have a bad effect on SEO.</p>\n\n<pre><code>add_filter( 'request', function( $query_vars ) {\n if( is_admin() ) return $query_vars;\n $_post = null;\n // find the queried post\n if( isset( $query_vars['post_type'], $query_vars['your-post-type'] ) && $query_vars['post_type'] == 'your-post-type' ) {\n // $query_vars['your-post-type'] will contains the post slug\n $_post = get_page_by_path( $query_vars['your-post-type'], OBJECT, $query_vars['post_type'] );\n } else if( isset( $query_vars['p'] ) ) {\n $_post = get_post( $query_vars['p'] );\n if( $_post != 'your-post-type' ) $_post = null;\n }\n if( $_post ) { // post found\n // get the redirect to page id\n $custom_page_id = get_post_meta( $_post->ID, 'custom_page_id', true );\n $custom_page = get_post( $custom_page_id );\n if( $custom_page ) { // valid page/post found.\n // set the query vars to display the page/post\n $query_vars[$custom_page->post_type] = $custom_page->post_name;\n $query_vars['name'] = $custom_page->post_name;\n $query_vars['post_type'] = $custom_page->post_type;\n }\n }\n return $query_vars;\n}, 10 );\n</code></pre>\n"
},
{
"answer_id": 353214,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>The idea of <a href=\"https://developer.wordpress.org/reference/hooks/template_include/\" rel=\"nofollow noreferrer\"><code>template_include</code></a> is to intercept the normal template procedure and replace the template with another one based on some conditions. What you are doing now is to redirect to another url which would, through the normal template procedure, produce the template you want.</p>\n\n<p>You can get your desired outcome by simply let <code>template_include</code> do what it is meant for. Since I don't know exactly how you have stored stuff I can't give you precise code, but it would look like this:</p>\n\n<pre><code>add_filter ('template_include','wpse352621_custom_template',10);\n\nfunction wpse352621_custom_template ($template) {\n if ('webinar' == get_post_type()) { // assuming this is the name of your cpt\n // now, with $custom_page_id, you must not retrieve the url, but the template.\n // you have asked the user which template he wants and stored it somewhere,\n // presumably as user data (*)\n wp_get_current_user();\n $user_template = $current_user->user_template // assuming this is where you stored it\n // now, just to be sure check if that template exists, then assign it\n $template_path = path.to.plugin.or.theme.directory . $user_template;\n if (file_exists ($template_path)) $template = $template_path;\n }\n return $template;\n }\n</code></pre>\n\n<p>(*) That would be the case if every user of the site can choose a template of his liking at this point. If you mean the admin can choose, you could store it as metadata to the post. Or you could even have a separate table somewhere in your plugin relating <code>$custom_page_id</code>'s to templates. That does not fundamentally change what you need to do.</p>\n"
}
] | 2019/11/15 | [
"https://wordpress.stackexchange.com/questions/352621",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52297/"
] | I am working on a webinar plugin that uses a custom post type to display the webinar pages. Those pages could be register, thank you, countdown, live etc. depending on the visitors registration status and the current webinar status.
The plugin uses the `template_include` action to render content based on the current post status and the visitors status (if they are registered or not).
The plugin lets users choose a custom page for one of those webinar pages, like a custom registration page or a custom thank you page. It shows the user a list of their WordPress pages and lets them choose one, then it saves the `post_id` in `wp_post_meta`.
In `template_include` I'm getting the `$custom_page_id` from `wp_post_meta` and if it is set, I redirect the visitor to that page in `template_include` using something like this:
```php
$redirect_url = get_permalink($custom_page_id);
wp_redirect($redirect_url);
```
So the visitor accesses my custom post url:
`https://example.com/my-post-type/mypost`
And is then redirected to:
`https://example.com/some-other-post`
What I really want to do is render the entire contents of `$custom_page_id` without redirecting and ideally pass in some meta data like the original post ID.
Is there any way I can render the full contents of `$custom_page_id` (including theme header & footer) without having to redirect so the visitor stays on `https://example.com/my-post-type/mypost` but sees exactly the same content as if they had redirected? | This was a bit tricky to solve your problem.
the `template_include` filter executed after the main query processed the current request. If you can filter the current request (query\_vars) and update it accordingly then WordPress will display any post/page you wanted to... Simply filter the `query_vars` with the `request` filter. Check the following snippet. But doing this might have a bad effect on SEO.
```
add_filter( 'request', function( $query_vars ) {
if( is_admin() ) return $query_vars;
$_post = null;
// find the queried post
if( isset( $query_vars['post_type'], $query_vars['your-post-type'] ) && $query_vars['post_type'] == 'your-post-type' ) {
// $query_vars['your-post-type'] will contains the post slug
$_post = get_page_by_path( $query_vars['your-post-type'], OBJECT, $query_vars['post_type'] );
} else if( isset( $query_vars['p'] ) ) {
$_post = get_post( $query_vars['p'] );
if( $_post != 'your-post-type' ) $_post = null;
}
if( $_post ) { // post found
// get the redirect to page id
$custom_page_id = get_post_meta( $_post->ID, 'custom_page_id', true );
$custom_page = get_post( $custom_page_id );
if( $custom_page ) { // valid page/post found.
// set the query vars to display the page/post
$query_vars[$custom_page->post_type] = $custom_page->post_name;
$query_vars['name'] = $custom_page->post_name;
$query_vars['post_type'] = $custom_page->post_type;
}
}
return $query_vars;
}, 10 );
``` |
352,669 | <p>The code below displays product category names, links and their thumbnails on hover. The thumbnails ($image) retrieved are those manually set via the woocommerce product category menu. </p>
<p>I am trying to instead, get these product category thumbnails from the best selling product in each. Im really not sure how to include new wp_query & get_post_meta to this. With this addition my thumbnails no longer display at all.</p>
<pre><code>$max_cat_count = 24;
$qty_per_column = 6;
$args = array(
'taxonomy' => 'product_cat',
'number' => $max_cat_count + 1, // keep the + 1
'hide_empty' => 0,
);
$get_cats = get_terms( $args );
$get_cats = ( ! is_wp_error( $get_cats ) ) ? $get_cats : [];
$total = count( $get_cats );
$list_number = 1;
$_new_col = false;
$columns = '';
foreach ( $get_cats as $i => $cat ) {
if ( $i >= $max_cat_count ) {
break;
}
if ( $i % $qty_per_column === 0 ) {
if ( $_new_col ) {
$columns .= '</ul></div><!-- .cat_columns -->';
}
$id = 'cat-col-' . $list_number;
$columns .= '<div class="menu cat_columns" id="' . $id . '">';
$columns .= '<ul class="hoverimage">';
$_new_col = true;
$list_number++;
}
if ( $total > $max_cat_count && $i === $max_cat_count - 1 ) {
$columns .= '<li class="all-link"><a href="/view-all">View All </a></li>';
} else {
$terms = get_terms( 'product_cat', array(
'hide_empty' => false,
) );
foreach ( $terms as $term ) {
$query = new WP_Query( [
'post_type' => 'product',
'posts_per_page' => 1,
'meta_key' => 'total_sales',
'orderby' => 'meta_value_num',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $term->slug,
),
),
] );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$thumbnail = content_url( '/uploads/woocommerce-placeholder-416x416.png' );
if ( has_post_thumbnail() ) {
$thumbnail = get_post_thumbnail_id();
$image = $thumbnail ? wp_get_attachment_url( $thumbnail ) : '';
}
}
}
wp_reset_postdata();
}
$link = '<a href="' . esc_url( get_term_link( $cat ) ) . '">' . esc_html( $cat->name ) . '</a>';
$columns .= '<li class="menu-item" data-image="' . esc_url( $image ) . '">' . $link . '</li>';
}
}
// Close last column, if any.
if ( $_new_col ) {
$columns .= '</ul></div><!-- .cat_columns -->';
}
?>
</code></pre>
| [
{
"answer_id": 353213,
"author": "Kudratullah",
"author_id": 62726,
"author_profile": "https://wordpress.stackexchange.com/users/62726",
"pm_score": 3,
"selected": true,
"text": "<p>This was a bit tricky to solve your problem.\nthe <code>template_include</code> filter executed after the main query processed the current request. If you can filter the current request (query_vars) and update it accordingly then WordPress will display any post/page you wanted to... Simply filter the <code>query_vars</code> with the <code>request</code> filter. Check the following snippet. But doing this might have a bad effect on SEO.</p>\n\n<pre><code>add_filter( 'request', function( $query_vars ) {\n if( is_admin() ) return $query_vars;\n $_post = null;\n // find the queried post\n if( isset( $query_vars['post_type'], $query_vars['your-post-type'] ) && $query_vars['post_type'] == 'your-post-type' ) {\n // $query_vars['your-post-type'] will contains the post slug\n $_post = get_page_by_path( $query_vars['your-post-type'], OBJECT, $query_vars['post_type'] );\n } else if( isset( $query_vars['p'] ) ) {\n $_post = get_post( $query_vars['p'] );\n if( $_post != 'your-post-type' ) $_post = null;\n }\n if( $_post ) { // post found\n // get the redirect to page id\n $custom_page_id = get_post_meta( $_post->ID, 'custom_page_id', true );\n $custom_page = get_post( $custom_page_id );\n if( $custom_page ) { // valid page/post found.\n // set the query vars to display the page/post\n $query_vars[$custom_page->post_type] = $custom_page->post_name;\n $query_vars['name'] = $custom_page->post_name;\n $query_vars['post_type'] = $custom_page->post_type;\n }\n }\n return $query_vars;\n}, 10 );\n</code></pre>\n"
},
{
"answer_id": 353214,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>The idea of <a href=\"https://developer.wordpress.org/reference/hooks/template_include/\" rel=\"nofollow noreferrer\"><code>template_include</code></a> is to intercept the normal template procedure and replace the template with another one based on some conditions. What you are doing now is to redirect to another url which would, through the normal template procedure, produce the template you want.</p>\n\n<p>You can get your desired outcome by simply let <code>template_include</code> do what it is meant for. Since I don't know exactly how you have stored stuff I can't give you precise code, but it would look like this:</p>\n\n<pre><code>add_filter ('template_include','wpse352621_custom_template',10);\n\nfunction wpse352621_custom_template ($template) {\n if ('webinar' == get_post_type()) { // assuming this is the name of your cpt\n // now, with $custom_page_id, you must not retrieve the url, but the template.\n // you have asked the user which template he wants and stored it somewhere,\n // presumably as user data (*)\n wp_get_current_user();\n $user_template = $current_user->user_template // assuming this is where you stored it\n // now, just to be sure check if that template exists, then assign it\n $template_path = path.to.plugin.or.theme.directory . $user_template;\n if (file_exists ($template_path)) $template = $template_path;\n }\n return $template;\n }\n</code></pre>\n\n<p>(*) That would be the case if every user of the site can choose a template of his liking at this point. If you mean the admin can choose, you could store it as metadata to the post. Or you could even have a separate table somewhere in your plugin relating <code>$custom_page_id</code>'s to templates. That does not fundamentally change what you need to do.</p>\n"
}
] | 2019/11/16 | [
"https://wordpress.stackexchange.com/questions/352669",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/174773/"
] | The code below displays product category names, links and their thumbnails on hover. The thumbnails ($image) retrieved are those manually set via the woocommerce product category menu.
I am trying to instead, get these product category thumbnails from the best selling product in each. Im really not sure how to include new wp\_query & get\_post\_meta to this. With this addition my thumbnails no longer display at all.
```
$max_cat_count = 24;
$qty_per_column = 6;
$args = array(
'taxonomy' => 'product_cat',
'number' => $max_cat_count + 1, // keep the + 1
'hide_empty' => 0,
);
$get_cats = get_terms( $args );
$get_cats = ( ! is_wp_error( $get_cats ) ) ? $get_cats : [];
$total = count( $get_cats );
$list_number = 1;
$_new_col = false;
$columns = '';
foreach ( $get_cats as $i => $cat ) {
if ( $i >= $max_cat_count ) {
break;
}
if ( $i % $qty_per_column === 0 ) {
if ( $_new_col ) {
$columns .= '</ul></div><!-- .cat_columns -->';
}
$id = 'cat-col-' . $list_number;
$columns .= '<div class="menu cat_columns" id="' . $id . '">';
$columns .= '<ul class="hoverimage">';
$_new_col = true;
$list_number++;
}
if ( $total > $max_cat_count && $i === $max_cat_count - 1 ) {
$columns .= '<li class="all-link"><a href="/view-all">View All </a></li>';
} else {
$terms = get_terms( 'product_cat', array(
'hide_empty' => false,
) );
foreach ( $terms as $term ) {
$query = new WP_Query( [
'post_type' => 'product',
'posts_per_page' => 1,
'meta_key' => 'total_sales',
'orderby' => 'meta_value_num',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $term->slug,
),
),
] );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$thumbnail = content_url( '/uploads/woocommerce-placeholder-416x416.png' );
if ( has_post_thumbnail() ) {
$thumbnail = get_post_thumbnail_id();
$image = $thumbnail ? wp_get_attachment_url( $thumbnail ) : '';
}
}
}
wp_reset_postdata();
}
$link = '<a href="' . esc_url( get_term_link( $cat ) ) . '">' . esc_html( $cat->name ) . '</a>';
$columns .= '<li class="menu-item" data-image="' . esc_url( $image ) . '">' . $link . '</li>';
}
}
// Close last column, if any.
if ( $_new_col ) {
$columns .= '</ul></div><!-- .cat_columns -->';
}
?>
``` | This was a bit tricky to solve your problem.
the `template_include` filter executed after the main query processed the current request. If you can filter the current request (query\_vars) and update it accordingly then WordPress will display any post/page you wanted to... Simply filter the `query_vars` with the `request` filter. Check the following snippet. But doing this might have a bad effect on SEO.
```
add_filter( 'request', function( $query_vars ) {
if( is_admin() ) return $query_vars;
$_post = null;
// find the queried post
if( isset( $query_vars['post_type'], $query_vars['your-post-type'] ) && $query_vars['post_type'] == 'your-post-type' ) {
// $query_vars['your-post-type'] will contains the post slug
$_post = get_page_by_path( $query_vars['your-post-type'], OBJECT, $query_vars['post_type'] );
} else if( isset( $query_vars['p'] ) ) {
$_post = get_post( $query_vars['p'] );
if( $_post != 'your-post-type' ) $_post = null;
}
if( $_post ) { // post found
// get the redirect to page id
$custom_page_id = get_post_meta( $_post->ID, 'custom_page_id', true );
$custom_page = get_post( $custom_page_id );
if( $custom_page ) { // valid page/post found.
// set the query vars to display the page/post
$query_vars[$custom_page->post_type] = $custom_page->post_name;
$query_vars['name'] = $custom_page->post_name;
$query_vars['post_type'] = $custom_page->post_type;
}
}
return $query_vars;
}, 10 );
``` |
352,672 | <p>I would like to replace the <code>WordPress</code> word in title of Dashboard.</p>
<p><a href="https://i.stack.imgur.com/tLDTf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tLDTf.png" alt="enter image description here"></a></p>
<p>Original title:</p>
<pre><code>Dashboard < Site Title - WordPress
</code></pre>
<p>Expected result:</p>
<pre><code>Dashboard < Site Title - foobar
</code></pre>
<p>I tried to do this with this below code, but it doesn't do what I expected.</p>
<pre><code>add_filter('admin_title', 'my_admin_title', 10, 2);
function my_admin_title($admin_title, $title)
{
return get_bloginfo('name').' &bull; '.$title;
}
</code></pre>
| [
{
"answer_id": 352676,
"author": "Judd Dunagan",
"author_id": 178433,
"author_profile": "https://wordpress.stackexchange.com/users/178433",
"pm_score": 1,
"selected": false,
"text": "<p>If you're talking about this area</p>\n\n<p><a href=\"https://i.stack.imgur.com/wzFjv.png\" rel=\"nofollow noreferrer\">!Wordpress Title</a>]<a href=\"https://i.stack.imgur.com/wzFjv.png\" rel=\"nofollow noreferrer\">1</a></p>\n\n<p>/wp-admin/options-general.php</p>\n\n<p><a href=\"https://i.stack.imgur.com/d0Nwx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/d0Nwx.png\" alt=\"Wordpress Title Setting\"></a></p>\n\n<p>You should not have to insert in PHP</p>\n"
},
{
"answer_id": 352683,
"author": "Ivan Frolov",
"author_id": 178434,
"author_profile": "https://wordpress.stackexchange.com/users/178434",
"pm_score": 3,
"selected": true,
"text": "<p>You've tried correct filter - just needs to update return:</p>\n\n<pre><code>function my_admin_title ( $admin_title, $title ) {\n return $title . ' ‹ ' . get_bloginfo( 'name' ) . ' — ' . 'foobar';\n}\nadd_filter( 'admin_title', 'my_admin_title', 10, 2 );\n</code></pre>\n\n<p>Btw, filter above works only for logged pages, for login page needs to add another filter:</p>\n\n<pre><code>add_filter( 'login_title', 'my_admin_title', 10, 2 );\n</code></pre>\n"
}
] | 2019/11/16 | [
"https://wordpress.stackexchange.com/questions/352672",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78021/"
] | I would like to replace the `WordPress` word in title of Dashboard.
[](https://i.stack.imgur.com/tLDTf.png)
Original title:
```
Dashboard < Site Title - WordPress
```
Expected result:
```
Dashboard < Site Title - foobar
```
I tried to do this with this below code, but it doesn't do what I expected.
```
add_filter('admin_title', 'my_admin_title', 10, 2);
function my_admin_title($admin_title, $title)
{
return get_bloginfo('name').' • '.$title;
}
``` | You've tried correct filter - just needs to update return:
```
function my_admin_title ( $admin_title, $title ) {
return $title . ' ‹ ' . get_bloginfo( 'name' ) . ' — ' . 'foobar';
}
add_filter( 'admin_title', 'my_admin_title', 10, 2 );
```
Btw, filter above works only for logged pages, for login page needs to add another filter:
```
add_filter( 'login_title', 'my_admin_title', 10, 2 );
``` |
352,723 | <p>When I update my page I see this error and I tried to fix it but that didn't work. I removed all plugins and checked but it was still not fixed. Then I removed all themes and installed another theme but still it is not fixed. Now I am confused how to fix it. Please guide me how to fix it and why this error is showing?</p>
| [
{
"answer_id": 352751,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 2,
"selected": false,
"text": "<p>That may not be a valid error. But the troubleshooting link provided in a comment to your question is a good place to start. Error logs are great help.</p>\n\n<p>You should also provide additional info (edit your question). When does this happen? All pages? Admin area only? Alternate Tuesdays?</p>\n\n<p>Make sure that you install themes/plugins only from the WP repository. There have been instances of malware'd plugins/themes causing problems.</p>\n"
},
{
"answer_id": 360104,
"author": "Lukman Yale",
"author_id": 183859,
"author_profile": "https://wordpress.stackexchange.com/users/183859",
"pm_score": 1,
"selected": false,
"text": "<p>Here's how I resolved this same issue when it completely logged me out of my site:\n- Install wp-rollback plugin via FTP or Cpanel > File Manager\n- To activate the plugin, follow this instruction here: <a href=\"https://wordpress.stackexchange.com/questions/199798/activate-a-plugin-through-phpmyadmin-or-ftp\">Activate a plugin through PHPMyAdmin or FTP?</a></p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 363451,
"author": "Ateeq Rafeeq",
"author_id": 170243,
"author_profile": "https://wordpress.stackexchange.com/users/170243",
"pm_score": 3,
"selected": false,
"text": "<p>You should troubleshoot your website for plugins and WordPress Themes.</p>\n<p>Make sure your PHP version is 7.3 or above.</p>\n<p>As you are unable to access your WordPress admin area so please try to access your file manager in cPanel or access public_html directory via FTP. Plugins and Themes directories are inside wp-content/ directories.</p>\n<p>Go to wp-content/ Directory them rename plugins/ directory to pluginsbackup/ now try to load your site. If this works that means you have problem with a plugin.</p>\n<p>If problem is with plugin change back the directory name pluginsbackup/ to plugins/ Enter in plugin directory. Now rename each plugins directory by placing backup at end of that directory name.</p>\n<p>Once you have changed all plugins directories names, start getting original directory names one by one and make sure you check the website if that’s still working after each plugin start working. As soon as you see which plugin is making problem just delete that plugin.</p>\n<p>Source <a href=\"https://www.webfulcreations.com/there-has-been-a-critical-error-on-your-website/\" rel=\"nofollow noreferrer\">There has been a critical error on your website</a>.</p>\n<p>If you can't figure out what's wrong please turn on the wp debug mode so you can get details of error. Edit your wp-config.php from WordPress root using FTP. And</p>\n<p>Find in <strong>wp-config.php</strong></p>\n<pre><code>define('WP_DEBUG', false);\n</code></pre>\n<p>And replace with</p>\n<pre><code>define('WP_DEBUG', true);\n</code></pre>\n<p>Once you turn on the wp debug mode you are not able to see the details of issue, weather is related to some missing file or some plugin is producing the FATAL error you can track and apply appropriate fix. Thanks. Once problem is fixed don't forget to turn off the debug mode in <code>wp-config.php</code></p>\n"
},
{
"answer_id": 378371,
"author": "Usama Khalid",
"author_id": 197728,
"author_profile": "https://wordpress.stackexchange.com/users/197728",
"pm_score": 2,
"selected": false,
"text": "<p>Well, I fixed the error by increasing the memory_limit and upload_max_filesize and it solved the problem quickly! Thank you to all guys here who made the ways for me!</p>\n"
}
] | 2019/11/17 | [
"https://wordpress.stackexchange.com/questions/352723",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178458/"
] | When I update my page I see this error and I tried to fix it but that didn't work. I removed all plugins and checked but it was still not fixed. Then I removed all themes and installed another theme but still it is not fixed. Now I am confused how to fix it. Please guide me how to fix it and why this error is showing? | You should troubleshoot your website for plugins and WordPress Themes.
Make sure your PHP version is 7.3 or above.
As you are unable to access your WordPress admin area so please try to access your file manager in cPanel or access public\_html directory via FTP. Plugins and Themes directories are inside wp-content/ directories.
Go to wp-content/ Directory them rename plugins/ directory to pluginsbackup/ now try to load your site. If this works that means you have problem with a plugin.
If problem is with plugin change back the directory name pluginsbackup/ to plugins/ Enter in plugin directory. Now rename each plugins directory by placing backup at end of that directory name.
Once you have changed all plugins directories names, start getting original directory names one by one and make sure you check the website if that’s still working after each plugin start working. As soon as you see which plugin is making problem just delete that plugin.
Source [There has been a critical error on your website](https://www.webfulcreations.com/there-has-been-a-critical-error-on-your-website/).
If you can't figure out what's wrong please turn on the wp debug mode so you can get details of error. Edit your wp-config.php from WordPress root using FTP. And
Find in **wp-config.php**
```
define('WP_DEBUG', false);
```
And replace with
```
define('WP_DEBUG', true);
```
Once you turn on the wp debug mode you are not able to see the details of issue, weather is related to some missing file or some plugin is producing the FATAL error you can track and apply appropriate fix. Thanks. Once problem is fixed don't forget to turn off the debug mode in `wp-config.php` |
352,767 | <p>I have a form with AJAX Submit. I am getting the value of fields as null.</p>
<pre><code>jQuery('#DownloadForm').submit(ajaxSubmit);
function ajaxSubmit() {
var DownloadForm = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: aj_ajax_demo.ajax_url,
data : {
action : 'set_lead_cookie_and_mail', // Note that this is part of the add_action() call.
nonce : aj_ajax_demo.aj_demo_nonce, // Note that 'aj_demo_nonce' is from the wp_localize_script() call.
form_data : DownloadForm
},
success: function(response) {
console.log(response);
}
});
return false;
}
</code></pre>
<p>And this is how I am fetching the data.</p>
<pre><code>add_action( 'wp_ajax_nopriv_set_lead_cookie_and_mail', 'mail_and_cookie_function' );
add_action( 'wp_ajax_set_lead_cookie_and_mail', 'mail_and_cookie_function' );
function mail_and_cookie_function() {
check_ajax_referer( 'aj-demo-nonce', 'nonce' ); // This function will die if nonce is not correct.
$name = sanitize_text_field($_POST["wpcf-lead-name"]);
$email = sanitize_text_field($_POST["wpcf-lead-email"]);
$number = sanitize_text_field($_POST["wpcf-lead-number"]);
$class = $_POST["wpcf-class"];
$category = sanitize_text_field($_POST["hidden_category"]);
if(!$_COOKIE[$category]) {
setcookie($category, "1", time()+2592000);
wp_send_json($class);
}
wp_die();
}
</code></pre>
<p>My response header is sending all the data correctly.</p>
<p>I am getting null as the response. I expect to get the value of the forms submitted.</p>
| [
{
"answer_id": 352751,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 2,
"selected": false,
"text": "<p>That may not be a valid error. But the troubleshooting link provided in a comment to your question is a good place to start. Error logs are great help.</p>\n\n<p>You should also provide additional info (edit your question). When does this happen? All pages? Admin area only? Alternate Tuesdays?</p>\n\n<p>Make sure that you install themes/plugins only from the WP repository. There have been instances of malware'd plugins/themes causing problems.</p>\n"
},
{
"answer_id": 360104,
"author": "Lukman Yale",
"author_id": 183859,
"author_profile": "https://wordpress.stackexchange.com/users/183859",
"pm_score": 1,
"selected": false,
"text": "<p>Here's how I resolved this same issue when it completely logged me out of my site:\n- Install wp-rollback plugin via FTP or Cpanel > File Manager\n- To activate the plugin, follow this instruction here: <a href=\"https://wordpress.stackexchange.com/questions/199798/activate-a-plugin-through-phpmyadmin-or-ftp\">Activate a plugin through PHPMyAdmin or FTP?</a></p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 363451,
"author": "Ateeq Rafeeq",
"author_id": 170243,
"author_profile": "https://wordpress.stackexchange.com/users/170243",
"pm_score": 3,
"selected": false,
"text": "<p>You should troubleshoot your website for plugins and WordPress Themes.</p>\n<p>Make sure your PHP version is 7.3 or above.</p>\n<p>As you are unable to access your WordPress admin area so please try to access your file manager in cPanel or access public_html directory via FTP. Plugins and Themes directories are inside wp-content/ directories.</p>\n<p>Go to wp-content/ Directory them rename plugins/ directory to pluginsbackup/ now try to load your site. If this works that means you have problem with a plugin.</p>\n<p>If problem is with plugin change back the directory name pluginsbackup/ to plugins/ Enter in plugin directory. Now rename each plugins directory by placing backup at end of that directory name.</p>\n<p>Once you have changed all plugins directories names, start getting original directory names one by one and make sure you check the website if that’s still working after each plugin start working. As soon as you see which plugin is making problem just delete that plugin.</p>\n<p>Source <a href=\"https://www.webfulcreations.com/there-has-been-a-critical-error-on-your-website/\" rel=\"nofollow noreferrer\">There has been a critical error on your website</a>.</p>\n<p>If you can't figure out what's wrong please turn on the wp debug mode so you can get details of error. Edit your wp-config.php from WordPress root using FTP. And</p>\n<p>Find in <strong>wp-config.php</strong></p>\n<pre><code>define('WP_DEBUG', false);\n</code></pre>\n<p>And replace with</p>\n<pre><code>define('WP_DEBUG', true);\n</code></pre>\n<p>Once you turn on the wp debug mode you are not able to see the details of issue, weather is related to some missing file or some plugin is producing the FATAL error you can track and apply appropriate fix. Thanks. Once problem is fixed don't forget to turn off the debug mode in <code>wp-config.php</code></p>\n"
},
{
"answer_id": 378371,
"author": "Usama Khalid",
"author_id": 197728,
"author_profile": "https://wordpress.stackexchange.com/users/197728",
"pm_score": 2,
"selected": false,
"text": "<p>Well, I fixed the error by increasing the memory_limit and upload_max_filesize and it solved the problem quickly! Thank you to all guys here who made the ways for me!</p>\n"
}
] | 2019/11/18 | [
"https://wordpress.stackexchange.com/questions/352767",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/167545/"
] | I have a form with AJAX Submit. I am getting the value of fields as null.
```
jQuery('#DownloadForm').submit(ajaxSubmit);
function ajaxSubmit() {
var DownloadForm = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: aj_ajax_demo.ajax_url,
data : {
action : 'set_lead_cookie_and_mail', // Note that this is part of the add_action() call.
nonce : aj_ajax_demo.aj_demo_nonce, // Note that 'aj_demo_nonce' is from the wp_localize_script() call.
form_data : DownloadForm
},
success: function(response) {
console.log(response);
}
});
return false;
}
```
And this is how I am fetching the data.
```
add_action( 'wp_ajax_nopriv_set_lead_cookie_and_mail', 'mail_and_cookie_function' );
add_action( 'wp_ajax_set_lead_cookie_and_mail', 'mail_and_cookie_function' );
function mail_and_cookie_function() {
check_ajax_referer( 'aj-demo-nonce', 'nonce' ); // This function will die if nonce is not correct.
$name = sanitize_text_field($_POST["wpcf-lead-name"]);
$email = sanitize_text_field($_POST["wpcf-lead-email"]);
$number = sanitize_text_field($_POST["wpcf-lead-number"]);
$class = $_POST["wpcf-class"];
$category = sanitize_text_field($_POST["hidden_category"]);
if(!$_COOKIE[$category]) {
setcookie($category, "1", time()+2592000);
wp_send_json($class);
}
wp_die();
}
```
My response header is sending all the data correctly.
I am getting null as the response. I expect to get the value of the forms submitted. | You should troubleshoot your website for plugins and WordPress Themes.
Make sure your PHP version is 7.3 or above.
As you are unable to access your WordPress admin area so please try to access your file manager in cPanel or access public\_html directory via FTP. Plugins and Themes directories are inside wp-content/ directories.
Go to wp-content/ Directory them rename plugins/ directory to pluginsbackup/ now try to load your site. If this works that means you have problem with a plugin.
If problem is with plugin change back the directory name pluginsbackup/ to plugins/ Enter in plugin directory. Now rename each plugins directory by placing backup at end of that directory name.
Once you have changed all plugins directories names, start getting original directory names one by one and make sure you check the website if that’s still working after each plugin start working. As soon as you see which plugin is making problem just delete that plugin.
Source [There has been a critical error on your website](https://www.webfulcreations.com/there-has-been-a-critical-error-on-your-website/).
If you can't figure out what's wrong please turn on the wp debug mode so you can get details of error. Edit your wp-config.php from WordPress root using FTP. And
Find in **wp-config.php**
```
define('WP_DEBUG', false);
```
And replace with
```
define('WP_DEBUG', true);
```
Once you turn on the wp debug mode you are not able to see the details of issue, weather is related to some missing file or some plugin is producing the FATAL error you can track and apply appropriate fix. Thanks. Once problem is fixed don't forget to turn off the debug mode in `wp-config.php` |
352,794 | <p>I'm looking for a solution to set my <a href="https://wordpress.org/support/article/dashboard-screen/" rel="nofollow noreferrer">WordPress login page</a> as the homepage. Maybe a redirect 301 will work. Are there any other solutions?</p>
| [
{
"answer_id": 352805,
"author": "John Swaringen",
"author_id": 723,
"author_profile": "https://wordpress.stackexchange.com/users/723",
"pm_score": 2,
"selected": false,
"text": "<p>Add the following to your <code>.htaccess</code> file:</p>\n\n<pre><code># Custom default index page\nDirectoryIndex ./wp-login.php\n</code></pre>\n\n<p>That should work.</p>\n"
},
{
"answer_id": 385042,
"author": "Tanbir",
"author_id": 203316,
"author_profile": "https://wordpress.stackexchange.com/users/203316",
"pm_score": 1,
"selected": false,
"text": "<p>Comment the last line and just add this line to index.php file</p>\n<pre><code> require __DIR__ . '/wp-login.php';\n</code></pre>\n<p>Means, it will look like this</p>\n<pre><code> ........\n #require __DIR__ . '/wp-blog-header.php';\n require __DIR__ . '/wp-login.php';\n</code></pre>\n"
}
] | 2019/11/18 | [
"https://wordpress.stackexchange.com/questions/352794",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82174/"
] | I'm looking for a solution to set my [WordPress login page](https://wordpress.org/support/article/dashboard-screen/) as the homepage. Maybe a redirect 301 will work. Are there any other solutions? | Add the following to your `.htaccess` file:
```
# Custom default index page
DirectoryIndex ./wp-login.php
```
That should work. |
352,896 | <p>Having an issue with my plugin updating the htaccess file. The code I used to do that is:</p>
<pre><code>insert_with_markers($htaccess_file, $marker, $lines);
</code></pre>
<p>The parameters used in that function have been previously defined properly. There error message is:</p>
<pre><code> Uncaught Error: Call to a member function switch_to_locale() on null
in /home2/path/to/site/fstraptest/wp-includes/l10n.php:1582
</code></pre>
<p>I tried ensuring that various functions used by switch_to_locale() are loaded:</p>
<pre><code>if (! function_exists('get_home_path'))
{include_once(ABSPATH . 'wp-admin/includes/file.php');}
if (! function_exists('insert_with_markers'))
{include_once(ABSPATH . 'wp-admin/includes/misc.php');}
if (! function_exists('switch_to_locale'))
{
include_once(ABSPATH . 'wp-admin/includes/l10n.php');
include_once(ABSPATH . 'wp-includes/class-wp-locale-switcher.php');
}
if (! function_exists('got_mod_rewrite'))
{include_once(ABSPATH . 'wp-admin/includes/misc.php');}
if (! function_exists('is_multisite'))
{include_once(ABSPATH . 'wp-admin/includes/load.php');}
</code></pre>
<p>But that didn't solve the issue. </p>
<p>This is with WP 5.3, PHP 7.3.11 . Similar code has worked before; this may have started with WP 5.3, but not sure. </p>
<p>The googles have not helped with this error. The language for the site is "en-US". The plugin does not have any language files. Theme has been changed to "Twenty-Thirteen"; error also occurs in other themes, so does not appear theme-dependent. </p>
<p><strong>Additional Code</strong></p>
<p>At the top of the plugin file, this code initializes the settings</p>
<pre><code>add_action( 'admin_init', 'CWPSO_settings_init' ); // does register_setting, add_settings_section add_settings_field, etc
</code></pre>
<p>The <code>CWPSO_settings_init()</code> does the register thing, then there are a bunch of <code>add_settings_field()</code> to set up the options. All of those look similar to this:</p>
<pre><code>add_settings_field(
'CWPSO_protect_config_file', // field name
__( '', 'CWPSO_namespace' ), // message before field (not used)
'CWPSO_protect_config_file_render', // render function
'pluginPage', // plugin page name
'CWPSO_pluginPage_section' // plugin section name
);
</code></pre>
<p>This code sanitizes that input field:</p>
<pre><code>if (isset($_POST['CWPSO_protect_config_file'])) {
$new_input['CWPSO_protect_config_file'] = "1";} else { $new_input['CWPSO_protect_config_file'] = "0";}
</code></pre>
<p>This code sets up an array of things that might happen to the htaccess file</p>
<pre><code>if (($options['CWPSO_protect_config_file']) and ($_GET['page'] == 'cellarweb_private_function')) {
$change_htaccess[] = 'CWPSO_protect_config_file';
}
</code></pre>
<p>This code checks the previous htaccess array, and builds the statements to put in the htaccess</p>
<pre><code>if (in_array('CWPSO_protect_config_file', $change_htaccess) ) {
$lines[] = ' # protect wp-config.php file from direct access';
$lines[] = ' <files wp-config.php>';
$lines[] = ' order allow,deny';
$lines[] = ' deny from all';
$lines[] = ' </files>';
}
</code></pre>
<p>This code does the actual htaccess file modification ($marker has been previously set)</p>
<pre><code>$success = insert_with_markers($htaccess_file, $marker, $lines);
</code></pre>
<p>And that <code>insert_with_markers()</code> line causes the error. Note that all of the settings that the plugin uses/creates/save work properly. If I comment out the <code>insert_with_markers()</code> line, the plugin settings display/save properly.</p>
| [
{
"answer_id": 352982,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 1,
"selected": false,
"text": "<p>From your comment:</p>\n\n<blockquote>\n <p>Those <code>htaccess</code> changes don't happen as a result of an <code>add_action</code>.\n Perhaps they should?</p>\n</blockquote>\n\n<p><strong>Yes, they should.</strong></p>\n\n<h2>And here's why</h2>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/insert_with_markers/\" rel=\"nofollow noreferrer\"><code>insert_with_markers()</code></a> calls <a href=\"https://developer.wordpress.org/reference/functions/switch_to_locale/\" rel=\"nofollow noreferrer\"><code>switch_to_locale()</code></a> which uses <code>$GLOBALS['wp_locale_switcher']</code> (or <code>$wp_locale_switcher</code>) which is initialized in <code>wp-settings.php</code>, but only after WordPress runs the <a href=\"https://developer.wordpress.org/reference/hooks/setup_theme/\" rel=\"nofollow noreferrer\"><code>setup_theme</code></a> hook.</p>\n\n<p>And looking at the error in question and <a href=\"https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/l10n.php#L1582\" rel=\"nofollow noreferrer\">line #1582</a> in <code>wp-includes/l10n.php</code> which is <code>return $wp_locale_switcher->switch_to_locale( $locale );</code>, that error occurred most likely because the global variable <code>$wp_locale_switcher</code> has not yet been defined or initialized. Which indicates that you called <code>insert_with_markers()</code> too early.</p>\n\n<p>So if you want to use <code>insert_with_markers()</code>, make sure you use the proper hook; for example, <a href=\"https://developer.wordpress.org/reference/hooks/load-page_hook/\" rel=\"nofollow noreferrer\"><code>load-{$page_hook}</code></a> or <a href=\"https://developer.wordpress.org/reference/hooks/update_option_option/\" rel=\"nofollow noreferrer\"><code>update_option_{$option}</code></a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Example 1:\nadd_action( 'admin_menu', function () {\n $hookname = add_menu_page( ... );\n add_action( 'load-' . $hookname, function () {\n // Call insert_with_markers()\n } );\n} );\n\n// Example 2:\nadd_action( 'update_option_my_field', function ( $old_value, $value ) {\n // Call insert_with_markers()\n}, 10, 2 );\n</code></pre>\n\n<p>Both tried & tested working on WordPress 5.2.4 and 5.3.</p>\n\n<p><em>But it's also possible there's a plugin or custom code which is messing with <code>$wp_locale_switcher</code>, so if using a hook later than <code>setup_theme</code> doesn't work for you, you can try deactivating plugins..</em></p>\n"
},
{
"answer_id": 353679,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": true,
"text": "<p>I discovered that there was an extra '-' character just above the line that caused the error. It was hard to see in my editor (and maybe because of some dust on the screen).</p>\n\n<p>The syntax checker in my editor (Rapid PHP 2018) didn't sense that error Only by looking very close did I find the extra character. Removing that fixed the problem.</p>\n\n<p>The lesson learned (again) is that sometimes the reported error line is not the problem. Errors can also be caused by statements previous to the reported line.</p>\n\n<p>But thanks for the assistance; learned something from them also. So, net 'win'...although very frustrating to figure it out.</p>\n"
}
] | 2019/11/20 | [
"https://wordpress.stackexchange.com/questions/352896",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29416/"
] | Having an issue with my plugin updating the htaccess file. The code I used to do that is:
```
insert_with_markers($htaccess_file, $marker, $lines);
```
The parameters used in that function have been previously defined properly. There error message is:
```
Uncaught Error: Call to a member function switch_to_locale() on null
in /home2/path/to/site/fstraptest/wp-includes/l10n.php:1582
```
I tried ensuring that various functions used by switch\_to\_locale() are loaded:
```
if (! function_exists('get_home_path'))
{include_once(ABSPATH . 'wp-admin/includes/file.php');}
if (! function_exists('insert_with_markers'))
{include_once(ABSPATH . 'wp-admin/includes/misc.php');}
if (! function_exists('switch_to_locale'))
{
include_once(ABSPATH . 'wp-admin/includes/l10n.php');
include_once(ABSPATH . 'wp-includes/class-wp-locale-switcher.php');
}
if (! function_exists('got_mod_rewrite'))
{include_once(ABSPATH . 'wp-admin/includes/misc.php');}
if (! function_exists('is_multisite'))
{include_once(ABSPATH . 'wp-admin/includes/load.php');}
```
But that didn't solve the issue.
This is with WP 5.3, PHP 7.3.11 . Similar code has worked before; this may have started with WP 5.3, but not sure.
The googles have not helped with this error. The language for the site is "en-US". The plugin does not have any language files. Theme has been changed to "Twenty-Thirteen"; error also occurs in other themes, so does not appear theme-dependent.
**Additional Code**
At the top of the plugin file, this code initializes the settings
```
add_action( 'admin_init', 'CWPSO_settings_init' ); // does register_setting, add_settings_section add_settings_field, etc
```
The `CWPSO_settings_init()` does the register thing, then there are a bunch of `add_settings_field()` to set up the options. All of those look similar to this:
```
add_settings_field(
'CWPSO_protect_config_file', // field name
__( '', 'CWPSO_namespace' ), // message before field (not used)
'CWPSO_protect_config_file_render', // render function
'pluginPage', // plugin page name
'CWPSO_pluginPage_section' // plugin section name
);
```
This code sanitizes that input field:
```
if (isset($_POST['CWPSO_protect_config_file'])) {
$new_input['CWPSO_protect_config_file'] = "1";} else { $new_input['CWPSO_protect_config_file'] = "0";}
```
This code sets up an array of things that might happen to the htaccess file
```
if (($options['CWPSO_protect_config_file']) and ($_GET['page'] == 'cellarweb_private_function')) {
$change_htaccess[] = 'CWPSO_protect_config_file';
}
```
This code checks the previous htaccess array, and builds the statements to put in the htaccess
```
if (in_array('CWPSO_protect_config_file', $change_htaccess) ) {
$lines[] = ' # protect wp-config.php file from direct access';
$lines[] = ' <files wp-config.php>';
$lines[] = ' order allow,deny';
$lines[] = ' deny from all';
$lines[] = ' </files>';
}
```
This code does the actual htaccess file modification ($marker has been previously set)
```
$success = insert_with_markers($htaccess_file, $marker, $lines);
```
And that `insert_with_markers()` line causes the error. Note that all of the settings that the plugin uses/creates/save work properly. If I comment out the `insert_with_markers()` line, the plugin settings display/save properly. | I discovered that there was an extra '-' character just above the line that caused the error. It was hard to see in my editor (and maybe because of some dust on the screen).
The syntax checker in my editor (Rapid PHP 2018) didn't sense that error Only by looking very close did I find the extra character. Removing that fixed the problem.
The lesson learned (again) is that sometimes the reported error line is not the problem. Errors can also be caused by statements previous to the reported line.
But thanks for the assistance; learned something from them also. So, net 'win'...although very frustrating to figure it out. |
352,900 | <p>I'm having issues with being able to get to my image files inside the Media Library. I'm having issues, since I have transferred my WordPress website from my local server to the live environment.</p>
<p>In the below screenshot you can see the files are in the correct directory:</p>
<p>wp-content/uploads/</p>
<p><a href="https://i.stack.imgur.com/fQ0Zo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fQ0Zo.png" alt="enter image description here"></a></p>
<p>I did try to also just drag and drop an image into my media library but get this error-" could not insert post into the database". </p>
<p>I double checked my permissions and they are correct with folders set to 755 and files set to 644.</p>
<p>My wp-config.php file is also setup to the correct table for my .sql database</p>
<p>Also, I included this code:</p>
<pre><code>define('WP_MEMORY_LIMIT', '1024M');
</code></pre>
<p>to the wp-config.php file, so this isn't the issue.</p>
<p>Thanks for the help</p>
| [
{
"answer_id": 352982,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 1,
"selected": false,
"text": "<p>From your comment:</p>\n\n<blockquote>\n <p>Those <code>htaccess</code> changes don't happen as a result of an <code>add_action</code>.\n Perhaps they should?</p>\n</blockquote>\n\n<p><strong>Yes, they should.</strong></p>\n\n<h2>And here's why</h2>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/insert_with_markers/\" rel=\"nofollow noreferrer\"><code>insert_with_markers()</code></a> calls <a href=\"https://developer.wordpress.org/reference/functions/switch_to_locale/\" rel=\"nofollow noreferrer\"><code>switch_to_locale()</code></a> which uses <code>$GLOBALS['wp_locale_switcher']</code> (or <code>$wp_locale_switcher</code>) which is initialized in <code>wp-settings.php</code>, but only after WordPress runs the <a href=\"https://developer.wordpress.org/reference/hooks/setup_theme/\" rel=\"nofollow noreferrer\"><code>setup_theme</code></a> hook.</p>\n\n<p>And looking at the error in question and <a href=\"https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/l10n.php#L1582\" rel=\"nofollow noreferrer\">line #1582</a> in <code>wp-includes/l10n.php</code> which is <code>return $wp_locale_switcher->switch_to_locale( $locale );</code>, that error occurred most likely because the global variable <code>$wp_locale_switcher</code> has not yet been defined or initialized. Which indicates that you called <code>insert_with_markers()</code> too early.</p>\n\n<p>So if you want to use <code>insert_with_markers()</code>, make sure you use the proper hook; for example, <a href=\"https://developer.wordpress.org/reference/hooks/load-page_hook/\" rel=\"nofollow noreferrer\"><code>load-{$page_hook}</code></a> or <a href=\"https://developer.wordpress.org/reference/hooks/update_option_option/\" rel=\"nofollow noreferrer\"><code>update_option_{$option}</code></a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Example 1:\nadd_action( 'admin_menu', function () {\n $hookname = add_menu_page( ... );\n add_action( 'load-' . $hookname, function () {\n // Call insert_with_markers()\n } );\n} );\n\n// Example 2:\nadd_action( 'update_option_my_field', function ( $old_value, $value ) {\n // Call insert_with_markers()\n}, 10, 2 );\n</code></pre>\n\n<p>Both tried & tested working on WordPress 5.2.4 and 5.3.</p>\n\n<p><em>But it's also possible there's a plugin or custom code which is messing with <code>$wp_locale_switcher</code>, so if using a hook later than <code>setup_theme</code> doesn't work for you, you can try deactivating plugins..</em></p>\n"
},
{
"answer_id": 353679,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": true,
"text": "<p>I discovered that there was an extra '-' character just above the line that caused the error. It was hard to see in my editor (and maybe because of some dust on the screen).</p>\n\n<p>The syntax checker in my editor (Rapid PHP 2018) didn't sense that error Only by looking very close did I find the extra character. Removing that fixed the problem.</p>\n\n<p>The lesson learned (again) is that sometimes the reported error line is not the problem. Errors can also be caused by statements previous to the reported line.</p>\n\n<p>But thanks for the assistance; learned something from them also. So, net 'win'...although very frustrating to figure it out.</p>\n"
}
] | 2019/11/20 | [
"https://wordpress.stackexchange.com/questions/352900",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178186/"
] | I'm having issues with being able to get to my image files inside the Media Library. I'm having issues, since I have transferred my WordPress website from my local server to the live environment.
In the below screenshot you can see the files are in the correct directory:
wp-content/uploads/
[](https://i.stack.imgur.com/fQ0Zo.png)
I did try to also just drag and drop an image into my media library but get this error-" could not insert post into the database".
I double checked my permissions and they are correct with folders set to 755 and files set to 644.
My wp-config.php file is also setup to the correct table for my .sql database
Also, I included this code:
```
define('WP_MEMORY_LIMIT', '1024M');
```
to the wp-config.php file, so this isn't the issue.
Thanks for the help | I discovered that there was an extra '-' character just above the line that caused the error. It was hard to see in my editor (and maybe because of some dust on the screen).
The syntax checker in my editor (Rapid PHP 2018) didn't sense that error Only by looking very close did I find the extra character. Removing that fixed the problem.
The lesson learned (again) is that sometimes the reported error line is not the problem. Errors can also be caused by statements previous to the reported line.
But thanks for the assistance; learned something from them also. So, net 'win'...although very frustrating to figure it out. |
353,004 | <p>I have a problem after migrating a WordPress site from Plesk and IIS to LAMP server.</p>
<p>I cannot access the Admin Panel, I can access <code>/wp-admin/</code> and can login successfully but I get redirected to the home page and not to Admin Page.</p>
<p>If I set <code>define('WP_DEBUG', true)</code> in <code>wp-config.php</code> file I get this error:</p>
<blockquote>
<p>Notice: Use of undefined constant _COOKIE - assumed '_COOKIE' in public_html/wp-content/themes/Avada/includes/fusion-functions.php on line 390
Sorry, you are not allowed to access this page.</p>
</blockquote>
<p>This line has the following code:</p>
<pre><code>if (!current_user_can('read') && !isset(${_COOKIE}['wp_min'])) {
</code></pre>
<p>I have manually added <code>.htaccess</code> file during migration and its content is:</p>
<pre><code>#BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p><strong>UPDATE</strong></p>
<p>PHP version is 7.0.27 and used to be 5.4.</p>
<p>I have already tried:</p>
<ul>
<li>Renamed plugins folder</li>
<li>Changed to default theme (my editing database entry in table options)</li>
<li>Changed keys in <code>wp-config.php</code></li>
<li><p>Added to <code>wp-config.php</code> file </p>
<pre><code>define(‘ADMIN_COOKIE_PATH’, ‘/’);
define(‘COOKIE_DOMAIN’, ”);
define(‘COOKIEPATH’, ”);
define(‘SITECOOKIEPATH’, ”);
</code></pre></li>
</ul>
<p>None of these has helped. I still cannot access the Admin Panel. Error remains the same.</p>
| [
{
"answer_id": 352982,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 1,
"selected": false,
"text": "<p>From your comment:</p>\n\n<blockquote>\n <p>Those <code>htaccess</code> changes don't happen as a result of an <code>add_action</code>.\n Perhaps they should?</p>\n</blockquote>\n\n<p><strong>Yes, they should.</strong></p>\n\n<h2>And here's why</h2>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/insert_with_markers/\" rel=\"nofollow noreferrer\"><code>insert_with_markers()</code></a> calls <a href=\"https://developer.wordpress.org/reference/functions/switch_to_locale/\" rel=\"nofollow noreferrer\"><code>switch_to_locale()</code></a> which uses <code>$GLOBALS['wp_locale_switcher']</code> (or <code>$wp_locale_switcher</code>) which is initialized in <code>wp-settings.php</code>, but only after WordPress runs the <a href=\"https://developer.wordpress.org/reference/hooks/setup_theme/\" rel=\"nofollow noreferrer\"><code>setup_theme</code></a> hook.</p>\n\n<p>And looking at the error in question and <a href=\"https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/l10n.php#L1582\" rel=\"nofollow noreferrer\">line #1582</a> in <code>wp-includes/l10n.php</code> which is <code>return $wp_locale_switcher->switch_to_locale( $locale );</code>, that error occurred most likely because the global variable <code>$wp_locale_switcher</code> has not yet been defined or initialized. Which indicates that you called <code>insert_with_markers()</code> too early.</p>\n\n<p>So if you want to use <code>insert_with_markers()</code>, make sure you use the proper hook; for example, <a href=\"https://developer.wordpress.org/reference/hooks/load-page_hook/\" rel=\"nofollow noreferrer\"><code>load-{$page_hook}</code></a> or <a href=\"https://developer.wordpress.org/reference/hooks/update_option_option/\" rel=\"nofollow noreferrer\"><code>update_option_{$option}</code></a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Example 1:\nadd_action( 'admin_menu', function () {\n $hookname = add_menu_page( ... );\n add_action( 'load-' . $hookname, function () {\n // Call insert_with_markers()\n } );\n} );\n\n// Example 2:\nadd_action( 'update_option_my_field', function ( $old_value, $value ) {\n // Call insert_with_markers()\n}, 10, 2 );\n</code></pre>\n\n<p>Both tried & tested working on WordPress 5.2.4 and 5.3.</p>\n\n<p><em>But it's also possible there's a plugin or custom code which is messing with <code>$wp_locale_switcher</code>, so if using a hook later than <code>setup_theme</code> doesn't work for you, you can try deactivating plugins..</em></p>\n"
},
{
"answer_id": 353679,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": true,
"text": "<p>I discovered that there was an extra '-' character just above the line that caused the error. It was hard to see in my editor (and maybe because of some dust on the screen).</p>\n\n<p>The syntax checker in my editor (Rapid PHP 2018) didn't sense that error Only by looking very close did I find the extra character. Removing that fixed the problem.</p>\n\n<p>The lesson learned (again) is that sometimes the reported error line is not the problem. Errors can also be caused by statements previous to the reported line.</p>\n\n<p>But thanks for the assistance; learned something from them also. So, net 'win'...although very frustrating to figure it out.</p>\n"
}
] | 2019/11/21 | [
"https://wordpress.stackexchange.com/questions/353004",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178679/"
] | I have a problem after migrating a WordPress site from Plesk and IIS to LAMP server.
I cannot access the Admin Panel, I can access `/wp-admin/` and can login successfully but I get redirected to the home page and not to Admin Page.
If I set `define('WP_DEBUG', true)` in `wp-config.php` file I get this error:
>
> Notice: Use of undefined constant \_COOKIE - assumed '\_COOKIE' in public\_html/wp-content/themes/Avada/includes/fusion-functions.php on line 390
> Sorry, you are not allowed to access this page.
>
>
>
This line has the following code:
```
if (!current_user_can('read') && !isset(${_COOKIE}['wp_min'])) {
```
I have manually added `.htaccess` file during migration and its content is:
```
#BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
**UPDATE**
PHP version is 7.0.27 and used to be 5.4.
I have already tried:
* Renamed plugins folder
* Changed to default theme (my editing database entry in table options)
* Changed keys in `wp-config.php`
* Added to `wp-config.php` file
```
define(‘ADMIN_COOKIE_PATH’, ‘/’);
define(‘COOKIE_DOMAIN’, ”);
define(‘COOKIEPATH’, ”);
define(‘SITECOOKIEPATH’, ”);
```
None of these has helped. I still cannot access the Admin Panel. Error remains the same. | I discovered that there was an extra '-' character just above the line that caused the error. It was hard to see in my editor (and maybe because of some dust on the screen).
The syntax checker in my editor (Rapid PHP 2018) didn't sense that error Only by looking very close did I find the extra character. Removing that fixed the problem.
The lesson learned (again) is that sometimes the reported error line is not the problem. Errors can also be caused by statements previous to the reported line.
But thanks for the assistance; learned something from them also. So, net 'win'...although very frustrating to figure it out. |
353,068 | <p>I tried to find with this select statement.</p>
<pre><code>SELECT * FROM `wp_options` WHERE 'option_name' LIKE '%core_update%'
</code></pre>
<p>Zero lines result.</p>
<p>What can I do beside update by hand. I only want to use the update button instead.</p>
<p>Thanks in advance.
Hans</p>
| [
{
"answer_id": 352982,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 1,
"selected": false,
"text": "<p>From your comment:</p>\n\n<blockquote>\n <p>Those <code>htaccess</code> changes don't happen as a result of an <code>add_action</code>.\n Perhaps they should?</p>\n</blockquote>\n\n<p><strong>Yes, they should.</strong></p>\n\n<h2>And here's why</h2>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/insert_with_markers/\" rel=\"nofollow noreferrer\"><code>insert_with_markers()</code></a> calls <a href=\"https://developer.wordpress.org/reference/functions/switch_to_locale/\" rel=\"nofollow noreferrer\"><code>switch_to_locale()</code></a> which uses <code>$GLOBALS['wp_locale_switcher']</code> (or <code>$wp_locale_switcher</code>) which is initialized in <code>wp-settings.php</code>, but only after WordPress runs the <a href=\"https://developer.wordpress.org/reference/hooks/setup_theme/\" rel=\"nofollow noreferrer\"><code>setup_theme</code></a> hook.</p>\n\n<p>And looking at the error in question and <a href=\"https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/l10n.php#L1582\" rel=\"nofollow noreferrer\">line #1582</a> in <code>wp-includes/l10n.php</code> which is <code>return $wp_locale_switcher->switch_to_locale( $locale );</code>, that error occurred most likely because the global variable <code>$wp_locale_switcher</code> has not yet been defined or initialized. Which indicates that you called <code>insert_with_markers()</code> too early.</p>\n\n<p>So if you want to use <code>insert_with_markers()</code>, make sure you use the proper hook; for example, <a href=\"https://developer.wordpress.org/reference/hooks/load-page_hook/\" rel=\"nofollow noreferrer\"><code>load-{$page_hook}</code></a> or <a href=\"https://developer.wordpress.org/reference/hooks/update_option_option/\" rel=\"nofollow noreferrer\"><code>update_option_{$option}</code></a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Example 1:\nadd_action( 'admin_menu', function () {\n $hookname = add_menu_page( ... );\n add_action( 'load-' . $hookname, function () {\n // Call insert_with_markers()\n } );\n} );\n\n// Example 2:\nadd_action( 'update_option_my_field', function ( $old_value, $value ) {\n // Call insert_with_markers()\n}, 10, 2 );\n</code></pre>\n\n<p>Both tried & tested working on WordPress 5.2.4 and 5.3.</p>\n\n<p><em>But it's also possible there's a plugin or custom code which is messing with <code>$wp_locale_switcher</code>, so if using a hook later than <code>setup_theme</code> doesn't work for you, you can try deactivating plugins..</em></p>\n"
},
{
"answer_id": 353679,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": true,
"text": "<p>I discovered that there was an extra '-' character just above the line that caused the error. It was hard to see in my editor (and maybe because of some dust on the screen).</p>\n\n<p>The syntax checker in my editor (Rapid PHP 2018) didn't sense that error Only by looking very close did I find the extra character. Removing that fixed the problem.</p>\n\n<p>The lesson learned (again) is that sometimes the reported error line is not the problem. Errors can also be caused by statements previous to the reported line.</p>\n\n<p>But thanks for the assistance; learned something from them also. So, net 'win'...although very frustrating to figure it out.</p>\n"
}
] | 2019/11/21 | [
"https://wordpress.stackexchange.com/questions/353068",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178720/"
] | I tried to find with this select statement.
```
SELECT * FROM `wp_options` WHERE 'option_name' LIKE '%core_update%'
```
Zero lines result.
What can I do beside update by hand. I only want to use the update button instead.
Thanks in advance.
Hans | I discovered that there was an extra '-' character just above the line that caused the error. It was hard to see in my editor (and maybe because of some dust on the screen).
The syntax checker in my editor (Rapid PHP 2018) didn't sense that error Only by looking very close did I find the extra character. Removing that fixed the problem.
The lesson learned (again) is that sometimes the reported error line is not the problem. Errors can also be caused by statements previous to the reported line.
But thanks for the assistance; learned something from them also. So, net 'win'...although very frustrating to figure it out. |
353,090 | <p>I need to output some posts on some pages and I created shortcode:</p>
<pre><code>function show_foo() {
// output stuff
}
add_shortcode( 'foo', 'show_foo' );
</code></pre>
<p>and I use it like this in templates:</p>
<pre><code>echo do_shortcode('[foo]');
</code></pre>
<p>But now I'm thinking if I shouldn't use action in favor of shortcode, like this:</p>
<pre><code>function show_foo() {
// output stuff
}
add_action( 'foo', 'show_foo' );
</code></pre>
<p>and in templates use it like this:</p>
<pre><code>do_action('foo');
</code></pre>
<p>What are the cons and pros of these two methods? Do I understand it right that shortcodes should be used only when you need to add attributes to your output like this?</p>
<pre><code>echo do_shortcode([foo param_1="bar" param_2="foobar"]);
</code></pre>
<p>And in cases that you need to let the user to put the output of the function into the wysiwyg editor because they don't have access to the templates?</p>
| [
{
"answer_id": 352982,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 1,
"selected": false,
"text": "<p>From your comment:</p>\n\n<blockquote>\n <p>Those <code>htaccess</code> changes don't happen as a result of an <code>add_action</code>.\n Perhaps they should?</p>\n</blockquote>\n\n<p><strong>Yes, they should.</strong></p>\n\n<h2>And here's why</h2>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/insert_with_markers/\" rel=\"nofollow noreferrer\"><code>insert_with_markers()</code></a> calls <a href=\"https://developer.wordpress.org/reference/functions/switch_to_locale/\" rel=\"nofollow noreferrer\"><code>switch_to_locale()</code></a> which uses <code>$GLOBALS['wp_locale_switcher']</code> (or <code>$wp_locale_switcher</code>) which is initialized in <code>wp-settings.php</code>, but only after WordPress runs the <a href=\"https://developer.wordpress.org/reference/hooks/setup_theme/\" rel=\"nofollow noreferrer\"><code>setup_theme</code></a> hook.</p>\n\n<p>And looking at the error in question and <a href=\"https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/l10n.php#L1582\" rel=\"nofollow noreferrer\">line #1582</a> in <code>wp-includes/l10n.php</code> which is <code>return $wp_locale_switcher->switch_to_locale( $locale );</code>, that error occurred most likely because the global variable <code>$wp_locale_switcher</code> has not yet been defined or initialized. Which indicates that you called <code>insert_with_markers()</code> too early.</p>\n\n<p>So if you want to use <code>insert_with_markers()</code>, make sure you use the proper hook; for example, <a href=\"https://developer.wordpress.org/reference/hooks/load-page_hook/\" rel=\"nofollow noreferrer\"><code>load-{$page_hook}</code></a> or <a href=\"https://developer.wordpress.org/reference/hooks/update_option_option/\" rel=\"nofollow noreferrer\"><code>update_option_{$option}</code></a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Example 1:\nadd_action( 'admin_menu', function () {\n $hookname = add_menu_page( ... );\n add_action( 'load-' . $hookname, function () {\n // Call insert_with_markers()\n } );\n} );\n\n// Example 2:\nadd_action( 'update_option_my_field', function ( $old_value, $value ) {\n // Call insert_with_markers()\n}, 10, 2 );\n</code></pre>\n\n<p>Both tried & tested working on WordPress 5.2.4 and 5.3.</p>\n\n<p><em>But it's also possible there's a plugin or custom code which is messing with <code>$wp_locale_switcher</code>, so if using a hook later than <code>setup_theme</code> doesn't work for you, you can try deactivating plugins..</em></p>\n"
},
{
"answer_id": 353679,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": true,
"text": "<p>I discovered that there was an extra '-' character just above the line that caused the error. It was hard to see in my editor (and maybe because of some dust on the screen).</p>\n\n<p>The syntax checker in my editor (Rapid PHP 2018) didn't sense that error Only by looking very close did I find the extra character. Removing that fixed the problem.</p>\n\n<p>The lesson learned (again) is that sometimes the reported error line is not the problem. Errors can also be caused by statements previous to the reported line.</p>\n\n<p>But thanks for the assistance; learned something from them also. So, net 'win'...although very frustrating to figure it out.</p>\n"
}
] | 2019/11/22 | [
"https://wordpress.stackexchange.com/questions/353090",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119679/"
] | I need to output some posts on some pages and I created shortcode:
```
function show_foo() {
// output stuff
}
add_shortcode( 'foo', 'show_foo' );
```
and I use it like this in templates:
```
echo do_shortcode('[foo]');
```
But now I'm thinking if I shouldn't use action in favor of shortcode, like this:
```
function show_foo() {
// output stuff
}
add_action( 'foo', 'show_foo' );
```
and in templates use it like this:
```
do_action('foo');
```
What are the cons and pros of these two methods? Do I understand it right that shortcodes should be used only when you need to add attributes to your output like this?
```
echo do_shortcode([foo param_1="bar" param_2="foobar"]);
```
And in cases that you need to let the user to put the output of the function into the wysiwyg editor because they don't have access to the templates? | I discovered that there was an extra '-' character just above the line that caused the error. It was hard to see in my editor (and maybe because of some dust on the screen).
The syntax checker in my editor (Rapid PHP 2018) didn't sense that error Only by looking very close did I find the extra character. Removing that fixed the problem.
The lesson learned (again) is that sometimes the reported error line is not the problem. Errors can also be caused by statements previous to the reported line.
But thanks for the assistance; learned something from them also. So, net 'win'...although very frustrating to figure it out. |
353,126 | <p>I have an up-to-date Wordpress install, and I've tried to do due diligence when it comes to security. However I'm having a recurring problem.</p>
<p>I've put my config at the level above my install location.</p>
<p>However every so often something writes a new <code>wp-config.php</code> to the install location, filled with someone's details.</p>
<p>I've analysed my Apache access logs and I'm seeing this:</p>
<pre><code>[IP removed] - - [22/Nov/2019:17:45:06 +0100] "POST /wordpress//wp-admin/setup-config.php?step=2 HTTP/1.1" 200 1116 "-" "python-requests/2.9.1"
[IP removed] - - [22/Nov/2019:17:45:09 +0100] "POST /wordpress//wp-admin/install.php?step=2 HTTP/1.1" 302 368 "-" "python-requests/2.9.1"
[IP removed] - - [22/Nov/2019:17:45:09 +0100] "GET /wordpress/wp-admin/setup-config.php HTTP/1.1" 200 1487 "-" "python-requests/2.9.1"
[IP removed] - - [22/Nov/2019:17:45:10 +0100] "GET /wordpress//wp-login.php HTTP/1.1" 302 332 "-" "Python-urllib/2.7"
[IP removed] - - [22/Nov/2019:17:45:11 +0100] "GET /wordpress/wp-admin/setup-config.php HTTP/1.1" 200 2791 "-" "Python-urllib/2.7"
</code></pre>
<p>I don't know for sure but I suspect that whatever they've managed to POST to the install stage has resulted in Wordpress creating a new config. This doesn't appear to achieve anything tangible for the attacker since they don't have valid credentials, a database or ability to create one, etc etc, but it does put in place a config that breaks the site, directing all access to the installer page.</p>
<p>The config produced is along the lines of this:</p>
<pre><code><?php
/**
* The base configuration for WordPress
*
* The wp-config.php creation script uses this file during the
* installation. You don't have to use the web site, you can
* copy this file to "wp-config.php" and fill in the values.
*
* This file contains the following configurations:
*
* * MySQL settings
* * Secret keys
* * Database table prefix
* * ABSPATH
*
* @link https://codex.wordpress.org/Editing_wp-config.php
*
* @package WordPress
*/
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define( 'DB_NAME', '[removed]' );
/** MySQL database username */
define( 'DB_USER', '[removed]' );
/** MySQL database password */
define( 'DB_PASSWORD', '[removed]' );
/** MySQL hostname */
define( 'DB_HOST', 'remotemysql.com' );
[snipped]
</code></pre>
<p>I can probably prevent reoccurrence by setting up rules to forbid access to the installer, but surely WP shouldn't be allowing this, and I can't find anything else on the subject.</p>
<p>Am I missing anything in terms of either how this is happening, or what might have been gained as a result?</p>
<p><strong>Edit:</strong> it seems like this needs some clarification. I believe that this is WP being induced to write a new config file to the main directory, as it would do if being newly installed. It is <em>not</em> modification of my config at the higher level. It does <em>not</em> appear to be a broader level of compromise.</p>
<p>As the site is non-critical at present, I've started logging request details (POST params etc) to the filesystem and we'll see what I get next time this happens, which is roughly daily.</p>
| [
{
"answer_id": 353135,
"author": "C0c0b33f",
"author_id": 173627,
"author_profile": "https://wordpress.stackexchange.com/users/173627",
"pm_score": 0,
"selected": false,
"text": "<p>You can move your config file up one directory and should check the file permissions to only allow you, the owner to edit it. If you have access to your .htaccess file, you can add the following to it to prevent access.</p>\n\n<pre><code># protect wpconfig.php \n<files wp-config.php> \n order allow,deny \n deny from all \n</files>\n</code></pre>\n\n<p><a href=\"https://wordpress.org/support/topic/permission-for-wp-config-php/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/topic/permission-for-wp-config-php/</a>\n<a href=\"https://www.webhostinghero.com/how-to-protect-your-wp-config-php-file-in-wordpress/\" rel=\"nofollow noreferrer\">https://www.webhostinghero.com/how-to-protect-your-wp-config-php-file-in-wordpress/</a>\n<a href=\"https://www.malcare.com/blog/how-to-secure-your-wordpress-site-with-wp-config-php/\" rel=\"nofollow noreferrer\">https://www.malcare.com/blog/how-to-secure-your-wordpress-site-with-wp-config-php/</a></p>\n"
},
{
"answer_id": 353136,
"author": "Khairul Alam",
"author_id": 91468,
"author_profile": "https://wordpress.stackexchange.com/users/91468",
"pm_score": 1,
"selected": false,
"text": "<p>I would do the following things -</p>\n\n<p>1) Check if any malicious content lives on the site. You can use free tools like - <a href=\"https://sitecheck.sucuri.net/\" rel=\"nofollow noreferrer\">https://sitecheck.sucuri.net/</a></p>\n\n<p>2) Change folder permission of your Wordpress installation to 755 if it's not set to that already. Also change the wp-config.php file permission to 755 to be on the safe side. </p>\n\n<p>3) You can also try to protect wp-config.php file by using the following rule in your .htaccess file. You have to put it at the bottom of the file; after all other rules</p>\n\n<pre><code><files wp-config.php>\norder allow,deny\ndeny from all\n</files>\n</code></pre>\n"
},
{
"answer_id": 353144,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>I've had a similar problem with a client that has multiple WP and non-WP installation on a shared server. The wp-config file gets some inserted code, and random PHP files are placed, along with inserted code in various (and added) index.php.</p>\n\n<p>I have reset all credentials (hosting, database, admin, etc) with very strong passwords. I have changed permissions on the files (some of the changed files have 'execute' added) to no avail. And the dates of the files don't change when they are modified, so harder to sense.</p>\n\n<p>I've written a file hash checker that compares all file's hashes in a separate table. That alerts me to the problem reoccuring, but I haven't found the infection point yet. And I've looked at just about all of the usual suspects. (Since I haven't found the culprit yet, I obviously haven't looked at the 'right' suspect yet.)</p>\n\n<p>And I have installed two different security plugins on all WP sites; still being attacked. (Luckily, the attack inserts code that doesn't work properly, since the inserted code depends on a specific value in the wp-options table. But it is irritating....) And protected the wp-config file with an htaccess rule; that didn't block it either.</p>\n\n<p>I have noticed that the wp-posts table has some inserted records, so you might look there. I haven't seen anything in the wp-options table yet.</p>\n\n<p>So, looking at every php file for inserted code; look for files with the 'execute' permission set; changing all credentials (hosting, ftp, database, master database, admin); looking for hidden users in wp-users table; look for modified plugins (delete manually and reinstall, which will hopefully save settings); same with themes; and hashing everything are some ideas.</p>\n\n<p>But will be following this, as I haven't got a full solution to either of our problems, but hoping my experiences will help.</p>\n\n<p><strong>Added</strong></p>\n\n<p>I found this resource, which may give you additional protection ideas: <a href=\"https://www.owasp.org/index.php/OWASP_Wordpress_Security_Implementation_Guideline\" rel=\"nofollow noreferrer\">https://www.owasp.org/index.php/OWASP_Wordpress_Security_Implementation_Guideline</a> . Many of the suggestions there might be appropriate. YMMV.</p>\n\n<p>And you might consider removing the install.php file - it is not needed after installation. Not sure if it is put back on a WP version update.</p>\n"
},
{
"answer_id": 353148,
"author": "John Dee",
"author_id": 131224,
"author_profile": "https://wordpress.stackexchange.com/users/131224",
"pm_score": 0,
"selected": false,
"text": "<p>Scrub the site and restore from backup.</p>\n\n<p><strong>If an attacker can write PHP code, you're system is 100% compromised and needs to be scrubbed.</strong> You cannot verify that the attack is over. You cannot figure out what is useful to the attackers or how they do it. They can execute <em>arbitrary code</em>. In other words, you don't own that instance anymore - they do. You still own the domain and hopefully you have access to your data. You should backup your data, and re-install the site to a new server.</p>\n\n<p>A great way to do this is use any basic backup system, but not a FULL backup system. For instance, doing an XML export will lose your monkey, but doing a backup with something like \"Duplicator\" will simply carry the infection to the new instance.</p>\n"
},
{
"answer_id": 353181,
"author": "Rob Pridham",
"author_id": 178765,
"author_profile": "https://wordpress.stackexchange.com/users/178765",
"pm_score": 1,
"selected": true,
"text": "<p>This turned out to be really, really stupid.</p>\n\n<p>Due to a mistake in the original commissioning process, there was a copy of the Wordpress install within the site, i.e. <code>/wordpress</code>, never set up. This is the sort of thing that would happen if you unpacked the install to the wrong level and then copied it upwards rather than moving it.</p>\n\n<p>In retrospect, the logs were clearly referring to this as the request, but I missed it, thinking that it was filesystem-relative.</p>\n\n<p>The attack speculatively hit this other install with a set of installation parameters, which then produced a config at the level above. This broke the proper site. However, fortunately, subsequent attempts to access the bad site also failed, because for whatever reason it produces a redirect loop. Therefore nothing was achieved.</p>\n"
}
] | 2019/11/22 | [
"https://wordpress.stackexchange.com/questions/353126",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178765/"
] | I have an up-to-date Wordpress install, and I've tried to do due diligence when it comes to security. However I'm having a recurring problem.
I've put my config at the level above my install location.
However every so often something writes a new `wp-config.php` to the install location, filled with someone's details.
I've analysed my Apache access logs and I'm seeing this:
```
[IP removed] - - [22/Nov/2019:17:45:06 +0100] "POST /wordpress//wp-admin/setup-config.php?step=2 HTTP/1.1" 200 1116 "-" "python-requests/2.9.1"
[IP removed] - - [22/Nov/2019:17:45:09 +0100] "POST /wordpress//wp-admin/install.php?step=2 HTTP/1.1" 302 368 "-" "python-requests/2.9.1"
[IP removed] - - [22/Nov/2019:17:45:09 +0100] "GET /wordpress/wp-admin/setup-config.php HTTP/1.1" 200 1487 "-" "python-requests/2.9.1"
[IP removed] - - [22/Nov/2019:17:45:10 +0100] "GET /wordpress//wp-login.php HTTP/1.1" 302 332 "-" "Python-urllib/2.7"
[IP removed] - - [22/Nov/2019:17:45:11 +0100] "GET /wordpress/wp-admin/setup-config.php HTTP/1.1" 200 2791 "-" "Python-urllib/2.7"
```
I don't know for sure but I suspect that whatever they've managed to POST to the install stage has resulted in Wordpress creating a new config. This doesn't appear to achieve anything tangible for the attacker since they don't have valid credentials, a database or ability to create one, etc etc, but it does put in place a config that breaks the site, directing all access to the installer page.
The config produced is along the lines of this:
```
<?php
/**
* The base configuration for WordPress
*
* The wp-config.php creation script uses this file during the
* installation. You don't have to use the web site, you can
* copy this file to "wp-config.php" and fill in the values.
*
* This file contains the following configurations:
*
* * MySQL settings
* * Secret keys
* * Database table prefix
* * ABSPATH
*
* @link https://codex.wordpress.org/Editing_wp-config.php
*
* @package WordPress
*/
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define( 'DB_NAME', '[removed]' );
/** MySQL database username */
define( 'DB_USER', '[removed]' );
/** MySQL database password */
define( 'DB_PASSWORD', '[removed]' );
/** MySQL hostname */
define( 'DB_HOST', 'remotemysql.com' );
[snipped]
```
I can probably prevent reoccurrence by setting up rules to forbid access to the installer, but surely WP shouldn't be allowing this, and I can't find anything else on the subject.
Am I missing anything in terms of either how this is happening, or what might have been gained as a result?
**Edit:** it seems like this needs some clarification. I believe that this is WP being induced to write a new config file to the main directory, as it would do if being newly installed. It is *not* modification of my config at the higher level. It does *not* appear to be a broader level of compromise.
As the site is non-critical at present, I've started logging request details (POST params etc) to the filesystem and we'll see what I get next time this happens, which is roughly daily. | This turned out to be really, really stupid.
Due to a mistake in the original commissioning process, there was a copy of the Wordpress install within the site, i.e. `/wordpress`, never set up. This is the sort of thing that would happen if you unpacked the install to the wrong level and then copied it upwards rather than moving it.
In retrospect, the logs were clearly referring to this as the request, but I missed it, thinking that it was filesystem-relative.
The attack speculatively hit this other install with a set of installation parameters, which then produced a config at the level above. This broke the proper site. However, fortunately, subsequent attempts to access the bad site also failed, because for whatever reason it produces a redirect loop. Therefore nothing was achieved. |
353,129 | <p>So, I am creating a shortcode to return some ACF content.</p>
<p>The following code works:</p>
<pre><code>function howitworks() {
$page = get_page_by_title('shop');
if (have_rows('steps', $page->ID)) :
while (have_rows('steps', $page->ID)) : the_row();
$image = get_sub_field('icon');
$i = '<div class="col">
<img src="'.$image['sizes']['thumbnail'].'" alt="'.$image['alt'].'" title="'.$image['alt'].'" />
<h2>'.the_sub_field('step').'</h2>
<p>'.the_sub_field('description').'</p>
</div>';
endwhile;
endif;
return $i;
}
add_shortcode('howitworks', 'howitworks');
</code></pre>
<p>The problem I am having is I'd like to add a div container in-between the <code>if</code> and the <code>while</code>. I have tried multiple ways. I tried another variable like <code>$j = '<div class="test">'</code> then added another return <code>return $i, $j</code>...but then I have a syntax error. If I add a semi-colon the error goes away, but the div doesn't get returned. If I wanted the div inside the while, I'd be fine. But it seems like I'm having issues because I'm trying to put it outside the while.</p>
<p>The other thing I tried was just to return the outer div like: <code>return '<div class="test">';</code> which will return the div, but then my original return doesn't return anything.</p>
<p>Any ideas?</p>
<p>Thanks,<br />
Josh</p>
| [
{
"answer_id": 353135,
"author": "C0c0b33f",
"author_id": 173627,
"author_profile": "https://wordpress.stackexchange.com/users/173627",
"pm_score": 0,
"selected": false,
"text": "<p>You can move your config file up one directory and should check the file permissions to only allow you, the owner to edit it. If you have access to your .htaccess file, you can add the following to it to prevent access.</p>\n\n<pre><code># protect wpconfig.php \n<files wp-config.php> \n order allow,deny \n deny from all \n</files>\n</code></pre>\n\n<p><a href=\"https://wordpress.org/support/topic/permission-for-wp-config-php/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/topic/permission-for-wp-config-php/</a>\n<a href=\"https://www.webhostinghero.com/how-to-protect-your-wp-config-php-file-in-wordpress/\" rel=\"nofollow noreferrer\">https://www.webhostinghero.com/how-to-protect-your-wp-config-php-file-in-wordpress/</a>\n<a href=\"https://www.malcare.com/blog/how-to-secure-your-wordpress-site-with-wp-config-php/\" rel=\"nofollow noreferrer\">https://www.malcare.com/blog/how-to-secure-your-wordpress-site-with-wp-config-php/</a></p>\n"
},
{
"answer_id": 353136,
"author": "Khairul Alam",
"author_id": 91468,
"author_profile": "https://wordpress.stackexchange.com/users/91468",
"pm_score": 1,
"selected": false,
"text": "<p>I would do the following things -</p>\n\n<p>1) Check if any malicious content lives on the site. You can use free tools like - <a href=\"https://sitecheck.sucuri.net/\" rel=\"nofollow noreferrer\">https://sitecheck.sucuri.net/</a></p>\n\n<p>2) Change folder permission of your Wordpress installation to 755 if it's not set to that already. Also change the wp-config.php file permission to 755 to be on the safe side. </p>\n\n<p>3) You can also try to protect wp-config.php file by using the following rule in your .htaccess file. You have to put it at the bottom of the file; after all other rules</p>\n\n<pre><code><files wp-config.php>\norder allow,deny\ndeny from all\n</files>\n</code></pre>\n"
},
{
"answer_id": 353144,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>I've had a similar problem with a client that has multiple WP and non-WP installation on a shared server. The wp-config file gets some inserted code, and random PHP files are placed, along with inserted code in various (and added) index.php.</p>\n\n<p>I have reset all credentials (hosting, database, admin, etc) with very strong passwords. I have changed permissions on the files (some of the changed files have 'execute' added) to no avail. And the dates of the files don't change when they are modified, so harder to sense.</p>\n\n<p>I've written a file hash checker that compares all file's hashes in a separate table. That alerts me to the problem reoccuring, but I haven't found the infection point yet. And I've looked at just about all of the usual suspects. (Since I haven't found the culprit yet, I obviously haven't looked at the 'right' suspect yet.)</p>\n\n<p>And I have installed two different security plugins on all WP sites; still being attacked. (Luckily, the attack inserts code that doesn't work properly, since the inserted code depends on a specific value in the wp-options table. But it is irritating....) And protected the wp-config file with an htaccess rule; that didn't block it either.</p>\n\n<p>I have noticed that the wp-posts table has some inserted records, so you might look there. I haven't seen anything in the wp-options table yet.</p>\n\n<p>So, looking at every php file for inserted code; look for files with the 'execute' permission set; changing all credentials (hosting, ftp, database, master database, admin); looking for hidden users in wp-users table; look for modified plugins (delete manually and reinstall, which will hopefully save settings); same with themes; and hashing everything are some ideas.</p>\n\n<p>But will be following this, as I haven't got a full solution to either of our problems, but hoping my experiences will help.</p>\n\n<p><strong>Added</strong></p>\n\n<p>I found this resource, which may give you additional protection ideas: <a href=\"https://www.owasp.org/index.php/OWASP_Wordpress_Security_Implementation_Guideline\" rel=\"nofollow noreferrer\">https://www.owasp.org/index.php/OWASP_Wordpress_Security_Implementation_Guideline</a> . Many of the suggestions there might be appropriate. YMMV.</p>\n\n<p>And you might consider removing the install.php file - it is not needed after installation. Not sure if it is put back on a WP version update.</p>\n"
},
{
"answer_id": 353148,
"author": "John Dee",
"author_id": 131224,
"author_profile": "https://wordpress.stackexchange.com/users/131224",
"pm_score": 0,
"selected": false,
"text": "<p>Scrub the site and restore from backup.</p>\n\n<p><strong>If an attacker can write PHP code, you're system is 100% compromised and needs to be scrubbed.</strong> You cannot verify that the attack is over. You cannot figure out what is useful to the attackers or how they do it. They can execute <em>arbitrary code</em>. In other words, you don't own that instance anymore - they do. You still own the domain and hopefully you have access to your data. You should backup your data, and re-install the site to a new server.</p>\n\n<p>A great way to do this is use any basic backup system, but not a FULL backup system. For instance, doing an XML export will lose your monkey, but doing a backup with something like \"Duplicator\" will simply carry the infection to the new instance.</p>\n"
},
{
"answer_id": 353181,
"author": "Rob Pridham",
"author_id": 178765,
"author_profile": "https://wordpress.stackexchange.com/users/178765",
"pm_score": 1,
"selected": true,
"text": "<p>This turned out to be really, really stupid.</p>\n\n<p>Due to a mistake in the original commissioning process, there was a copy of the Wordpress install within the site, i.e. <code>/wordpress</code>, never set up. This is the sort of thing that would happen if you unpacked the install to the wrong level and then copied it upwards rather than moving it.</p>\n\n<p>In retrospect, the logs were clearly referring to this as the request, but I missed it, thinking that it was filesystem-relative.</p>\n\n<p>The attack speculatively hit this other install with a set of installation parameters, which then produced a config at the level above. This broke the proper site. However, fortunately, subsequent attempts to access the bad site also failed, because for whatever reason it produces a redirect loop. Therefore nothing was achieved.</p>\n"
}
] | 2019/11/22 | [
"https://wordpress.stackexchange.com/questions/353129",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9820/"
] | So, I am creating a shortcode to return some ACF content.
The following code works:
```
function howitworks() {
$page = get_page_by_title('shop');
if (have_rows('steps', $page->ID)) :
while (have_rows('steps', $page->ID)) : the_row();
$image = get_sub_field('icon');
$i = '<div class="col">
<img src="'.$image['sizes']['thumbnail'].'" alt="'.$image['alt'].'" title="'.$image['alt'].'" />
<h2>'.the_sub_field('step').'</h2>
<p>'.the_sub_field('description').'</p>
</div>';
endwhile;
endif;
return $i;
}
add_shortcode('howitworks', 'howitworks');
```
The problem I am having is I'd like to add a div container in-between the `if` and the `while`. I have tried multiple ways. I tried another variable like `$j = '<div class="test">'` then added another return `return $i, $j`...but then I have a syntax error. If I add a semi-colon the error goes away, but the div doesn't get returned. If I wanted the div inside the while, I'd be fine. But it seems like I'm having issues because I'm trying to put it outside the while.
The other thing I tried was just to return the outer div like: `return '<div class="test">';` which will return the div, but then my original return doesn't return anything.
Any ideas?
Thanks,
Josh | This turned out to be really, really stupid.
Due to a mistake in the original commissioning process, there was a copy of the Wordpress install within the site, i.e. `/wordpress`, never set up. This is the sort of thing that would happen if you unpacked the install to the wrong level and then copied it upwards rather than moving it.
In retrospect, the logs were clearly referring to this as the request, but I missed it, thinking that it was filesystem-relative.
The attack speculatively hit this other install with a set of installation parameters, which then produced a config at the level above. This broke the proper site. However, fortunately, subsequent attempts to access the bad site also failed, because for whatever reason it produces a redirect loop. Therefore nothing was achieved. |
353,137 | <p>I'm trying to set notifications when I have products from these two different categories inside the card in <code>WooCommerce</code>.</p>
<p>This is the code which I using:</p>
<pre><code>add_action( 'woocommerce_checkout_before_customer_details', 'webroom_check_if_product_category_is_in_cart' );
function webroom_check_if_product_category_is_in_cart() {
$cat_in_cart = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( has_term( 'cat1', 'product_cat', $cart_item['product_id'] ) &&
has_term( 'cat2', 'product_cat', $cart_item['product_id'] ) ) {
$cat_in_cart = true;
break;
}
}
if ( $cat_in_cart ) {
$notice = 'Notification';
wc_print_notice($notice, 'notice');
}
}
</code></pre>
<p>This code works perfectly if I only set one category, but when I set two categories, for some reason I don't have results nor errors.</p>
| [
{
"answer_id": 353135,
"author": "C0c0b33f",
"author_id": 173627,
"author_profile": "https://wordpress.stackexchange.com/users/173627",
"pm_score": 0,
"selected": false,
"text": "<p>You can move your config file up one directory and should check the file permissions to only allow you, the owner to edit it. If you have access to your .htaccess file, you can add the following to it to prevent access.</p>\n\n<pre><code># protect wpconfig.php \n<files wp-config.php> \n order allow,deny \n deny from all \n</files>\n</code></pre>\n\n<p><a href=\"https://wordpress.org/support/topic/permission-for-wp-config-php/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/topic/permission-for-wp-config-php/</a>\n<a href=\"https://www.webhostinghero.com/how-to-protect-your-wp-config-php-file-in-wordpress/\" rel=\"nofollow noreferrer\">https://www.webhostinghero.com/how-to-protect-your-wp-config-php-file-in-wordpress/</a>\n<a href=\"https://www.malcare.com/blog/how-to-secure-your-wordpress-site-with-wp-config-php/\" rel=\"nofollow noreferrer\">https://www.malcare.com/blog/how-to-secure-your-wordpress-site-with-wp-config-php/</a></p>\n"
},
{
"answer_id": 353136,
"author": "Khairul Alam",
"author_id": 91468,
"author_profile": "https://wordpress.stackexchange.com/users/91468",
"pm_score": 1,
"selected": false,
"text": "<p>I would do the following things -</p>\n\n<p>1) Check if any malicious content lives on the site. You can use free tools like - <a href=\"https://sitecheck.sucuri.net/\" rel=\"nofollow noreferrer\">https://sitecheck.sucuri.net/</a></p>\n\n<p>2) Change folder permission of your Wordpress installation to 755 if it's not set to that already. Also change the wp-config.php file permission to 755 to be on the safe side. </p>\n\n<p>3) You can also try to protect wp-config.php file by using the following rule in your .htaccess file. You have to put it at the bottom of the file; after all other rules</p>\n\n<pre><code><files wp-config.php>\norder allow,deny\ndeny from all\n</files>\n</code></pre>\n"
},
{
"answer_id": 353144,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>I've had a similar problem with a client that has multiple WP and non-WP installation on a shared server. The wp-config file gets some inserted code, and random PHP files are placed, along with inserted code in various (and added) index.php.</p>\n\n<p>I have reset all credentials (hosting, database, admin, etc) with very strong passwords. I have changed permissions on the files (some of the changed files have 'execute' added) to no avail. And the dates of the files don't change when they are modified, so harder to sense.</p>\n\n<p>I've written a file hash checker that compares all file's hashes in a separate table. That alerts me to the problem reoccuring, but I haven't found the infection point yet. And I've looked at just about all of the usual suspects. (Since I haven't found the culprit yet, I obviously haven't looked at the 'right' suspect yet.)</p>\n\n<p>And I have installed two different security plugins on all WP sites; still being attacked. (Luckily, the attack inserts code that doesn't work properly, since the inserted code depends on a specific value in the wp-options table. But it is irritating....) And protected the wp-config file with an htaccess rule; that didn't block it either.</p>\n\n<p>I have noticed that the wp-posts table has some inserted records, so you might look there. I haven't seen anything in the wp-options table yet.</p>\n\n<p>So, looking at every php file for inserted code; look for files with the 'execute' permission set; changing all credentials (hosting, ftp, database, master database, admin); looking for hidden users in wp-users table; look for modified plugins (delete manually and reinstall, which will hopefully save settings); same with themes; and hashing everything are some ideas.</p>\n\n<p>But will be following this, as I haven't got a full solution to either of our problems, but hoping my experiences will help.</p>\n\n<p><strong>Added</strong></p>\n\n<p>I found this resource, which may give you additional protection ideas: <a href=\"https://www.owasp.org/index.php/OWASP_Wordpress_Security_Implementation_Guideline\" rel=\"nofollow noreferrer\">https://www.owasp.org/index.php/OWASP_Wordpress_Security_Implementation_Guideline</a> . Many of the suggestions there might be appropriate. YMMV.</p>\n\n<p>And you might consider removing the install.php file - it is not needed after installation. Not sure if it is put back on a WP version update.</p>\n"
},
{
"answer_id": 353148,
"author": "John Dee",
"author_id": 131224,
"author_profile": "https://wordpress.stackexchange.com/users/131224",
"pm_score": 0,
"selected": false,
"text": "<p>Scrub the site and restore from backup.</p>\n\n<p><strong>If an attacker can write PHP code, you're system is 100% compromised and needs to be scrubbed.</strong> You cannot verify that the attack is over. You cannot figure out what is useful to the attackers or how they do it. They can execute <em>arbitrary code</em>. In other words, you don't own that instance anymore - they do. You still own the domain and hopefully you have access to your data. You should backup your data, and re-install the site to a new server.</p>\n\n<p>A great way to do this is use any basic backup system, but not a FULL backup system. For instance, doing an XML export will lose your monkey, but doing a backup with something like \"Duplicator\" will simply carry the infection to the new instance.</p>\n"
},
{
"answer_id": 353181,
"author": "Rob Pridham",
"author_id": 178765,
"author_profile": "https://wordpress.stackexchange.com/users/178765",
"pm_score": 1,
"selected": true,
"text": "<p>This turned out to be really, really stupid.</p>\n\n<p>Due to a mistake in the original commissioning process, there was a copy of the Wordpress install within the site, i.e. <code>/wordpress</code>, never set up. This is the sort of thing that would happen if you unpacked the install to the wrong level and then copied it upwards rather than moving it.</p>\n\n<p>In retrospect, the logs were clearly referring to this as the request, but I missed it, thinking that it was filesystem-relative.</p>\n\n<p>The attack speculatively hit this other install with a set of installation parameters, which then produced a config at the level above. This broke the proper site. However, fortunately, subsequent attempts to access the bad site also failed, because for whatever reason it produces a redirect loop. Therefore nothing was achieved.</p>\n"
}
] | 2019/11/22 | [
"https://wordpress.stackexchange.com/questions/353137",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178581/"
] | I'm trying to set notifications when I have products from these two different categories inside the card in `WooCommerce`.
This is the code which I using:
```
add_action( 'woocommerce_checkout_before_customer_details', 'webroom_check_if_product_category_is_in_cart' );
function webroom_check_if_product_category_is_in_cart() {
$cat_in_cart = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( has_term( 'cat1', 'product_cat', $cart_item['product_id'] ) &&
has_term( 'cat2', 'product_cat', $cart_item['product_id'] ) ) {
$cat_in_cart = true;
break;
}
}
if ( $cat_in_cart ) {
$notice = 'Notification';
wc_print_notice($notice, 'notice');
}
}
```
This code works perfectly if I only set one category, but when I set two categories, for some reason I don't have results nor errors. | This turned out to be really, really stupid.
Due to a mistake in the original commissioning process, there was a copy of the Wordpress install within the site, i.e. `/wordpress`, never set up. This is the sort of thing that would happen if you unpacked the install to the wrong level and then copied it upwards rather than moving it.
In retrospect, the logs were clearly referring to this as the request, but I missed it, thinking that it was filesystem-relative.
The attack speculatively hit this other install with a set of installation parameters, which then produced a config at the level above. This broke the proper site. However, fortunately, subsequent attempts to access the bad site also failed, because for whatever reason it produces a redirect loop. Therefore nothing was achieved. |
353,165 | <p>Wordpress initial install. Version <code>5.3</code></p>
<blockquote>
<p>index.php</p>
</blockquote>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
test
</body>
</code></pre>
<p></p>
<blockquote>
<p>style.css</p>
</blockquote>
<pre><code>/*
Theme Name: Gerboni
Theme URI: http://linards-berzins.co.uk/
Author: Linards Bērziņš
Author URI: http://linards-berzins.co.uk/
Description: Woocommerce theme for online shop
Version: 1.0
Text-domain: gerboni
License: GNU General Public License v2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Tags: e-commerce, blog, custom-menu, custom-logo, featured-images,footer-widgets, theme-options, translation-ready, right-sidebar, sticky-post, threaded-comments
*/
</code></pre>
<p>Theme Appearance dashboard:
<a href="https://i.stack.imgur.com/hxX7a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hxX7a.png" alt="enter image description here"></a></p>
<p>Any advice appreciated. </p>
| [
{
"answer_id": 353503,
"author": "mrwpress",
"author_id": 115461,
"author_profile": "https://wordpress.stackexchange.com/users/115461",
"pm_score": 3,
"selected": true,
"text": "<p>The WC single item template is located at:</p>\n\n<p><code>yoursite.com/wp-content/plugins/woocommerce/templates/single-product.php</code></p>\n\n<p>See this documentation:</p>\n\n<p><a href=\"https://docs.woocommerce.com/document/template-structure/\" rel=\"nofollow noreferrer\">https://docs.woocommerce.com/document/template-structure/</a></p>\n\n<p>So, you would want to move any of those templates to your child theme under <code>/wp-content/themes/your-child-theme/woocommerce/[any_template_you_want]</code></p>\n\n<p>So, for example, if you wanted to edit the single-product.php but safe from WC updates, you would put the file in this directory and do your mods:</p>\n\n<p><code>www.yoursite.com/wp-content/themes/your_child_theme/woocommerce/single-product.php</code></p>\n\n<p>Last thing to mention here is keep the directory structure as well. So, if you want to edit something in the 'emails' folder, it would be like this:</p>\n\n<p><code>www.yoursite.com/wp-content/themes/your_child_theme/woocommerce/emails/admin-new-order.php</code> (just for example sake)</p>\n\n<p>So, copy any templates you want to modify using that documentation above and you will be safe from any updates over time.</p>\n"
},
{
"answer_id": 353562,
"author": "Khairul Alam",
"author_id": 91468,
"author_profile": "https://wordpress.stackexchange.com/users/91468",
"pm_score": 0,
"selected": false,
"text": "<p>Why would you need to edit the template for single item? Do you want to customize the template to change its look and feel? </p>\n\n<p>If not, this is how you add a single item to your website - </p>\n\n<ol>\n<li>Create a Product in Woocommerce</li>\n<li>Copy the product URL</li>\n<li>Go to Appearance > Menus </li>\n<li>Locate your Primary Menu (Assuming you want to put it there)</li>\n<li>Add a 'Custom Link' item to your menu. Paste the product URL in the 'URL' box.</li>\n<li>SAVE YOUR MENU.</li>\n</ol>\n\n<p>There you have it. A single product on your site linked directly from the MENU. </p>\n\n<p>IF YOU ARE STILL LOOKING FOR THE TEMPLATE THEN FOLLOW THE INSTRUCTIONS BELOW -</p>\n\n<ol>\n<li>Login to your Hosting account or FTP into it</li>\n<li>Go to public_html/wp-content/plugins/woocommerce/templates/single-product.php</li>\n</ol>\n\n<p>Note: Any change you make to this template will be overwritten whenever you update the Woocommerce plugin. So changes should be made through your theme's functions.php file. </p>\n"
}
] | 2019/11/23 | [
"https://wordpress.stackexchange.com/questions/353165",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34320/"
] | Wordpress initial install. Version `5.3`
>
> index.php
>
>
>
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
test
</body>
```
>
> style.css
>
>
>
```
/*
Theme Name: Gerboni
Theme URI: http://linards-berzins.co.uk/
Author: Linards Bērziņš
Author URI: http://linards-berzins.co.uk/
Description: Woocommerce theme for online shop
Version: 1.0
Text-domain: gerboni
License: GNU General Public License v2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Tags: e-commerce, blog, custom-menu, custom-logo, featured-images,footer-widgets, theme-options, translation-ready, right-sidebar, sticky-post, threaded-comments
*/
```
Theme Appearance dashboard:
[](https://i.stack.imgur.com/hxX7a.png)
Any advice appreciated. | The WC single item template is located at:
`yoursite.com/wp-content/plugins/woocommerce/templates/single-product.php`
See this documentation:
<https://docs.woocommerce.com/document/template-structure/>
So, you would want to move any of those templates to your child theme under `/wp-content/themes/your-child-theme/woocommerce/[any_template_you_want]`
So, for example, if you wanted to edit the single-product.php but safe from WC updates, you would put the file in this directory and do your mods:
`www.yoursite.com/wp-content/themes/your_child_theme/woocommerce/single-product.php`
Last thing to mention here is keep the directory structure as well. So, if you want to edit something in the 'emails' folder, it would be like this:
`www.yoursite.com/wp-content/themes/your_child_theme/woocommerce/emails/admin-new-order.php` (just for example sake)
So, copy any templates you want to modify using that documentation above and you will be safe from any updates over time. |
353,219 | <p>I've made a loop that goes over all the gigs I've attended, some gigs have the same songs.</p>
<p>Here is the result of that array:
<a href="http://snippi.com/s/k80v7pe" rel="nofollow noreferrer">http://snippi.com/s/k80v7pe</a></p>
<p>Now I want to have an array of all the distinct song id's. So want to see all the songs that I've ever heard:</p>
<pre><code>//get the songs field get_field('songs')
foreach ($postIds as $postId){
array_push($songIds, get_field('songs', $postId));
}
//Over here I'm trying to print all the ID's of the song
foreach ($songIds as $songId) {
echo $songId->ID;
}
</code></pre>
<p>But I'm getting the following error:</p>
<blockquote>
<p>Notice: Trying to get property 'ID' of non-object in</p>
</blockquote>
<p>Is that because of that the array <code>$songIds</code> has an array in an array?</p>
| [
{
"answer_id": 353223,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>No, that's because you are treating an <a href=\"https://www.php.net/manual/en/language.types.array.php\" rel=\"nofollow noreferrer\">array</a> as an <a href=\"https://www.php.net/manual/en/language.types.object.php\" rel=\"nofollow noreferrer\">object</a> and <code>PHP</code> doesn't convert those types automatically. To get an individual element from an object you use:</p>\n\n<pre><code>$my_object->Element1;\n</code></pre>\n\n<p>To get an individual element from an array you use:</p>\n\n<pre><code>$my_array[Element1];\n</code></pre>\n\n<p>You can even nest arrays. So if you have $my_array, where each element is another array, you can get elementX from arrayY like this:</p>\n\n<pre><code>$my_array[arrayY][elementX];\n</code></pre>\n\n<p>In your case, apparently, you have an array, which holds an array, which holds objects, amounting to:</p>\n\n<pre><code>$my_array[arrayY][elementX]->componentZ\n</code></pre>\n"
},
{
"answer_id": 353372,
"author": "Dennis",
"author_id": 178703,
"author_profile": "https://wordpress.stackexchange.com/users/178703",
"pm_score": 0,
"selected": false,
"text": "<p>Because <code>$songIds</code> is an array within an array, I have to do 2 loops within each other.</p>\n\n<p>The code below pushes all post id's from the different arrays in a new array <code>$allSongs</code>.</p>\n\n<p>This way I have an array with all the id's. Some id's will be duplicates because some songs are played more than 1 time over all the gigs.</p>\n\n<pre><code>foreach ($songIds as $songId) {\n foreach ($songId as $key => $value) {\n array_push($allSongs, $value->ID);\n }\n}\n\n//all songs\nprint_r($allSongs);\n</code></pre>\n\n<p>To retrieve only unique id's, you can use the array function <code>array_unique</code> to remove the duplicates from an array.</p>\n\n<pre><code>$uniqueSongs = array_unique($allSongs, SORT_REGULAR);\nprint_r($uniqueSongs);\n</code></pre>\n"
}
] | 2019/11/24 | [
"https://wordpress.stackexchange.com/questions/353219",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178703/"
] | I've made a loop that goes over all the gigs I've attended, some gigs have the same songs.
Here is the result of that array:
<http://snippi.com/s/k80v7pe>
Now I want to have an array of all the distinct song id's. So want to see all the songs that I've ever heard:
```
//get the songs field get_field('songs')
foreach ($postIds as $postId){
array_push($songIds, get_field('songs', $postId));
}
//Over here I'm trying to print all the ID's of the song
foreach ($songIds as $songId) {
echo $songId->ID;
}
```
But I'm getting the following error:
>
> Notice: Trying to get property 'ID' of non-object in
>
>
>
Is that because of that the array `$songIds` has an array in an array? | No, that's because you are treating an [array](https://www.php.net/manual/en/language.types.array.php) as an [object](https://www.php.net/manual/en/language.types.object.php) and `PHP` doesn't convert those types automatically. To get an individual element from an object you use:
```
$my_object->Element1;
```
To get an individual element from an array you use:
```
$my_array[Element1];
```
You can even nest arrays. So if you have $my\_array, where each element is another array, you can get elementX from arrayY like this:
```
$my_array[arrayY][elementX];
```
In your case, apparently, you have an array, which holds an array, which holds objects, amounting to:
```
$my_array[arrayY][elementX]->componentZ
``` |
353,229 | <p>I'm using Woocommerce in WordPress and noticed the variation price does not show on the product page, but does when I add the item to a cart. The variation prices are the same no matter what the size selection is. I read this is an issue with Woocommerce, but I'm wondering if anyone has found a way to get the price to show. Currently as a work around, I had to add price in the product Description. Any assistance would be greatly appreciated. I'm also not all that familiar with WordPress and Woocommerce, but I have resources that can help me if the respond is above my understanding. Thank you in advance. </p>
| [
{
"answer_id": 353223,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>No, that's because you are treating an <a href=\"https://www.php.net/manual/en/language.types.array.php\" rel=\"nofollow noreferrer\">array</a> as an <a href=\"https://www.php.net/manual/en/language.types.object.php\" rel=\"nofollow noreferrer\">object</a> and <code>PHP</code> doesn't convert those types automatically. To get an individual element from an object you use:</p>\n\n<pre><code>$my_object->Element1;\n</code></pre>\n\n<p>To get an individual element from an array you use:</p>\n\n<pre><code>$my_array[Element1];\n</code></pre>\n\n<p>You can even nest arrays. So if you have $my_array, where each element is another array, you can get elementX from arrayY like this:</p>\n\n<pre><code>$my_array[arrayY][elementX];\n</code></pre>\n\n<p>In your case, apparently, you have an array, which holds an array, which holds objects, amounting to:</p>\n\n<pre><code>$my_array[arrayY][elementX]->componentZ\n</code></pre>\n"
},
{
"answer_id": 353372,
"author": "Dennis",
"author_id": 178703,
"author_profile": "https://wordpress.stackexchange.com/users/178703",
"pm_score": 0,
"selected": false,
"text": "<p>Because <code>$songIds</code> is an array within an array, I have to do 2 loops within each other.</p>\n\n<p>The code below pushes all post id's from the different arrays in a new array <code>$allSongs</code>.</p>\n\n<p>This way I have an array with all the id's. Some id's will be duplicates because some songs are played more than 1 time over all the gigs.</p>\n\n<pre><code>foreach ($songIds as $songId) {\n foreach ($songId as $key => $value) {\n array_push($allSongs, $value->ID);\n }\n}\n\n//all songs\nprint_r($allSongs);\n</code></pre>\n\n<p>To retrieve only unique id's, you can use the array function <code>array_unique</code> to remove the duplicates from an array.</p>\n\n<pre><code>$uniqueSongs = array_unique($allSongs, SORT_REGULAR);\nprint_r($uniqueSongs);\n</code></pre>\n"
}
] | 2019/11/24 | [
"https://wordpress.stackexchange.com/questions/353229",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178856/"
] | I'm using Woocommerce in WordPress and noticed the variation price does not show on the product page, but does when I add the item to a cart. The variation prices are the same no matter what the size selection is. I read this is an issue with Woocommerce, but I'm wondering if anyone has found a way to get the price to show. Currently as a work around, I had to add price in the product Description. Any assistance would be greatly appreciated. I'm also not all that familiar with WordPress and Woocommerce, but I have resources that can help me if the respond is above my understanding. Thank you in advance. | No, that's because you are treating an [array](https://www.php.net/manual/en/language.types.array.php) as an [object](https://www.php.net/manual/en/language.types.object.php) and `PHP` doesn't convert those types automatically. To get an individual element from an object you use:
```
$my_object->Element1;
```
To get an individual element from an array you use:
```
$my_array[Element1];
```
You can even nest arrays. So if you have $my\_array, where each element is another array, you can get elementX from arrayY like this:
```
$my_array[arrayY][elementX];
```
In your case, apparently, you have an array, which holds an array, which holds objects, amounting to:
```
$my_array[arrayY][elementX]->componentZ
``` |
353,233 | <p>I have a mystery problem. I have successfully created a custom post type, with associated categories. BUT, when I list the posts, the QuickEdit section does not display the title, date or any information. It is blank and I don't know why. Can anyone see the problem?</p>
<pre><code>//////////////////////// setup admin pages
add_action( 'init', 'mmd_client_tracking_form', 0 ); // Add the menu
function mmd_client_tracking_form()
{
$labels = array(
'name' => _x( 'Review Client Workouts', 'mmd_client_list' ),
'singular_name' => _x( 'Manage Clients', 'mmd_client_list' ),
'add_new' => _x( 'New Client', 'mmd_client_list' ),
'add_new_item' => __( 'Add New Client' ),
'edit_item' => __( 'Edit Client' ),
'new_item' => __( 'New Client' ),
'all_items' => __( 'Workout Clients' ),
'view_item' => __( 'View Client' ),
'search_items' => __( 'Search Clients' ),
'not_found' => __( 'No Clients found' ),
'not_found_in_trash' => __( 'No Clients found in the Trash' ),
'parent_item_colon' => '',
'menu_name' => 'Biorider Tracking'
);
$args = array(
'register_meta_box_cb' => 'mmdtrack_meta_box', // Register a meta box
'labels' => $labels,
'description' => 'This post type holds all posts for your directory items.',
'public' => true,
'menu_position' => 10,
'show_ui' => true,
'supports' => array( 'title' ),
'has_archive' => true,
'menu_icon' => 'dashicons-media-spreadsheet',
);
register_post_type( 'mmdtrack', $args );
}
//-----------------------------------------------------------------
// CUSTOM CATAGORY
//-----------------------------------------------------------------
add_action( 'init', 'mmd_track_taxonomies', 0 ); // Add the standard submenu
function mmd_track_taxonomies() {
$labels = array(
'name' => _x( 'Biorider Categories', 'Biorider Categories' ),
'singular_name' => _x( 'Category', 'taxonomy singular name' ),
'search_items' => __( 'Search Clients Categories' ),
'all_items' => __( 'All Clients Categories' ),
'parent_item' => __( 'Parent Clients Categories' ),
'parent_item_colon' => __( 'Parent Clients Category:' ),
'edit_item' => __( 'Edit Clients Category' ),
'update_item' => __( 'Update Clients Category' ),
'add_new_item' => __( 'Add New Clients Category' ),
'new_item_name' => __( 'New Clients Category Name' ),
'menu_name' => __( 'Clients Categories')
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'mmdtrack_cat' )
);
register_taxonomy( 'mmdtrack_cat', 'mmdtrack', $args );
}
add_action( 'init', 'mmd_tracking_menu', 0 ); // Add the standard submenu
function mmd_tracking_menu()
{
add_submenu_page('edit.php?post_type=mmdtrack', // Parent Slug from add_menu_page
'Biorider Settings', // Title of page
'Settings', // Menu title
'manage_options', // Minimum capability to view the menu.
'mmd_Tracking_Settings_slug', // Unqiue Slug Name
'mmd_trackingAdminPage' ); // A callback function used to display page content.
}
//-----------------------------------------------------------------
// ENTRIES OF MEMBER LISTINGS - MANUAL
//-----------------------------------------------------------------
function mmdtrack_meta_box(WP_Post $post)
{
$prefix = 'mmdtrack'; // Custom Post Name
add_meta_box($prefix, 'Set Tracking', mmdtrack_client_tracking_form);
}
function mmdtrack_client_tracking_form($PostId)
{
... displaying code for metabox
}
////////////////////////////////////////////////////////////////////////
// THIS HOOKS IN TO WORDPRESS CUSTOM POST AND CHANGES THE
// MANAGE LIST FORM
//////////////////////////////////////////////////////////////////////
add_filter('manage_mmdtrack_posts_columns', 'mmd_member_track_columns_head');
function mmd_member_track_columns_head($defaults) {
$new_columns['cb'] = '<input type="checkbox" />';
$new_columns['mmd_member_name'] = 'Name';
$new_columns['mmd_member_tracking_workout_count'] = 'Number of Workouts';
$new_columns['mmd_member_memberships'] = 'Active Membershps';
$new_columns['mmd_member_category'] = 'Categories';
return $new_columns;
}
add_action('manage_mmdtrack_posts_custom_column', 'mmd_track_columns_content', 10, 2);
function mmd_track_columns_content($column_name, $post_ID)
{
switch($column_name)
{
case 'mmd_member_name':
$Name = get_the_title( $post_ID );
echo $Name;
break;
case 'mmd_member_tracking_workout_count':
$user_ID = mmd_track_FindUser($post_ID);
echo mmd_track_GetWorkoutCnt($user_ID);
break;
case 'mmd_member_memberships':
$user_ID = mmd_track_FindUser($post_ID);
if($user_ID==0)
echo "None";
break;
case 'mmd_member_category':
$terms = get_the_terms( $post_ID, 'mmdtrack_cat' );
/* If terms were found. */
if ( !empty( $terms ) )
{
$out = array();
/* Loop through each term, linking to the 'edit posts' page for the specific term. */
foreach ( $terms as $term )
{
$out[] = sprintf( '<a href="%s">%s</a>',
esc_url( add_query_arg( array( 'post_type' => 'mmdtrack', 'mmdtrack_cat' => $term->slug ), 'edit.php' ) ),
esc_html( sanitize_term_field( 'name', $term->name, $term->term_id, 'mmdtrack_cat', 'display' ) )
);
}
/* Join the terms, separating them with a comma. */
echo join( ', ', $out );
}
break;
}
}
function mmd_track_emptytrash($post_ID)
{
if(get_post_status( $post_id ) === 'trash')
ClearMemberWorkouts($post_ID);
return 0;
}
add_action( 'before_delete_post', 'mmd_track_emptytrash');
////////////////////////////////////////////////////////////
// If a list is trashed, make sure all the list records are
// removed from the table.
////////////////////////////////////////////////////////////
function mmd_track_place_in_trash($post_ID)
{
}
add_action('wp_trash_post', 'mmd_track_place_in_trash');
</code></pre>
| [
{
"answer_id": 353236,
"author": "jg314",
"author_id": 26202,
"author_profile": "https://wordpress.stackexchange.com/users/26202",
"pm_score": 3,
"selected": true,
"text": "<p>The issue looks to be associated with your <code>mmd_member_track_columns_head()</code> function. Instead of modifying the default columns, they are being completely overwritten, causing the Quick Edit functionality to stop working. In particular, the <code>title</code> key must be part of the array for it to work. Try something like this:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('manage_mmdtrack_posts_columns', 'mmd_member_track_columns_head');\nfunction mmd_member_track_columns_head( $defaults ) {\n\n // Modify the existing columns, instead of overwriting them.\n $defaults['title'] = 'Name';\n $defaults['mmd_member_tracking_workout_count'] = 'Number of Workouts';\n $defaults['mmd_member_memberships'] = 'Active Membershps';\n\n // Remove the \"Date\" column if you don't want it.\n unset( $defaults['date'] );\n\n return $defaults;\n}\n</code></pre>\n\n<p>This code does a few things:</p>\n\n<ol>\n<li>It retains the \"Title\" column to allow the Quick Edit functionality to work, but renames it to \"Name\". This should also allow you to remove code for outputting the title from <code>mmd_track_columns_content()</code> since WordPress does this automatically.</li>\n<li>It removes the need for the <code>mmd_member_category</code> column, since WordPress outputs the associated taxonomy terms automatically. This should also allow you to remove code from <code>mmd_track_columns_content()</code>.</li>\n</ol>\n\n<p>In general, I'd recommend using the functionality that WordPress already provides instead of rewriting it. Not only will this limit the amount of custom code you have to write, but it will also further ensure compatibility with future versions of WordPress.</p>\n\n<p>I hope this is helpful. Let me know if you have any questions.</p>\n"
},
{
"answer_id": 353260,
"author": "Debbie Kurth",
"author_id": 119560,
"author_profile": "https://wordpress.stackexchange.com/users/119560",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks to Jg314, the answer was simple. I took away the default Title Once that was restored, everything worked again.</p>\n\n<p>WRONG WAY. Remove this <code>$new_columns['mmd_member_name']</code> as seen below</p>\n\n<pre><code>function mmd_member_track_columns_head($defaults) {\n\n $new_columns['cb'] = '<input type=\"checkbox\" />';\n $new_columns['mmd_member_name'] = 'Name';\n $new_columns['mmd_member_tracking_workout_count'] = 'Number of Workouts';\n $new_columns['mmd_member_memberships'] = 'Active Membershps';\n $new_columns['mmd_member_category'] = 'Categories';\n\n return $new_columns;\n}\n\nadd_action('manage_mmdtrack_posts_custom_column', 'mmd_track_columns_content', 10, 2);\nfunction mmd_track_columns_content($column_name, $post_ID)\n{\n</code></pre>\n\n<p>and the remove the associated key <code>case 'mmd_member_name':</code></p>\n\n<pre><code>switch($column_name)\n { \n case 'mmd_member_name': \n $Name = get_the_title( $post_ID );\n echo $Name;\n break;\n\n case 'mmd_member_tracking_workout_count':\n $user_ID = mmd_track_FindUser($post_ID);\n echo mmd_track_GetWorkoutCnt($user_ID);\n break;\n\n case 'mmd_member_memberships':\n $user_ID = mmd_track_FindUser($post_ID);\n if($user_ID==0)\n echo \"None\";\n break;\n\n case 'mmd_member_category':\n $terms = get_the_terms( $post_ID, 'mmdtrack_cat' );\n\n /* If terms were found. */\n if ( !empty( $terms ) ) \n {\n $out = array();\n\n /* Loop through each term, linking to the 'edit posts' page for the specific term. */\n foreach ( $terms as $term ) \n {\n $out[] = sprintf( '<a href=\"%s\">%s</a>',\n esc_url( add_query_arg( array( 'post_type' => 'mmdtrack', 'mmdtrack_cat' => $term->slug ), 'edit.php' ) ),\n esc_html( sanitize_term_field( 'name', $term->name, $term->term_id, 'mmdtrack_cat', 'display' ) )\n );\n }\n\n /* Join the terms, separating them with a comma. */\n echo join( ', ', $out );\n }\n\n break; \n\n }\n}\n\n\n\n</code></pre>\n\n<p>WHAT FIXED IT. Add back <code>$new_columns['title'] = __('Title');</code></p>\n\n<pre><code>add_filter('manage_mmdclienttrack_posts_columns', 'mmd_member_track_columns_head');\nfunction mmd_member_track_columns_head($defaults) {\n\n $new_columns['cb'] = '<input type=\"checkbox\" />';\n $new_columns['title'] = __('Title');\n $new_columns['mmd_member_tracking_workout_count'] = 'Number of Workouts';\n $new_columns['mmd_member_memberships'] = 'Active Membershps';\n $new_columns['mmd_member_category'] = 'Categories';\n\n return $new_columns;\n}\n```\n\n\n</code></pre>\n"
}
] | 2019/11/24 | [
"https://wordpress.stackexchange.com/questions/353233",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119560/"
] | I have a mystery problem. I have successfully created a custom post type, with associated categories. BUT, when I list the posts, the QuickEdit section does not display the title, date or any information. It is blank and I don't know why. Can anyone see the problem?
```
//////////////////////// setup admin pages
add_action( 'init', 'mmd_client_tracking_form', 0 ); // Add the menu
function mmd_client_tracking_form()
{
$labels = array(
'name' => _x( 'Review Client Workouts', 'mmd_client_list' ),
'singular_name' => _x( 'Manage Clients', 'mmd_client_list' ),
'add_new' => _x( 'New Client', 'mmd_client_list' ),
'add_new_item' => __( 'Add New Client' ),
'edit_item' => __( 'Edit Client' ),
'new_item' => __( 'New Client' ),
'all_items' => __( 'Workout Clients' ),
'view_item' => __( 'View Client' ),
'search_items' => __( 'Search Clients' ),
'not_found' => __( 'No Clients found' ),
'not_found_in_trash' => __( 'No Clients found in the Trash' ),
'parent_item_colon' => '',
'menu_name' => 'Biorider Tracking'
);
$args = array(
'register_meta_box_cb' => 'mmdtrack_meta_box', // Register a meta box
'labels' => $labels,
'description' => 'This post type holds all posts for your directory items.',
'public' => true,
'menu_position' => 10,
'show_ui' => true,
'supports' => array( 'title' ),
'has_archive' => true,
'menu_icon' => 'dashicons-media-spreadsheet',
);
register_post_type( 'mmdtrack', $args );
}
//-----------------------------------------------------------------
// CUSTOM CATAGORY
//-----------------------------------------------------------------
add_action( 'init', 'mmd_track_taxonomies', 0 ); // Add the standard submenu
function mmd_track_taxonomies() {
$labels = array(
'name' => _x( 'Biorider Categories', 'Biorider Categories' ),
'singular_name' => _x( 'Category', 'taxonomy singular name' ),
'search_items' => __( 'Search Clients Categories' ),
'all_items' => __( 'All Clients Categories' ),
'parent_item' => __( 'Parent Clients Categories' ),
'parent_item_colon' => __( 'Parent Clients Category:' ),
'edit_item' => __( 'Edit Clients Category' ),
'update_item' => __( 'Update Clients Category' ),
'add_new_item' => __( 'Add New Clients Category' ),
'new_item_name' => __( 'New Clients Category Name' ),
'menu_name' => __( 'Clients Categories')
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'mmdtrack_cat' )
);
register_taxonomy( 'mmdtrack_cat', 'mmdtrack', $args );
}
add_action( 'init', 'mmd_tracking_menu', 0 ); // Add the standard submenu
function mmd_tracking_menu()
{
add_submenu_page('edit.php?post_type=mmdtrack', // Parent Slug from add_menu_page
'Biorider Settings', // Title of page
'Settings', // Menu title
'manage_options', // Minimum capability to view the menu.
'mmd_Tracking_Settings_slug', // Unqiue Slug Name
'mmd_trackingAdminPage' ); // A callback function used to display page content.
}
//-----------------------------------------------------------------
// ENTRIES OF MEMBER LISTINGS - MANUAL
//-----------------------------------------------------------------
function mmdtrack_meta_box(WP_Post $post)
{
$prefix = 'mmdtrack'; // Custom Post Name
add_meta_box($prefix, 'Set Tracking', mmdtrack_client_tracking_form);
}
function mmdtrack_client_tracking_form($PostId)
{
... displaying code for metabox
}
////////////////////////////////////////////////////////////////////////
// THIS HOOKS IN TO WORDPRESS CUSTOM POST AND CHANGES THE
// MANAGE LIST FORM
//////////////////////////////////////////////////////////////////////
add_filter('manage_mmdtrack_posts_columns', 'mmd_member_track_columns_head');
function mmd_member_track_columns_head($defaults) {
$new_columns['cb'] = '<input type="checkbox" />';
$new_columns['mmd_member_name'] = 'Name';
$new_columns['mmd_member_tracking_workout_count'] = 'Number of Workouts';
$new_columns['mmd_member_memberships'] = 'Active Membershps';
$new_columns['mmd_member_category'] = 'Categories';
return $new_columns;
}
add_action('manage_mmdtrack_posts_custom_column', 'mmd_track_columns_content', 10, 2);
function mmd_track_columns_content($column_name, $post_ID)
{
switch($column_name)
{
case 'mmd_member_name':
$Name = get_the_title( $post_ID );
echo $Name;
break;
case 'mmd_member_tracking_workout_count':
$user_ID = mmd_track_FindUser($post_ID);
echo mmd_track_GetWorkoutCnt($user_ID);
break;
case 'mmd_member_memberships':
$user_ID = mmd_track_FindUser($post_ID);
if($user_ID==0)
echo "None";
break;
case 'mmd_member_category':
$terms = get_the_terms( $post_ID, 'mmdtrack_cat' );
/* If terms were found. */
if ( !empty( $terms ) )
{
$out = array();
/* Loop through each term, linking to the 'edit posts' page for the specific term. */
foreach ( $terms as $term )
{
$out[] = sprintf( '<a href="%s">%s</a>',
esc_url( add_query_arg( array( 'post_type' => 'mmdtrack', 'mmdtrack_cat' => $term->slug ), 'edit.php' ) ),
esc_html( sanitize_term_field( 'name', $term->name, $term->term_id, 'mmdtrack_cat', 'display' ) )
);
}
/* Join the terms, separating them with a comma. */
echo join( ', ', $out );
}
break;
}
}
function mmd_track_emptytrash($post_ID)
{
if(get_post_status( $post_id ) === 'trash')
ClearMemberWorkouts($post_ID);
return 0;
}
add_action( 'before_delete_post', 'mmd_track_emptytrash');
////////////////////////////////////////////////////////////
// If a list is trashed, make sure all the list records are
// removed from the table.
////////////////////////////////////////////////////////////
function mmd_track_place_in_trash($post_ID)
{
}
add_action('wp_trash_post', 'mmd_track_place_in_trash');
``` | The issue looks to be associated with your `mmd_member_track_columns_head()` function. Instead of modifying the default columns, they are being completely overwritten, causing the Quick Edit functionality to stop working. In particular, the `title` key must be part of the array for it to work. Try something like this:
```php
add_filter('manage_mmdtrack_posts_columns', 'mmd_member_track_columns_head');
function mmd_member_track_columns_head( $defaults ) {
// Modify the existing columns, instead of overwriting them.
$defaults['title'] = 'Name';
$defaults['mmd_member_tracking_workout_count'] = 'Number of Workouts';
$defaults['mmd_member_memberships'] = 'Active Membershps';
// Remove the "Date" column if you don't want it.
unset( $defaults['date'] );
return $defaults;
}
```
This code does a few things:
1. It retains the "Title" column to allow the Quick Edit functionality to work, but renames it to "Name". This should also allow you to remove code for outputting the title from `mmd_track_columns_content()` since WordPress does this automatically.
2. It removes the need for the `mmd_member_category` column, since WordPress outputs the associated taxonomy terms automatically. This should also allow you to remove code from `mmd_track_columns_content()`.
In general, I'd recommend using the functionality that WordPress already provides instead of rewriting it. Not only will this limit the amount of custom code you have to write, but it will also further ensure compatibility with future versions of WordPress.
I hope this is helpful. Let me know if you have any questions. |
353,244 | <p>I am trying to write an if condition with 3 statements but it keeps crashing the site. Here is my statement, can you please advise what the issue is.</p>
<pre><code><?php if (is_page ('20')){?>
print this
<?php elseif (is_page ('50')){?>
then print this
<?php } else { ?>
print this
<?php } ?>
</code></pre>
| [
{
"answer_id": 353246,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>You're missing <code>}</code> before <code>elseif</code>:</p>\n\n<pre><code><?php if (is_page ('20')){?>\nprint this\n<?php } elseif (is_page ('50')){?>\nthen print this\n<?php } else { ?>\nprint this\n<?php } ?>\n</code></pre>\n\n<p>Remove the PHP tags and you'll see why:</p>\n\n<pre><code>if ( is_page( '20' ) ) {\n\nelseif ( is_page( '50' ) ) {\n\n} else {\n\n}\n</code></pre>\n"
},
{
"answer_id": 353281,
"author": "ejomi",
"author_id": 178884,
"author_profile": "https://wordpress.stackexchange.com/users/178884",
"pm_score": 0,
"selected": false,
"text": "<p>You may write the statement in only one, short row:</p>\n\n<pre><code>print (is_page('20') ? \"my output for page 20\" : (is_page('50') ? \"my output for page 50\" : \"my output for anything else\") );\n</code></pre>\n\n<p>Important: Brackets must be in the right order like <code>(statement ? if-result : else-result)</code> where the \"else-result\" is a 2nd nested statement, so it looks like <code>(statement-1 ? 1st-if-result : (statement ? 2nd-if-result : last-else-result) )</code>\nGood luck!</p>\n"
}
] | 2019/11/25 | [
"https://wordpress.stackexchange.com/questions/353244",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66373/"
] | I am trying to write an if condition with 3 statements but it keeps crashing the site. Here is my statement, can you please advise what the issue is.
```
<?php if (is_page ('20')){?>
print this
<?php elseif (is_page ('50')){?>
then print this
<?php } else { ?>
print this
<?php } ?>
``` | You're missing `}` before `elseif`:
```
<?php if (is_page ('20')){?>
print this
<?php } elseif (is_page ('50')){?>
then print this
<?php } else { ?>
print this
<?php } ?>
```
Remove the PHP tags and you'll see why:
```
if ( is_page( '20' ) ) {
elseif ( is_page( '50' ) ) {
} else {
}
``` |
353,314 | <p>I tried everything. I even removed all content in functions.php and created a whole new file with just this:</p>
<pre><code>function wpdocs_dequeue_script() {
if (is_singular()) {
wp_dequeue_script( 'gdrts-rating' );
}
}
add_action( 'wp_print_scripts', 'wpdocs_dequeue_script', 100 );
</code></pre>
<p>The idea is to remove some Javascript files from my custom post type. I thought I was doing something wrong so I first tried with is_page() and even is_home(), but even that is not working for me. It seems like the code is not fired or so.</p>
<p><strong>This is my plugin:</strong></p>
<pre><code> wp_enqueue_script('gdrts-events', $this->file('js', 'events'), array(), gdrts_settings()->file_version(), false);
wp_enqueue_script('gdrts-rating', $this->file('js', 'rating'), $depend_js, gdrts_settings()->file_version(), true);
</code></pre>
<p>So, I also tried to do it like this:</p>
<pre><code>function wpdocs_dequeue_script() {
wp_dequeue_script( 'gdrts-rating' );
}
add_action( 'wp_enqueue_scripts', 'wpdocs_dequeue_script', 100 );
</code></pre>
<p>Not working!</p>
| [
{
"answer_id": 353251,
"author": "admcfajn",
"author_id": 123674,
"author_profile": "https://wordpress.stackexchange.com/users/123674",
"pm_score": 0,
"selected": false,
"text": "<p>Add a pre_get_posts filter.</p>\n\n<p>It looks like the following:</p>\n\n<pre><code>function do_this_before_stuff( $the_query_object ) {\n if ( ! empty( $_GET['something'] ) ) {\n $something = sanitize_key( $_GET['something'] );\n $the_query_object->set( 'something', $something );\n }\n}\nadd_action( 'pre_get_posts', 'do_this_before_stuff' );\n</code></pre>\n\n<p>There's other good places to put actions/filters, but <code>pre_get_posts</code> is a pretty great one.</p>\n"
},
{
"answer_id": 353253,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 4,
"selected": true,
"text": "<p>In WordPress, <code>name</code> is a <a href=\"https://codex.wordpress.org/Reserved_Terms\" rel=\"noreferrer\">reserved term</a> (emphasis mine):</p>\n\n<blockquote>\n <p>There is a complete set of reserved keywords, or terms, in WordPress\n that <strong>should not be used in certain circumstances</strong> as they may conflict\n with core functionality. You should avoid using any of these terms\n when:</p>\n \n <ul>\n <li><strong>Passing a term through a <code>$_GET</code> or <code>$_POST</code> array</strong> </li>\n <li>Registering a taxonomy or post type slug</li>\n <li>Handling query variables</li>\n </ul>\n</blockquote>\n\n<p>In this case, this is not just a redirect. Internally, all WordPress pages and posts are accessed via query parameters on <code>index.php</code>, so whenever you access a URL like <code>https://example.com/post-name/</code>, you're <em>actually</em> loading <code>https://example.com/index.php?name=post-name</code>. So if you somehow changed WordPress so that posts were not accessible with the <code>name</code> parameter, you'd break all of your post permalinks.</p>\n\n<p>To avoid conflicts with WordPress, you should choose something else for your parameter, such as <code>first_name</code>, or <code>full_name</code>.</p>\n"
}
] | 2019/11/25 | [
"https://wordpress.stackexchange.com/questions/353314",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62192/"
] | I tried everything. I even removed all content in functions.php and created a whole new file with just this:
```
function wpdocs_dequeue_script() {
if (is_singular()) {
wp_dequeue_script( 'gdrts-rating' );
}
}
add_action( 'wp_print_scripts', 'wpdocs_dequeue_script', 100 );
```
The idea is to remove some Javascript files from my custom post type. I thought I was doing something wrong so I first tried with is\_page() and even is\_home(), but even that is not working for me. It seems like the code is not fired or so.
**This is my plugin:**
```
wp_enqueue_script('gdrts-events', $this->file('js', 'events'), array(), gdrts_settings()->file_version(), false);
wp_enqueue_script('gdrts-rating', $this->file('js', 'rating'), $depend_js, gdrts_settings()->file_version(), true);
```
So, I also tried to do it like this:
```
function wpdocs_dequeue_script() {
wp_dequeue_script( 'gdrts-rating' );
}
add_action( 'wp_enqueue_scripts', 'wpdocs_dequeue_script', 100 );
```
Not working! | In WordPress, `name` is a [reserved term](https://codex.wordpress.org/Reserved_Terms) (emphasis mine):
>
> There is a complete set of reserved keywords, or terms, in WordPress
> that **should not be used in certain circumstances** as they may conflict
> with core functionality. You should avoid using any of these terms
> when:
>
>
> * **Passing a term through a `$_GET` or `$_POST` array**
> * Registering a taxonomy or post type slug
> * Handling query variables
>
>
>
In this case, this is not just a redirect. Internally, all WordPress pages and posts are accessed via query parameters on `index.php`, so whenever you access a URL like `https://example.com/post-name/`, you're *actually* loading `https://example.com/index.php?name=post-name`. So if you somehow changed WordPress so that posts were not accessible with the `name` parameter, you'd break all of your post permalinks.
To avoid conflicts with WordPress, you should choose something else for your parameter, such as `first_name`, or `full_name`. |
353,317 | <p>I am trying to get all posts from category <code>products</code>. My template looks like this: <code>/products/PARENT_CATEGORY/CHILD_CATEGORY</code>. What I need is all the posts from every CHILD_CATEGORY.</p>
<p>I try to access it via <code>/posts?categories=28</code>, but it returns no posts, as the category with ID of 28 doesn't have any posts itself. But its child, for example, category with ID of 40, has some posts. Should I access them like <code>/posts?categories=40,41,42...</code>? Or there is another way to do it?</p>
| [
{
"answer_id": 353324,
"author": "Faye",
"author_id": 76600,
"author_profile": "https://wordpress.stackexchange.com/users/76600",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think you can query your posts via a url like that.</p>\n\n<p>Ideally, you would have a template file <code>taxonomy-{taxonomyname}.php</code> so in this case, <code>taxonomy-products.php</code> </p>\n\n<p>From there, there's a few different ways to do this, though the one I would use is to set up a loop like this.</p>\n\n<pre><code><?php\n\n $args = [\n 'post_type' => 'post',\n 'posts_per_page' => 8, // or however many you want\n 'post_status' => 'publish',\n 'order' => 'DESC',\n 'orderby' => 'date',\n 'tax_query' => [ // this part will get the category and its childs\n [\n 'taxonomy' => 'category',\n 'terms' => [ '28' ], // parent category id\n 'field' => 'term_id',\n ],\n ],\n ];\n\n // The Query.\n $the_query = new WP_Query( $args );\n\n\n // The Loop.\n if ( $the_query->have_posts() ) {\n ?>\n\n <?php\n while ( $the_query->have_posts() ) {\n\n $the_query->the_post();\n\n // your code for the post here like the_title and the_excerpt\n\n }\n ?>\n\n\n <?php\n wp_reset_postdata();\n }\n ?>\n</code></pre>\n"
},
{
"answer_id": 364303,
"author": "Álvaro Reneses",
"author_id": 186255,
"author_profile": "https://wordpress.stackexchange.com/users/186255",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same use case than you — calling WP-API from React — and ran into the same issue.</p>\n\n<p>Unfortunately WP-API does not support filtering by parent categories. In order to support it, you could extend the API's functionality, adding a new filter that will run a <code>tax_query</code> behind the scenes, similar to <a href=\"https://wordpress.stackexchange.com/a/353324/186255\">Faye's answer</a>.</p>\n\n<p>Assuming that you have access to the Wordpress application, modify the <code>functions.php</code> in the current theme adding:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Add parent_category filter to REST API\nfunction rest_filter_by_parent_category($args, $request) \n{\n if (isset($request['parent_category'])) {\n $parent_category = sanitize_text_field($request['parent_category']);\n $args['tax_query'] = [\n [\n 'taxonomy' => 'category', \n 'field' => 'term_id', \n 'include_children' => true,\n 'operator' => 'IN',\n 'terms' => $parent_category, \n ]\n ];\n }\n return $args;\n}\n\nadd_filter('rest_post_query', 'rest_filter_by_parent_category', 10, 3);\n</code></pre>\n\n<p>Then, just query the API with the new filter: <code>/posts?parent_category=28</code></p>\n\n<p><strong>Alternative</strong></p>\n\n<p>If you cannot modify the <code>functions.php</code> file (e.g. you are querying an external blog), then you could:</p>\n\n<ol>\n<li>Fetch all the categories (which you might have already done in your app).</li>\n<li>Build a reverse index, with the shape <code>[parentId: number] => number[]</code></li>\n<li>Build the query using <code>categories=C1,C2...</code> using the reverse index.</li>\n</ol>\n\n<pre class=\"lang-js prettyprint-override\"><code>const axios = require(\"axios\");\n\n// Query all the categories from Wordpress\nconst fetchCategories = async () => {\n const params = [\n \"_fields[]=id\",\n \"_fields[]=parent\",\n // Ideally you would use a better pagination strategy\n \"page=1\",\n \"per_page=100\",\n ];\n\n // Using axios, but you could use native fetch or any other library\n return axios\n .get(`WORDPRESS_SITE/wp-json/wp/v2/categories?${params.join(\"&\")}`)\n .then((result) => result.data);\n};\n\n// Build reverse index\nconst buildParentIndex = (categories) => {\n return categories.reduce((acc, category) => {\n const hasParent = !!category.parent; // Root categories have ID 0\n\n const parentId = hasParent ? category.parent : category.id;\n if (!acc[parentId]) {\n acc[parentId] = [];\n }\n\n if (hasParent) {\n acc[parentId].push(category.id);\n }\n\n return acc;\n }, {});\n};\n\n(async () => {\n // You should pre-compute & cache these, as fetching the categories\n // and building the index on every request will heavily affect\n // the latency of your request\n const categories = await fetchCategories();\n const parentIndex = buildParentIndex(categories);\n\n const fetchPostsByParentId = (categoryId) =>\n axios\n .get(\n `WORDPRESS_SITE/wp-json/wp/v2/posts?categories${parentIndex[\n categoryId\n ].join(\"&\")}`\n )\n .then((result) => result.data);\n})();\n</code></pre>\n\n<p>If possible, I'd suggest to go with the first approach — modifying <code>functions.php</code> — as it's simpler and more consistent. The JS alternative will likely require caching for that the latency not to be impacted, which brings a lot of potential issues (e.g. stale cache). </p>\n\n<p><strong>Source</strong></p>\n\n<ul>\n<li><a href=\"https://barebones.dev/rest-api-filter-posts-by-tax_query/\" rel=\"nofollow noreferrer\">https://barebones.dev/rest-api-filter-posts-by-tax_query/</a></li>\n<li><a href=\"https://wordpress.stackexchange.com/questions/313380/how-to-display-child-posts-in-the-parent-category\">How to display child posts in the parent category</a></li>\n</ul>\n"
}
] | 2019/11/25 | [
"https://wordpress.stackexchange.com/questions/353317",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178908/"
] | I am trying to get all posts from category `products`. My template looks like this: `/products/PARENT_CATEGORY/CHILD_CATEGORY`. What I need is all the posts from every CHILD\_CATEGORY.
I try to access it via `/posts?categories=28`, but it returns no posts, as the category with ID of 28 doesn't have any posts itself. But its child, for example, category with ID of 40, has some posts. Should I access them like `/posts?categories=40,41,42...`? Or there is another way to do it? | I had the same use case than you — calling WP-API from React — and ran into the same issue.
Unfortunately WP-API does not support filtering by parent categories. In order to support it, you could extend the API's functionality, adding a new filter that will run a `tax_query` behind the scenes, similar to [Faye's answer](https://wordpress.stackexchange.com/a/353324/186255).
Assuming that you have access to the Wordpress application, modify the `functions.php` in the current theme adding:
```php
// Add parent_category filter to REST API
function rest_filter_by_parent_category($args, $request)
{
if (isset($request['parent_category'])) {
$parent_category = sanitize_text_field($request['parent_category']);
$args['tax_query'] = [
[
'taxonomy' => 'category',
'field' => 'term_id',
'include_children' => true,
'operator' => 'IN',
'terms' => $parent_category,
]
];
}
return $args;
}
add_filter('rest_post_query', 'rest_filter_by_parent_category', 10, 3);
```
Then, just query the API with the new filter: `/posts?parent_category=28`
**Alternative**
If you cannot modify the `functions.php` file (e.g. you are querying an external blog), then you could:
1. Fetch all the categories (which you might have already done in your app).
2. Build a reverse index, with the shape `[parentId: number] => number[]`
3. Build the query using `categories=C1,C2...` using the reverse index.
```js
const axios = require("axios");
// Query all the categories from Wordpress
const fetchCategories = async () => {
const params = [
"_fields[]=id",
"_fields[]=parent",
// Ideally you would use a better pagination strategy
"page=1",
"per_page=100",
];
// Using axios, but you could use native fetch or any other library
return axios
.get(`WORDPRESS_SITE/wp-json/wp/v2/categories?${params.join("&")}`)
.then((result) => result.data);
};
// Build reverse index
const buildParentIndex = (categories) => {
return categories.reduce((acc, category) => {
const hasParent = !!category.parent; // Root categories have ID 0
const parentId = hasParent ? category.parent : category.id;
if (!acc[parentId]) {
acc[parentId] = [];
}
if (hasParent) {
acc[parentId].push(category.id);
}
return acc;
}, {});
};
(async () => {
// You should pre-compute & cache these, as fetching the categories
// and building the index on every request will heavily affect
// the latency of your request
const categories = await fetchCategories();
const parentIndex = buildParentIndex(categories);
const fetchPostsByParentId = (categoryId) =>
axios
.get(
`WORDPRESS_SITE/wp-json/wp/v2/posts?categories${parentIndex[
categoryId
].join("&")}`
)
.then((result) => result.data);
})();
```
If possible, I'd suggest to go with the first approach — modifying `functions.php` — as it's simpler and more consistent. The JS alternative will likely require caching for that the latency not to be impacted, which brings a lot of potential issues (e.g. stale cache).
**Source**
* <https://barebones.dev/rest-api-filter-posts-by-tax_query/>
* [How to display child posts in the parent category](https://wordpress.stackexchange.com/questions/313380/how-to-display-child-posts-in-the-parent-category) |
353,353 | <p>You see I have a Navigation bar items, in the parent item <code>Products & Services</code> with two sub menus.</p>
<p><a href="https://i.stack.imgur.com/j59wZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j59wZ.png" alt="redire"></a></p>
<p>I have a requirement, when I click the menu item <code>Products & Services</code> it redirect to its sub-menu <code>Dedicated Servers</code>. </p>
<p>How can I do with this?</p>
<hr>
<p><strong>EDIT-01</strong></p>
<p>I only want the <code>Products & Services</code> parent have this redirect, the other parent do not need, such as <code>Home</code>, <code>Advantage</code> they all have their own page.</p>
| [
{
"answer_id": 353324,
"author": "Faye",
"author_id": 76600,
"author_profile": "https://wordpress.stackexchange.com/users/76600",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think you can query your posts via a url like that.</p>\n\n<p>Ideally, you would have a template file <code>taxonomy-{taxonomyname}.php</code> so in this case, <code>taxonomy-products.php</code> </p>\n\n<p>From there, there's a few different ways to do this, though the one I would use is to set up a loop like this.</p>\n\n<pre><code><?php\n\n $args = [\n 'post_type' => 'post',\n 'posts_per_page' => 8, // or however many you want\n 'post_status' => 'publish',\n 'order' => 'DESC',\n 'orderby' => 'date',\n 'tax_query' => [ // this part will get the category and its childs\n [\n 'taxonomy' => 'category',\n 'terms' => [ '28' ], // parent category id\n 'field' => 'term_id',\n ],\n ],\n ];\n\n // The Query.\n $the_query = new WP_Query( $args );\n\n\n // The Loop.\n if ( $the_query->have_posts() ) {\n ?>\n\n <?php\n while ( $the_query->have_posts() ) {\n\n $the_query->the_post();\n\n // your code for the post here like the_title and the_excerpt\n\n }\n ?>\n\n\n <?php\n wp_reset_postdata();\n }\n ?>\n</code></pre>\n"
},
{
"answer_id": 364303,
"author": "Álvaro Reneses",
"author_id": 186255,
"author_profile": "https://wordpress.stackexchange.com/users/186255",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same use case than you — calling WP-API from React — and ran into the same issue.</p>\n\n<p>Unfortunately WP-API does not support filtering by parent categories. In order to support it, you could extend the API's functionality, adding a new filter that will run a <code>tax_query</code> behind the scenes, similar to <a href=\"https://wordpress.stackexchange.com/a/353324/186255\">Faye's answer</a>.</p>\n\n<p>Assuming that you have access to the Wordpress application, modify the <code>functions.php</code> in the current theme adding:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Add parent_category filter to REST API\nfunction rest_filter_by_parent_category($args, $request) \n{\n if (isset($request['parent_category'])) {\n $parent_category = sanitize_text_field($request['parent_category']);\n $args['tax_query'] = [\n [\n 'taxonomy' => 'category', \n 'field' => 'term_id', \n 'include_children' => true,\n 'operator' => 'IN',\n 'terms' => $parent_category, \n ]\n ];\n }\n return $args;\n}\n\nadd_filter('rest_post_query', 'rest_filter_by_parent_category', 10, 3);\n</code></pre>\n\n<p>Then, just query the API with the new filter: <code>/posts?parent_category=28</code></p>\n\n<p><strong>Alternative</strong></p>\n\n<p>If you cannot modify the <code>functions.php</code> file (e.g. you are querying an external blog), then you could:</p>\n\n<ol>\n<li>Fetch all the categories (which you might have already done in your app).</li>\n<li>Build a reverse index, with the shape <code>[parentId: number] => number[]</code></li>\n<li>Build the query using <code>categories=C1,C2...</code> using the reverse index.</li>\n</ol>\n\n<pre class=\"lang-js prettyprint-override\"><code>const axios = require(\"axios\");\n\n// Query all the categories from Wordpress\nconst fetchCategories = async () => {\n const params = [\n \"_fields[]=id\",\n \"_fields[]=parent\",\n // Ideally you would use a better pagination strategy\n \"page=1\",\n \"per_page=100\",\n ];\n\n // Using axios, but you could use native fetch or any other library\n return axios\n .get(`WORDPRESS_SITE/wp-json/wp/v2/categories?${params.join(\"&\")}`)\n .then((result) => result.data);\n};\n\n// Build reverse index\nconst buildParentIndex = (categories) => {\n return categories.reduce((acc, category) => {\n const hasParent = !!category.parent; // Root categories have ID 0\n\n const parentId = hasParent ? category.parent : category.id;\n if (!acc[parentId]) {\n acc[parentId] = [];\n }\n\n if (hasParent) {\n acc[parentId].push(category.id);\n }\n\n return acc;\n }, {});\n};\n\n(async () => {\n // You should pre-compute & cache these, as fetching the categories\n // and building the index on every request will heavily affect\n // the latency of your request\n const categories = await fetchCategories();\n const parentIndex = buildParentIndex(categories);\n\n const fetchPostsByParentId = (categoryId) =>\n axios\n .get(\n `WORDPRESS_SITE/wp-json/wp/v2/posts?categories${parentIndex[\n categoryId\n ].join(\"&\")}`\n )\n .then((result) => result.data);\n})();\n</code></pre>\n\n<p>If possible, I'd suggest to go with the first approach — modifying <code>functions.php</code> — as it's simpler and more consistent. The JS alternative will likely require caching for that the latency not to be impacted, which brings a lot of potential issues (e.g. stale cache). </p>\n\n<p><strong>Source</strong></p>\n\n<ul>\n<li><a href=\"https://barebones.dev/rest-api-filter-posts-by-tax_query/\" rel=\"nofollow noreferrer\">https://barebones.dev/rest-api-filter-posts-by-tax_query/</a></li>\n<li><a href=\"https://wordpress.stackexchange.com/questions/313380/how-to-display-child-posts-in-the-parent-category\">How to display child posts in the parent category</a></li>\n</ul>\n"
}
] | 2019/11/26 | [
"https://wordpress.stackexchange.com/questions/353353",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178244/"
] | You see I have a Navigation bar items, in the parent item `Products & Services` with two sub menus.
[](https://i.stack.imgur.com/j59wZ.png)
I have a requirement, when I click the menu item `Products & Services` it redirect to its sub-menu `Dedicated Servers`.
How can I do with this?
---
**EDIT-01**
I only want the `Products & Services` parent have this redirect, the other parent do not need, such as `Home`, `Advantage` they all have their own page. | I had the same use case than you — calling WP-API from React — and ran into the same issue.
Unfortunately WP-API does not support filtering by parent categories. In order to support it, you could extend the API's functionality, adding a new filter that will run a `tax_query` behind the scenes, similar to [Faye's answer](https://wordpress.stackexchange.com/a/353324/186255).
Assuming that you have access to the Wordpress application, modify the `functions.php` in the current theme adding:
```php
// Add parent_category filter to REST API
function rest_filter_by_parent_category($args, $request)
{
if (isset($request['parent_category'])) {
$parent_category = sanitize_text_field($request['parent_category']);
$args['tax_query'] = [
[
'taxonomy' => 'category',
'field' => 'term_id',
'include_children' => true,
'operator' => 'IN',
'terms' => $parent_category,
]
];
}
return $args;
}
add_filter('rest_post_query', 'rest_filter_by_parent_category', 10, 3);
```
Then, just query the API with the new filter: `/posts?parent_category=28`
**Alternative**
If you cannot modify the `functions.php` file (e.g. you are querying an external blog), then you could:
1. Fetch all the categories (which you might have already done in your app).
2. Build a reverse index, with the shape `[parentId: number] => number[]`
3. Build the query using `categories=C1,C2...` using the reverse index.
```js
const axios = require("axios");
// Query all the categories from Wordpress
const fetchCategories = async () => {
const params = [
"_fields[]=id",
"_fields[]=parent",
// Ideally you would use a better pagination strategy
"page=1",
"per_page=100",
];
// Using axios, but you could use native fetch or any other library
return axios
.get(`WORDPRESS_SITE/wp-json/wp/v2/categories?${params.join("&")}`)
.then((result) => result.data);
};
// Build reverse index
const buildParentIndex = (categories) => {
return categories.reduce((acc, category) => {
const hasParent = !!category.parent; // Root categories have ID 0
const parentId = hasParent ? category.parent : category.id;
if (!acc[parentId]) {
acc[parentId] = [];
}
if (hasParent) {
acc[parentId].push(category.id);
}
return acc;
}, {});
};
(async () => {
// You should pre-compute & cache these, as fetching the categories
// and building the index on every request will heavily affect
// the latency of your request
const categories = await fetchCategories();
const parentIndex = buildParentIndex(categories);
const fetchPostsByParentId = (categoryId) =>
axios
.get(
`WORDPRESS_SITE/wp-json/wp/v2/posts?categories${parentIndex[
categoryId
].join("&")}`
)
.then((result) => result.data);
})();
```
If possible, I'd suggest to go with the first approach — modifying `functions.php` — as it's simpler and more consistent. The JS alternative will likely require caching for that the latency not to be impacted, which brings a lot of potential issues (e.g. stale cache).
**Source**
* <https://barebones.dev/rest-api-filter-posts-by-tax_query/>
* [How to display child posts in the parent category](https://wordpress.stackexchange.com/questions/313380/how-to-display-child-posts-in-the-parent-category) |
353,370 | <p>Is it possible to block specific plugins from updating, manually too? I don't want to block this by hiding the notification, changing the plugin version or anything like this. I'd like the notification to show, show the new version number, but when hitting the update manually it should block/disallow this - preferably displaying some sort of (cusomized) notification in the plugin section (eg. "Update for this plugin is not possible").</p>
| [
{
"answer_id": 353324,
"author": "Faye",
"author_id": 76600,
"author_profile": "https://wordpress.stackexchange.com/users/76600",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think you can query your posts via a url like that.</p>\n\n<p>Ideally, you would have a template file <code>taxonomy-{taxonomyname}.php</code> so in this case, <code>taxonomy-products.php</code> </p>\n\n<p>From there, there's a few different ways to do this, though the one I would use is to set up a loop like this.</p>\n\n<pre><code><?php\n\n $args = [\n 'post_type' => 'post',\n 'posts_per_page' => 8, // or however many you want\n 'post_status' => 'publish',\n 'order' => 'DESC',\n 'orderby' => 'date',\n 'tax_query' => [ // this part will get the category and its childs\n [\n 'taxonomy' => 'category',\n 'terms' => [ '28' ], // parent category id\n 'field' => 'term_id',\n ],\n ],\n ];\n\n // The Query.\n $the_query = new WP_Query( $args );\n\n\n // The Loop.\n if ( $the_query->have_posts() ) {\n ?>\n\n <?php\n while ( $the_query->have_posts() ) {\n\n $the_query->the_post();\n\n // your code for the post here like the_title and the_excerpt\n\n }\n ?>\n\n\n <?php\n wp_reset_postdata();\n }\n ?>\n</code></pre>\n"
},
{
"answer_id": 364303,
"author": "Álvaro Reneses",
"author_id": 186255,
"author_profile": "https://wordpress.stackexchange.com/users/186255",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same use case than you — calling WP-API from React — and ran into the same issue.</p>\n\n<p>Unfortunately WP-API does not support filtering by parent categories. In order to support it, you could extend the API's functionality, adding a new filter that will run a <code>tax_query</code> behind the scenes, similar to <a href=\"https://wordpress.stackexchange.com/a/353324/186255\">Faye's answer</a>.</p>\n\n<p>Assuming that you have access to the Wordpress application, modify the <code>functions.php</code> in the current theme adding:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Add parent_category filter to REST API\nfunction rest_filter_by_parent_category($args, $request) \n{\n if (isset($request['parent_category'])) {\n $parent_category = sanitize_text_field($request['parent_category']);\n $args['tax_query'] = [\n [\n 'taxonomy' => 'category', \n 'field' => 'term_id', \n 'include_children' => true,\n 'operator' => 'IN',\n 'terms' => $parent_category, \n ]\n ];\n }\n return $args;\n}\n\nadd_filter('rest_post_query', 'rest_filter_by_parent_category', 10, 3);\n</code></pre>\n\n<p>Then, just query the API with the new filter: <code>/posts?parent_category=28</code></p>\n\n<p><strong>Alternative</strong></p>\n\n<p>If you cannot modify the <code>functions.php</code> file (e.g. you are querying an external blog), then you could:</p>\n\n<ol>\n<li>Fetch all the categories (which you might have already done in your app).</li>\n<li>Build a reverse index, with the shape <code>[parentId: number] => number[]</code></li>\n<li>Build the query using <code>categories=C1,C2...</code> using the reverse index.</li>\n</ol>\n\n<pre class=\"lang-js prettyprint-override\"><code>const axios = require(\"axios\");\n\n// Query all the categories from Wordpress\nconst fetchCategories = async () => {\n const params = [\n \"_fields[]=id\",\n \"_fields[]=parent\",\n // Ideally you would use a better pagination strategy\n \"page=1\",\n \"per_page=100\",\n ];\n\n // Using axios, but you could use native fetch or any other library\n return axios\n .get(`WORDPRESS_SITE/wp-json/wp/v2/categories?${params.join(\"&\")}`)\n .then((result) => result.data);\n};\n\n// Build reverse index\nconst buildParentIndex = (categories) => {\n return categories.reduce((acc, category) => {\n const hasParent = !!category.parent; // Root categories have ID 0\n\n const parentId = hasParent ? category.parent : category.id;\n if (!acc[parentId]) {\n acc[parentId] = [];\n }\n\n if (hasParent) {\n acc[parentId].push(category.id);\n }\n\n return acc;\n }, {});\n};\n\n(async () => {\n // You should pre-compute & cache these, as fetching the categories\n // and building the index on every request will heavily affect\n // the latency of your request\n const categories = await fetchCategories();\n const parentIndex = buildParentIndex(categories);\n\n const fetchPostsByParentId = (categoryId) =>\n axios\n .get(\n `WORDPRESS_SITE/wp-json/wp/v2/posts?categories${parentIndex[\n categoryId\n ].join(\"&\")}`\n )\n .then((result) => result.data);\n})();\n</code></pre>\n\n<p>If possible, I'd suggest to go with the first approach — modifying <code>functions.php</code> — as it's simpler and more consistent. The JS alternative will likely require caching for that the latency not to be impacted, which brings a lot of potential issues (e.g. stale cache). </p>\n\n<p><strong>Source</strong></p>\n\n<ul>\n<li><a href=\"https://barebones.dev/rest-api-filter-posts-by-tax_query/\" rel=\"nofollow noreferrer\">https://barebones.dev/rest-api-filter-posts-by-tax_query/</a></li>\n<li><a href=\"https://wordpress.stackexchange.com/questions/313380/how-to-display-child-posts-in-the-parent-category\">How to display child posts in the parent category</a></li>\n</ul>\n"
}
] | 2019/11/26 | [
"https://wordpress.stackexchange.com/questions/353370",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142331/"
] | Is it possible to block specific plugins from updating, manually too? I don't want to block this by hiding the notification, changing the plugin version or anything like this. I'd like the notification to show, show the new version number, but when hitting the update manually it should block/disallow this - preferably displaying some sort of (cusomized) notification in the plugin section (eg. "Update for this plugin is not possible"). | I had the same use case than you — calling WP-API from React — and ran into the same issue.
Unfortunately WP-API does not support filtering by parent categories. In order to support it, you could extend the API's functionality, adding a new filter that will run a `tax_query` behind the scenes, similar to [Faye's answer](https://wordpress.stackexchange.com/a/353324/186255).
Assuming that you have access to the Wordpress application, modify the `functions.php` in the current theme adding:
```php
// Add parent_category filter to REST API
function rest_filter_by_parent_category($args, $request)
{
if (isset($request['parent_category'])) {
$parent_category = sanitize_text_field($request['parent_category']);
$args['tax_query'] = [
[
'taxonomy' => 'category',
'field' => 'term_id',
'include_children' => true,
'operator' => 'IN',
'terms' => $parent_category,
]
];
}
return $args;
}
add_filter('rest_post_query', 'rest_filter_by_parent_category', 10, 3);
```
Then, just query the API with the new filter: `/posts?parent_category=28`
**Alternative**
If you cannot modify the `functions.php` file (e.g. you are querying an external blog), then you could:
1. Fetch all the categories (which you might have already done in your app).
2. Build a reverse index, with the shape `[parentId: number] => number[]`
3. Build the query using `categories=C1,C2...` using the reverse index.
```js
const axios = require("axios");
// Query all the categories from Wordpress
const fetchCategories = async () => {
const params = [
"_fields[]=id",
"_fields[]=parent",
// Ideally you would use a better pagination strategy
"page=1",
"per_page=100",
];
// Using axios, but you could use native fetch or any other library
return axios
.get(`WORDPRESS_SITE/wp-json/wp/v2/categories?${params.join("&")}`)
.then((result) => result.data);
};
// Build reverse index
const buildParentIndex = (categories) => {
return categories.reduce((acc, category) => {
const hasParent = !!category.parent; // Root categories have ID 0
const parentId = hasParent ? category.parent : category.id;
if (!acc[parentId]) {
acc[parentId] = [];
}
if (hasParent) {
acc[parentId].push(category.id);
}
return acc;
}, {});
};
(async () => {
// You should pre-compute & cache these, as fetching the categories
// and building the index on every request will heavily affect
// the latency of your request
const categories = await fetchCategories();
const parentIndex = buildParentIndex(categories);
const fetchPostsByParentId = (categoryId) =>
axios
.get(
`WORDPRESS_SITE/wp-json/wp/v2/posts?categories${parentIndex[
categoryId
].join("&")}`
)
.then((result) => result.data);
})();
```
If possible, I'd suggest to go with the first approach — modifying `functions.php` — as it's simpler and more consistent. The JS alternative will likely require caching for that the latency not to be impacted, which brings a lot of potential issues (e.g. stale cache).
**Source**
* <https://barebones.dev/rest-api-filter-posts-by-tax_query/>
* [How to display child posts in the parent category](https://wordpress.stackexchange.com/questions/313380/how-to-display-child-posts-in-the-parent-category) |
353,379 | <p>I have a created a contact form in the <code>function.php</code> and added short code on my page and it's working. I am getting my form.</p>
<pre><code>function st_contact_form(){
ob_start();
?>
<div class="contact_form-wrapper popup-contact-form">
<form action="" method="post" name="contact_form" id="contact_form" autocomplete="off">
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-xs-12 ">
<div class="form-group">
<input type="text" name="name" placeholder="Name" class="form-control" required>
</div>
</div>
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-xs-12 ">
<div class="form-group">
<input type="email" name="email" placeholder="Email Id" class="form-control" required>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-xs-12 ">
<div class="form-group">
<input type="text" name="mobileno" placeholder="Phone no" class="form-control" required>
</div>
</div>
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-xs-12 ">
<div class="form-group select-service">
<select class="form-control" name="type_of_services" required>
<option selected disabled>Select Service</option>
<option value="1">Testing one</option>
<option value="2">Testing two</option>
</select>
</div>
</div>
</div>
<div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-xs-12 paddingLR0">
<div class="form-group">
<textarea class="form-control" placeholder="Message" name="message" rows="2" required></textarea>
</div>
</div>
<div class="form-group ">
<input type="submit" name="send" value="Submit" class="btn_st btn_maroon form_submit_btn">
</div>
</form>
</div>
<?php
return ob_get_clean();
}
add_shortcode( 'contact_form', 'st_contact_form' );
</code></pre>
<p>I added below script in script file and validation is working. Now I want to know how to submit the form in wordpress? Should I create a table? or I have to create process.php file and add some logic?</p>
<pre><code>$("#contact_form").validate({
rules: {
name: {
required:true
},
email: {
required:true,
email: true,
emailExt: true
},
mobileno: {
required:true,
minlength: 10,
maxlength: 10,
number: true
},
type_of_services: {
required:true
},
message: {
required:true
}
},
submitHandler: function(r) {
if(isReqInprogress){
return;
}
isReqInprogress = true;
$.ajax({
url:base_url+"/wp-content/themes/mytheme/process.php",
type: "post",
data:{name:name,email:email,mobileno:mobileno,type_of_services:type_of_services,message:message},
dataType:"JSON",
success: function(response) {
alert("success");
isReqInprogress = false;
}
})
}
});
</code></pre>
<p><strong>Process.php</strong></p>
<pre><code><?php
global $wpdb;
$data = $_POST;
$to = $data['email'];
$subject = 'The subject';
$body = 'The email body content';
$headers = array('Content-Type: text/html; charset=UTF-8');
//$mail = wp_mail($data['email'], $subject, $body, $headers );
//if ($mail) {
$wpdb->insert('wp_contact',
array(
'name' => $data['name'],
'email' => $data['email'],
'mobileno' => $data['mobileno'],
'message' => $data['message'],
),
array(
'%s',
'%s',
'%s',
'%s',
)
);
//}
?>
</code></pre>
<p>Would you help me out?</p>
| [
{
"answer_id": 353392,
"author": "Manan",
"author_id": 178960,
"author_profile": "https://wordpress.stackexchange.com/users/178960",
"pm_score": -1,
"selected": false,
"text": "<p>Yes you have to write code for inserting data in your process.php</p>\n\n<pre><code>global $wpdb;\n$name=$_POST['name'];\n$email= $_POST['email'];\n$mob=$_POST['moblieno'];\n$service_type=$_POST['type_of_service'];\n$msg=$_POST['message'];\n$wpdb->insert('tbl_name',array('name_field'=>$name,'email_field'=>$email,'service-field'=>$service_type,'message_field'=>$msg));\n</code></pre>\n"
},
{
"answer_id": 353508,
"author": "Naren Verma",
"author_id": 177715,
"author_profile": "https://wordpress.stackexchange.com/users/177715",
"pm_score": 1,
"selected": true,
"text": "<p>Finally, I got my solution,</p>\n<p>I added below code in <code>function.php</code> and using shortcode I am getting my form on webpage</p>\n<pre><code>function st_contact_form(){\nob_start();\n ?>\n <div class="contact_form-wrapper popup-contact-form">\n <form action="" method="post" name="contact_form" id="contact_form" autocomplete="off">\n <div class="row"> \n <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-xs-12 ">\n <div class="form-group">\n <input type="text" name="name" placeholder="Name" class="form-control" required>\n </div>\n </div>\n <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-xs-12 ">\n <div class="form-group">\n <input type="email" name="email" placeholder="Email Id" class="form-control" required>\n </div>\n </div>\n </div> \n <div class="row"> \n <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-xs-12 ">\n <div class="form-group">\n <input type="text" name="mobileno" placeholder="Phone no" class="form-control" required>\n </div>\n </div> \n <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-xs-12 ">\n <div class="form-group select-service">\n <select class="form-control" name="type_of_services" required>\n <option selected disabled>Select Service</option>\n <option value="1">Testing one</option>\n <option value="2">Testing two</option>\n\n </select>\n </div>\n </div>\n </div>\n <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-xs-12 paddingLR0">\n <div class="form-group">\n <textarea class="form-control" placeholder="Message" name="message" rows="2" required></textarea>\n </div>\n </div>\n <div class="form-group ">\n <input type="submit" name="send" value="Submit" class="btn_st btn_maroon form_submit_btn">\n </div>\n </form>\n </div>\n<?php\nreturn ob_get_clean();\n}\nadd_shortcode( 'contact_form', 'st_contact_form' );\n</code></pre>\n<p>Now next step is, JQuery validation and Ajax. Also I created a <code>process.php</code> file in my theme</p>\n<pre><code>$("#contact_form").validate({\nrules: {\n name: {\n required:true\n },\n email: {\n required:true,\n email: true\n },\n mobileno: {\n required:true,\n minlength: 10,\n maxlength: 10,\n number: true\n },\n type_of_services: {\n required:true\n },\n message: {\n required:true\n }\n},\n \nsubmitHandler: function(form) {\n if(isReqInprogress){\n return;\n }\n $.ajax({\n url:"/wp-content/themes/themename/process.php",\n type: "post",\n data:$('#contact_form').serialize(), \n dataType:"JSON",\n success: function(response) {\n \n alert("Your message has been received and we will be contacting you shortly to follow-up.");\n isReqInprogress = false;\n }\n });\n}\n});\n</code></pre>\n<p><strong>Process.php</strong></p>\n<p>Note: I have created a contact table in my database</p>\n<pre><code><?php\ndefine( 'BLOCK_LOAD', true );\nrequire_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-config.php' );\nrequire_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-includes/wp-db.php' );\n$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);\n\nglobal $wpdb; // <--- making $wpdb as global\n$data = $_POST;\n$query=$wpdb->insert('contact',\n array(\n 'name' => $data['name'],\n 'email' => $data['email'],\n 'phone' => $data['mobileno'],\n 'type_of_services' => $data['type_of_services'],\n 'message' => $data['message']\n ),\n array(\n '%s',\n '%s',\n '%s',\n '%s',\n '%s',\n )\n);\n\n\n if ($query) {\n $response['error'] = "true";\n\n }else{\n $response['error'] = "false";\n } \necho json_encode($response);\nexit();\n // $wpdb->show_errors(); \n\n?>\n</code></pre>\n<p>that's it. It's working perfectly for me.</p>\n"
}
] | 2019/11/26 | [
"https://wordpress.stackexchange.com/questions/353379",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/177715/"
] | I have a created a contact form in the `function.php` and added short code on my page and it's working. I am getting my form.
```
function st_contact_form(){
ob_start();
?>
<div class="contact_form-wrapper popup-contact-form">
<form action="" method="post" name="contact_form" id="contact_form" autocomplete="off">
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-xs-12 ">
<div class="form-group">
<input type="text" name="name" placeholder="Name" class="form-control" required>
</div>
</div>
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-xs-12 ">
<div class="form-group">
<input type="email" name="email" placeholder="Email Id" class="form-control" required>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-xs-12 ">
<div class="form-group">
<input type="text" name="mobileno" placeholder="Phone no" class="form-control" required>
</div>
</div>
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-xs-12 ">
<div class="form-group select-service">
<select class="form-control" name="type_of_services" required>
<option selected disabled>Select Service</option>
<option value="1">Testing one</option>
<option value="2">Testing two</option>
</select>
</div>
</div>
</div>
<div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-xs-12 paddingLR0">
<div class="form-group">
<textarea class="form-control" placeholder="Message" name="message" rows="2" required></textarea>
</div>
</div>
<div class="form-group ">
<input type="submit" name="send" value="Submit" class="btn_st btn_maroon form_submit_btn">
</div>
</form>
</div>
<?php
return ob_get_clean();
}
add_shortcode( 'contact_form', 'st_contact_form' );
```
I added below script in script file and validation is working. Now I want to know how to submit the form in wordpress? Should I create a table? or I have to create process.php file and add some logic?
```
$("#contact_form").validate({
rules: {
name: {
required:true
},
email: {
required:true,
email: true,
emailExt: true
},
mobileno: {
required:true,
minlength: 10,
maxlength: 10,
number: true
},
type_of_services: {
required:true
},
message: {
required:true
}
},
submitHandler: function(r) {
if(isReqInprogress){
return;
}
isReqInprogress = true;
$.ajax({
url:base_url+"/wp-content/themes/mytheme/process.php",
type: "post",
data:{name:name,email:email,mobileno:mobileno,type_of_services:type_of_services,message:message},
dataType:"JSON",
success: function(response) {
alert("success");
isReqInprogress = false;
}
})
}
});
```
**Process.php**
```
<?php
global $wpdb;
$data = $_POST;
$to = $data['email'];
$subject = 'The subject';
$body = 'The email body content';
$headers = array('Content-Type: text/html; charset=UTF-8');
//$mail = wp_mail($data['email'], $subject, $body, $headers );
//if ($mail) {
$wpdb->insert('wp_contact',
array(
'name' => $data['name'],
'email' => $data['email'],
'mobileno' => $data['mobileno'],
'message' => $data['message'],
),
array(
'%s',
'%s',
'%s',
'%s',
)
);
//}
?>
```
Would you help me out? | Finally, I got my solution,
I added below code in `function.php` and using shortcode I am getting my form on webpage
```
function st_contact_form(){
ob_start();
?>
<div class="contact_form-wrapper popup-contact-form">
<form action="" method="post" name="contact_form" id="contact_form" autocomplete="off">
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-xs-12 ">
<div class="form-group">
<input type="text" name="name" placeholder="Name" class="form-control" required>
</div>
</div>
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-xs-12 ">
<div class="form-group">
<input type="email" name="email" placeholder="Email Id" class="form-control" required>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-xs-12 ">
<div class="form-group">
<input type="text" name="mobileno" placeholder="Phone no" class="form-control" required>
</div>
</div>
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-xs-12 ">
<div class="form-group select-service">
<select class="form-control" name="type_of_services" required>
<option selected disabled>Select Service</option>
<option value="1">Testing one</option>
<option value="2">Testing two</option>
</select>
</div>
</div>
</div>
<div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-xs-12 paddingLR0">
<div class="form-group">
<textarea class="form-control" placeholder="Message" name="message" rows="2" required></textarea>
</div>
</div>
<div class="form-group ">
<input type="submit" name="send" value="Submit" class="btn_st btn_maroon form_submit_btn">
</div>
</form>
</div>
<?php
return ob_get_clean();
}
add_shortcode( 'contact_form', 'st_contact_form' );
```
Now next step is, JQuery validation and Ajax. Also I created a `process.php` file in my theme
```
$("#contact_form").validate({
rules: {
name: {
required:true
},
email: {
required:true,
email: true
},
mobileno: {
required:true,
minlength: 10,
maxlength: 10,
number: true
},
type_of_services: {
required:true
},
message: {
required:true
}
},
submitHandler: function(form) {
if(isReqInprogress){
return;
}
$.ajax({
url:"/wp-content/themes/themename/process.php",
type: "post",
data:$('#contact_form').serialize(),
dataType:"JSON",
success: function(response) {
alert("Your message has been received and we will be contacting you shortly to follow-up.");
isReqInprogress = false;
}
});
}
});
```
**Process.php**
Note: I have created a contact table in my database
```
<?php
define( 'BLOCK_LOAD', true );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-config.php' );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-includes/wp-db.php' );
$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
global $wpdb; // <--- making $wpdb as global
$data = $_POST;
$query=$wpdb->insert('contact',
array(
'name' => $data['name'],
'email' => $data['email'],
'phone' => $data['mobileno'],
'type_of_services' => $data['type_of_services'],
'message' => $data['message']
),
array(
'%s',
'%s',
'%s',
'%s',
'%s',
)
);
if ($query) {
$response['error'] = "true";
}else{
$response['error'] = "false";
}
echo json_encode($response);
exit();
// $wpdb->show_errors();
?>
```
that's it. It's working perfectly for me. |
353,389 | <p>When i attach below line code i get white screen and in console log it is getting below error my browsers are up to date</p>
<p>Code </p>
<pre><code>body:not(.no-transition) #wrapper, .animsition-overlay { position: relative; opacity: 0; -webkit-animation-fill-mode: both;
animation-fill-mode: both; }
</code></pre>
<p>Console log error </p>
<blockquote>
<p>JQMIGRATE: Migrate is installed, version 1.4.1
jquery-migrate.min.js:2:552 Animsition: Element does not exist on
page. plugins.js:428:1211 Animsition: Does not support this browser.
plugins.js:428:1273</p>
</blockquote>
| [
{
"answer_id": 353397,
"author": "Andrew",
"author_id": 164495,
"author_profile": "https://wordpress.stackexchange.com/users/164495",
"pm_score": 1,
"selected": false,
"text": "<p>\"White screen\" generally means there is a PHP error preventing the page from being generated. You should <a href=\"https://wordpress.org/support/article/debugging-in-wordpress/\" rel=\"nofollow noreferrer\">check your WordPress error log</a> (wp-content/debug.log by default) for any relevant errors. </p>\n\n<p>Adding CSS code would not prevent the page from loading.</p>\n"
},
{
"answer_id": 377440,
"author": "ROMEO 1.0.1",
"author_id": 196891,
"author_profile": "https://wordpress.stackexchange.com/users/196891",
"pm_score": 0,
"selected": false,
"text": "<p>Sometimes a default <strong>(if that exists)</strong> WordPress <em>css</em> attribute name may have a conflict with the attribute names in your <em>css</em> .</p>\n<p>Try changing your <em>css</em> names to something different of <strong>more descriptive</strong>,</p>\n<p>An example name that I've seen bring conflict/WSOD <strong>aka:</strong> "White Screen Of Death" in WordPress is <code>.page</code></p>\n<p>Try avoiding words like:</p>\n<ol>\n<li>blog</li>\n<li>wordpress</li>\n<li>wp</li>\n<li>header</li>\n<li>footer</li>\n</ol>\n<p>... or anything generic in your <em>css</em></p>\n<p>Hope this helps.</p>\n"
}
] | 2019/11/26 | [
"https://wordpress.stackexchange.com/questions/353389",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178938/"
] | When i attach below line code i get white screen and in console log it is getting below error my browsers are up to date
Code
```
body:not(.no-transition) #wrapper, .animsition-overlay { position: relative; opacity: 0; -webkit-animation-fill-mode: both;
animation-fill-mode: both; }
```
Console log error
>
> JQMIGRATE: Migrate is installed, version 1.4.1
> jquery-migrate.min.js:2:552 Animsition: Element does not exist on
> page. plugins.js:428:1211 Animsition: Does not support this browser.
> plugins.js:428:1273
>
>
> | "White screen" generally means there is a PHP error preventing the page from being generated. You should [check your WordPress error log](https://wordpress.org/support/article/debugging-in-wordpress/) (wp-content/debug.log by default) for any relevant errors.
Adding CSS code would not prevent the page from loading. |
353,426 | <p>I have the following situation which I tried to solve by using the website and forum but unfortunately no success so far.</p>
<p>I am working on a new site (old still-now online) but when changing the Site Address (URL), i receive a error 404 when trying to accees the site www.gas-spring.com. <a href="https://i.stack.imgur.com/BQNWP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BQNWP.png" alt="enter image description here"></a></p>
<p>When changing the permalink settings and saving them there is no change and I still receive the error 404. When I change the Site Address (URL) back to wordpress URL everything is working fine. I stopped plugins and clearing cache etc.. but nothing seems to work.</p>
<p>The .htaccess is :</p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>I really would like to receive some help in resolving this. I'm a beginner with Wordpress so maybe I have overlooked something. </p>
<p>I use filezilla to upload the site and the files are stored in - /home/www/public_html/wordpress </p>
<p>If i check the following link, <a href="https://www.gas-spring.com/wordpress/" rel="nofollow noreferrer">https://www.gas-spring.com/wordpress/</a> , I can see some of the website loading but still with errors.</p>
<p>Filezilla / folder : <a href="https://i.stack.imgur.com/geYg0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/geYg0.png" alt="enter image description here"></a></p>
<p>Please inform me if you require any more info.
Thanks in advace,
Regards,
Stefan</p>
| [
{
"answer_id": 353430,
"author": "Vimal Usadadiya",
"author_id": 178951,
"author_profile": "https://wordpress.stackexchange.com/users/178951",
"pm_score": 1,
"selected": false,
"text": "<p>You can also change site address in database direct. You can use below link to generate sql query to change your old url to new url.\n<a href=\"https://codepen.io/EightArmsHQ/full/nzEjI\" rel=\"nofollow noreferrer\">https://codepen.io/EightArmsHQ/full/nzEjI</a></p>\n\n<p>and try below .htaccess code:</p>\n\n<pre><code><IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n</code></pre>\n"
},
{
"answer_id": 353445,
"author": "Stefan",
"author_id": 178986,
"author_profile": "https://wordpress.stackexchange.com/users/178986",
"pm_score": 0,
"selected": false,
"text": "<p>I am checking links/permalinks etc... and when I edit a page and update/preview it I see the following message, \"Updating failed. Error message: The response is not a valid JSON response.\"</p>\n\n<p>I did not see this message / error before. Does it have something to do with the site not viewing properly ?</p>\n\n<p><a href=\"https://i.stack.imgur.com/n4brk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/n4brk.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 353450,
"author": "TomC",
"author_id": 36980,
"author_profile": "https://wordpress.stackexchange.com/users/36980",
"pm_score": 1,
"selected": true,
"text": "<p>You have installed your website in public_html/wordpress so you need to move it up a directory in FTP or change your URL in the dashboard to gas-springs.com/wordpress.</p>\n\n<p>The JSON error is because your Wordpress URL is HTTP and the Site URL is HTTPS.</p>\n"
}
] | 2019/11/27 | [
"https://wordpress.stackexchange.com/questions/353426",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178986/"
] | I have the following situation which I tried to solve by using the website and forum but unfortunately no success so far.
I am working on a new site (old still-now online) but when changing the Site Address (URL), i receive a error 404 when trying to accees the site www.gas-spring.com. [](https://i.stack.imgur.com/BQNWP.png)
When changing the permalink settings and saving them there is no change and I still receive the error 404. When I change the Site Address (URL) back to wordpress URL everything is working fine. I stopped plugins and clearing cache etc.. but nothing seems to work.
The .htaccess is :
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
I really would like to receive some help in resolving this. I'm a beginner with Wordpress so maybe I have overlooked something.
I use filezilla to upload the site and the files are stored in - /home/www/public\_html/wordpress
If i check the following link, <https://www.gas-spring.com/wordpress/> , I can see some of the website loading but still with errors.
Filezilla / folder : [](https://i.stack.imgur.com/geYg0.png)
Please inform me if you require any more info.
Thanks in advace,
Regards,
Stefan | You have installed your website in public\_html/wordpress so you need to move it up a directory in FTP or change your URL in the dashboard to gas-springs.com/wordpress.
The JSON error is because your Wordpress URL is HTTP and the Site URL is HTTPS. |
353,441 | <p>Is there a simple method to passing data from one file to another? I'm new to PHP and can't find a simple answer to my problem online. Apologies if this has been answered a million times & thanks in advance. </p>
<pre><code>My Template
<?php
// Declare a variable with the name of the file I want to pull in
$critical_css = 'style';
// Header
get_header();
?>
</code></pre>
<pre><code>Header
// Get php file with inline style written inside
<?php get_template_part('/path/to/' . $critical_css); ?>
</code></pre>
| [
{
"answer_id": 353442,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 3,
"selected": true,
"text": "<p>The WordPress template functions don't support passing variables (to my knowledge) by default, so you need to write your own function. For example like this,</p>\n<pre><code>// functions.php\nfunction my_template_include_with_variables( string $path = '', $data = null ) {\n $file = get_template_directory() . '/' . $path . '.php';\n if ( $path && file_exists( $file ) ) {\n // $data variable is now available in the other file\n include $file;\n } \n}\n\n// in a template file\n$critical_css = 'style';\n// include header.php and have $critical_css available in the template file\nmy_template_include_with_variables('header', $critical_css);\n\n// in header.php\nvar_dump($data); // should contain whatever $critical_css had\n</code></pre>\n<hr />\n<p><strong>UPDATE 18.8.2020</strong></p>\n<p>Since <a href=\"https://wordpress.org/news/2020/08/eckstine/\" rel=\"nofollow noreferrer\">WordPress 5.5</a> you are able to pass additional arguments with the native template functions (e.g. <a href=\"https://developer.wordpress.org/reference/functions/get_header/\" rel=\"nofollow noreferrer\">get_header()</a>, <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow noreferrer\">get_template_part()</a>, etc.) to the template files in an array.</p>\n<p>From dev docs,</p>\n<blockquote>\n<p>get_template_part( string $slug, string $name = null, array $args =\narray() )</p>\n</blockquote>\n"
},
{
"answer_id": 353444,
"author": "maryisdead",
"author_id": 2637,
"author_profile": "https://wordpress.stackexchange.com/users/2637",
"pm_score": 2,
"selected": false,
"text": "<p>Simply declaring your variable as <a href=\"https://www.php.net/manual/en/language.variables.scope.php#language.variables.scope.global\" rel=\"nofollow noreferrer\">global</a> in your header template will suffice:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php\n\nglobal $critical_css;\nget_template_part('/path/to/' . $critical_css);\n\n?> \n</code></pre>\n\n<p>No need to write your own template loading stuff (which usually is a bad idea). </p>\n"
}
] | 2019/11/27 | [
"https://wordpress.stackexchange.com/questions/353441",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/163457/"
] | Is there a simple method to passing data from one file to another? I'm new to PHP and can't find a simple answer to my problem online. Apologies if this has been answered a million times & thanks in advance.
```
My Template
<?php
// Declare a variable with the name of the file I want to pull in
$critical_css = 'style';
// Header
get_header();
?>
```
```
Header
// Get php file with inline style written inside
<?php get_template_part('/path/to/' . $critical_css); ?>
``` | The WordPress template functions don't support passing variables (to my knowledge) by default, so you need to write your own function. For example like this,
```
// functions.php
function my_template_include_with_variables( string $path = '', $data = null ) {
$file = get_template_directory() . '/' . $path . '.php';
if ( $path && file_exists( $file ) ) {
// $data variable is now available in the other file
include $file;
}
}
// in a template file
$critical_css = 'style';
// include header.php and have $critical_css available in the template file
my_template_include_with_variables('header', $critical_css);
// in header.php
var_dump($data); // should contain whatever $critical_css had
```
---
**UPDATE 18.8.2020**
Since [WordPress 5.5](https://wordpress.org/news/2020/08/eckstine/) you are able to pass additional arguments with the native template functions (e.g. [get\_header()](https://developer.wordpress.org/reference/functions/get_header/), [get\_template\_part()](https://developer.wordpress.org/reference/functions/get_template_part/), etc.) to the template files in an array.
From dev docs,
>
> get\_template\_part( string $slug, string $name = null, array $args =
> array() )
>
>
> |
353,454 | <p>I have an old server that runs important PHP aplication that required PHP 5.2.17. What is the newest WordPress that I can install on it?</p>
| [
{
"answer_id": 353442,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 3,
"selected": true,
"text": "<p>The WordPress template functions don't support passing variables (to my knowledge) by default, so you need to write your own function. For example like this,</p>\n<pre><code>// functions.php\nfunction my_template_include_with_variables( string $path = '', $data = null ) {\n $file = get_template_directory() . '/' . $path . '.php';\n if ( $path && file_exists( $file ) ) {\n // $data variable is now available in the other file\n include $file;\n } \n}\n\n// in a template file\n$critical_css = 'style';\n// include header.php and have $critical_css available in the template file\nmy_template_include_with_variables('header', $critical_css);\n\n// in header.php\nvar_dump($data); // should contain whatever $critical_css had\n</code></pre>\n<hr />\n<p><strong>UPDATE 18.8.2020</strong></p>\n<p>Since <a href=\"https://wordpress.org/news/2020/08/eckstine/\" rel=\"nofollow noreferrer\">WordPress 5.5</a> you are able to pass additional arguments with the native template functions (e.g. <a href=\"https://developer.wordpress.org/reference/functions/get_header/\" rel=\"nofollow noreferrer\">get_header()</a>, <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow noreferrer\">get_template_part()</a>, etc.) to the template files in an array.</p>\n<p>From dev docs,</p>\n<blockquote>\n<p>get_template_part( string $slug, string $name = null, array $args =\narray() )</p>\n</blockquote>\n"
},
{
"answer_id": 353444,
"author": "maryisdead",
"author_id": 2637,
"author_profile": "https://wordpress.stackexchange.com/users/2637",
"pm_score": 2,
"selected": false,
"text": "<p>Simply declaring your variable as <a href=\"https://www.php.net/manual/en/language.variables.scope.php#language.variables.scope.global\" rel=\"nofollow noreferrer\">global</a> in your header template will suffice:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php\n\nglobal $critical_css;\nget_template_part('/path/to/' . $critical_css);\n\n?> \n</code></pre>\n\n<p>No need to write your own template loading stuff (which usually is a bad idea). </p>\n"
}
] | 2019/11/27 | [
"https://wordpress.stackexchange.com/questions/353454",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105257/"
] | I have an old server that runs important PHP aplication that required PHP 5.2.17. What is the newest WordPress that I can install on it? | The WordPress template functions don't support passing variables (to my knowledge) by default, so you need to write your own function. For example like this,
```
// functions.php
function my_template_include_with_variables( string $path = '', $data = null ) {
$file = get_template_directory() . '/' . $path . '.php';
if ( $path && file_exists( $file ) ) {
// $data variable is now available in the other file
include $file;
}
}
// in a template file
$critical_css = 'style';
// include header.php and have $critical_css available in the template file
my_template_include_with_variables('header', $critical_css);
// in header.php
var_dump($data); // should contain whatever $critical_css had
```
---
**UPDATE 18.8.2020**
Since [WordPress 5.5](https://wordpress.org/news/2020/08/eckstine/) you are able to pass additional arguments with the native template functions (e.g. [get\_header()](https://developer.wordpress.org/reference/functions/get_header/), [get\_template\_part()](https://developer.wordpress.org/reference/functions/get_template_part/), etc.) to the template files in an array.
From dev docs,
>
> get\_template\_part( string $slug, string $name = null, array $args =
> array() )
>
>
> |
353,488 | <p>I have set up a custom post type (CPT) with the support for editor removed:</p>
<pre><code>register_post_type( 'review', array(
'label' => 'Reviews',
'labels' => array(
'name' => 'Reviews',
/* etc */
),
'description' => 'Tour reviews',
'menu_icon' => 'dashicons-format-chat',
'public' => true,
'supports' => array(
'title',
'revisions',
'author',
),
'has_archive' => false,
'show_in_rest' => true,
'rewrite' => array('slug' => 'reviews'),
));
</code></pre>
<p>(Yes, I'm using only the title for content ;) )</p>
<p>This works fine! However...</p>
<p>When I add a new post of this type, the auto-generated permalink has the slug of another post type's title instead of using the added post type's title.</p>
<p>So it produces:</p>
<p><em><strong>/reviews/title-of-the-last-post-of-another-post-type/</strong></em></p>
<p>instead of:</p>
<p><em><strong>/reviews/newly-added-post-of-this-post-type/</strong></em></p>
<p>Strangely, the "reviews" part is correct, but the <code>page_name</code> part isn't.</p>
<h3>Is this a bug or am I missing something?</h3>
<p>NB: If I add support for <code>editor</code> in the <code>register_post_type</code> call, this problem doesn't occur. But I don't want the editor enabled for this post type.</p>
<p>NB2: After first publish, if I manually empty the permalink's edit field and click "Update", the correct slug/<code>page_name</code> is generated.</p>
| [
{
"answer_id": 353490,
"author": "Vitor Almeida",
"author_id": 92290,
"author_profile": "https://wordpress.stackexchange.com/users/92290",
"pm_score": 1,
"selected": false,
"text": "<p>When registering or updating any rewrite for any post/custom post type you need to flush rewrite rules by the admin panel or via code:</p>\n\n<pre><code>register_activation_hook( __FILE__, 'plugin_activation' );\nfunction plugin_activation() {\n update_option('plugin_permalinks_flushed', 0);\n}\n\nadd_action( 'init', 'register_custom_post_type' );\nfunction register_custom_post_type() {\n global $wp;\n register_post_type( 'review', array(\n 'label' => 'Reviews',\n 'labels' => array(\n 'name' => 'Reviews',\n /* etc */\n ),\n 'description' => 'Tour reviews',\n 'menu_icon' => 'dashicons-format-chat',\n 'public' => true,\n 'supports' => array(\n 'title',\n 'revisions',\n 'author',\n ),\n 'has_archive' => false,\n 'show_in_rest' => true,\n 'rewrite' => array('slug' => 'reviews'),\n ));\n\n if( !get_option('plugin_permalinks_flushed') ) {\n\n flush_rewrite_rules(false);\n update_option('plugin_permalinks_flushed', 1);\n\n }\n}\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/flush_rewrite_rules/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/flush_rewrite_rules/</a></p>\n"
},
{
"answer_id": 354011,
"author": "Philip",
"author_id": 88982,
"author_profile": "https://wordpress.stackexchange.com/users/88982",
"pm_score": 1,
"selected": true,
"text": "<h1>Update</h1>\n<p>As Vitor Almeida suggested, I tried this in a blank installation of WP (v5.3) with only the default plugins installed and my theme. In this setting all works fine, as it should. Seems like one of the plugins below messes the slug up by providing the slug <code>input</code> field with a default (wrong) value when creating a new post, instead of leaving it blank:</p>\n<ul>\n<li>Yoast SEO Premium</li>\n<li>WP Rocket</li>\n<li>ShortPixel Image Optimizer</li>\n<li>Polylang</li>\n<li>Contact Form 7</li>\n<li>GDPR Cookie Consent</li>\n<li>Instagram Feed Pro Developer</li>\n</ul>\n<h1>Workaround / 'Solution'</h1>\n<p>I used a inline jQuery script to empty the slug input field on load and before publishing/updating, to make sure the WP script handling the post is forced to generate a slug based on the title. A little messy, but it works.</p>\n"
}
] | 2019/11/27 | [
"https://wordpress.stackexchange.com/questions/353488",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88982/"
] | I have set up a custom post type (CPT) with the support for editor removed:
```
register_post_type( 'review', array(
'label' => 'Reviews',
'labels' => array(
'name' => 'Reviews',
/* etc */
),
'description' => 'Tour reviews',
'menu_icon' => 'dashicons-format-chat',
'public' => true,
'supports' => array(
'title',
'revisions',
'author',
),
'has_archive' => false,
'show_in_rest' => true,
'rewrite' => array('slug' => 'reviews'),
));
```
(Yes, I'm using only the title for content ;) )
This works fine! However...
When I add a new post of this type, the auto-generated permalink has the slug of another post type's title instead of using the added post type's title.
So it produces:
***/reviews/title-of-the-last-post-of-another-post-type/***
instead of:
***/reviews/newly-added-post-of-this-post-type/***
Strangely, the "reviews" part is correct, but the `page_name` part isn't.
### Is this a bug or am I missing something?
NB: If I add support for `editor` in the `register_post_type` call, this problem doesn't occur. But I don't want the editor enabled for this post type.
NB2: After first publish, if I manually empty the permalink's edit field and click "Update", the correct slug/`page_name` is generated. | Update
======
As Vitor Almeida suggested, I tried this in a blank installation of WP (v5.3) with only the default plugins installed and my theme. In this setting all works fine, as it should. Seems like one of the plugins below messes the slug up by providing the slug `input` field with a default (wrong) value when creating a new post, instead of leaving it blank:
* Yoast SEO Premium
* WP Rocket
* ShortPixel Image Optimizer
* Polylang
* Contact Form 7
* GDPR Cookie Consent
* Instagram Feed Pro Developer
Workaround / 'Solution'
=======================
I used a inline jQuery script to empty the slug input field on load and before publishing/updating, to make sure the WP script handling the post is forced to generate a slug based on the title. A little messy, but it works. |
353,659 | <p>I want to change the article url as</p>
<pre><code>www.***.com/post/%post_id%
</code></pre>
<p>For example,</p>
<pre><code>www.***.com/post/156/
</code></pre>
<p>And now, I did it.</p>
<p>But I don't know how to change the category like this. For example,</p>
<pre><code>www.***.com/category/12/
</code></pre>
<p>Generally, the category url is:</p>
<pre><code>www.***.com/category/cat1/cat1.1/cat1.1.1/
</code></pre>
<p>I want to get:</p>
<pre><code>www.***.com/category/cat1.1.1/
</code></pre>
<p>And now I want to only display the ID of the cat1.1.1, like:</p>
<pre><code>www.***.com/category/12/ ( the id of cat1.1.1 is 12 )
</code></pre>
| [
{
"answer_id": 353672,
"author": "Spcaeyob",
"author_id": 164672,
"author_profile": "https://wordpress.stackexchange.com/users/164672",
"pm_score": -1,
"selected": false,
"text": "<p>Go to Admin panel -> Settings -> Permalinks. Change your permalink structure to numerical. Also change your category base to <em>category</em> . This will give you the permalink structure you're asking for, I.E: </p>\n\n<blockquote>\n <p>www.***.com/category/12/</p>\n</blockquote>\n\n<p>I'm not sure what you mean by </p>\n\n<blockquote>\n <p>and just show the last subcategory.</p>\n</blockquote>\n"
},
{
"answer_id": 353694,
"author": "Glu",
"author_id": 179137,
"author_profile": "https://wordpress.stackexchange.com/users/179137",
"pm_score": 2,
"selected": true,
"text": "<p>I find my answer on the internet.</p>\n\n<pre><code>function numeric_category_rewrite_rules( $rules ) {\n $custom_rules = array();\n foreach ( $rules as $regex => $rewrite ) {\n $regex = str_replace( '/(.+?)/', '/([0-9]{1,})/', $regex );\n $rewrite = str_replace( '?category_name=', '?cat=', $rewrite );\n $custom_rules[ $regex ] = $rewrite;\n }\n return $custom_rules;\n}\nadd_filter( 'category_rewrite_rules', 'numeric_category_rewrite_rules' );\n\nfunction numeric_category_link( $category_link, $term_id ) {\n global $wp_rewrite;\n if ( $wp_rewrite->using_permalinks() ) {\n $permastruct = $wp_rewrite->get_extra_permastruct( 'category' );\n $permastruct = str_replace( '%category%', $term_id, $permastruct );\n $category_link = home_url( user_trailingslashit( $permastruct, 'category' ) );\n }\n return $category_link;\n}\nadd_filter( 'category_link', 'numeric_category_link', 10, 2 );\n</code></pre>\n"
}
] | 2019/11/30 | [
"https://wordpress.stackexchange.com/questions/353659",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/179137/"
] | I want to change the article url as
```
www.***.com/post/%post_id%
```
For example,
```
www.***.com/post/156/
```
And now, I did it.
But I don't know how to change the category like this. For example,
```
www.***.com/category/12/
```
Generally, the category url is:
```
www.***.com/category/cat1/cat1.1/cat1.1.1/
```
I want to get:
```
www.***.com/category/cat1.1.1/
```
And now I want to only display the ID of the cat1.1.1, like:
```
www.***.com/category/12/ ( the id of cat1.1.1 is 12 )
``` | I find my answer on the internet.
```
function numeric_category_rewrite_rules( $rules ) {
$custom_rules = array();
foreach ( $rules as $regex => $rewrite ) {
$regex = str_replace( '/(.+?)/', '/([0-9]{1,})/', $regex );
$rewrite = str_replace( '?category_name=', '?cat=', $rewrite );
$custom_rules[ $regex ] = $rewrite;
}
return $custom_rules;
}
add_filter( 'category_rewrite_rules', 'numeric_category_rewrite_rules' );
function numeric_category_link( $category_link, $term_id ) {
global $wp_rewrite;
if ( $wp_rewrite->using_permalinks() ) {
$permastruct = $wp_rewrite->get_extra_permastruct( 'category' );
$permastruct = str_replace( '%category%', $term_id, $permastruct );
$category_link = home_url( user_trailingslashit( $permastruct, 'category' ) );
}
return $category_link;
}
add_filter( 'category_link', 'numeric_category_link', 10, 2 );
``` |
353,734 | <p>I really can't get the right practices from official docs. I think it's a complete mess.</p>
<p>At some point, they started to say to activate the title-tag feature: after_setup_theme ></p>
<pre><code>add_theme_support('title-tag');
</code></pre>
<ul>
<li><p>Ok. At this point they stated we should delete the <code><title></code> tag from page and stop using <code>wp_title()</code>. Perfect. </p></li>
<li><p>So we had to use the <code>'wp_title'</code> filter to modify our titles. Right. I did, that worked, once upon a time.</p></li>
<li><p>Then they said '<code>'wp_title'</code> filter was deprecated, and we should have used <code>pre_get_document_title</code> and other filters. Wow, great. Currently they seem not to work, though.</p></li>
<li><p>Then they said '<code>'wp_title'</code> filter was <em>'reinstated until alternative usages have been identified and a path forward for them defined'</em> Sexy.</p></li>
</ul>
<p>But if I look into the core code, I can see that the 'title-tag' has no filters to modify its output. So if I want custom coded texts inside my titles, should I use wp_title() again and disable 'title-tag' support?</p>
<p>Really, can someone shed a definitive light on this topic?</p>
| [
{
"answer_id": 353735,
"author": "Luca Reghellin",
"author_id": 10381,
"author_profile": "https://wordpress.stackexchange.com/users/10381",
"pm_score": -1,
"selected": false,
"text": "<p>As far as I can say, currently for me the best option is the old school <code>wp_title()</code> thing: that will work. So:</p>\n\n<ul>\n<li>Do not add <code>title-tag</code> theme sopport</li>\n<li>Keep your <code><title><?php wp_title([whatever options]) ?></title></code> on page</li>\n<li>If you need further customisations, feel free to use the <code>wp_title</code> filter > it's not deprecated and will correctly work.</li>\n</ul>\n\n<p>Until the next wp messy recommendations..</p>\n"
},
{
"answer_id": 353738,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 2,
"selected": false,
"text": "<p>Do you have any SEO plugins installed? They usually fiddle with this logic. Having Yoast enabled, the <code>pre_get_document_title</code> does not work for me, instead you should use <code>wpseo_title</code> <a href=\"https://yoast.com/wordpress/plugins/seo/api/\" rel=\"nofollow noreferrer\">per their documentation</a>.</p>\n\n<p>Having said that, with SEO plugins disabled and <code>add_theme_support('title-tag');</code> enabled, the <code>pre_get_document_title</code> filter works for me without any problem.</p>\n\n<pre><code>add_action('after_setup_theme', function () {\n add_theme_support('title-tag');\n}, 20);\n\nadd_filter('pre_get_document_title', function ($title) {\n return 'ORO!';\n});\n</code></pre>\n\n<p>Result is, that I see <code>ORO!</code> as the page title.</p>\n"
}
] | 2019/12/02 | [
"https://wordpress.stackexchange.com/questions/353734",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10381/"
] | I really can't get the right practices from official docs. I think it's a complete mess.
At some point, they started to say to activate the title-tag feature: after\_setup\_theme >
```
add_theme_support('title-tag');
```
* Ok. At this point they stated we should delete the `<title>` tag from page and stop using `wp_title()`. Perfect.
* So we had to use the `'wp_title'` filter to modify our titles. Right. I did, that worked, once upon a time.
* Then they said '`'wp_title'` filter was deprecated, and we should have used `pre_get_document_title` and other filters. Wow, great. Currently they seem not to work, though.
* Then they said '`'wp_title'` filter was *'reinstated until alternative usages have been identified and a path forward for them defined'* Sexy.
But if I look into the core code, I can see that the 'title-tag' has no filters to modify its output. So if I want custom coded texts inside my titles, should I use wp\_title() again and disable 'title-tag' support?
Really, can someone shed a definitive light on this topic? | Do you have any SEO plugins installed? They usually fiddle with this logic. Having Yoast enabled, the `pre_get_document_title` does not work for me, instead you should use `wpseo_title` [per their documentation](https://yoast.com/wordpress/plugins/seo/api/).
Having said that, with SEO plugins disabled and `add_theme_support('title-tag');` enabled, the `pre_get_document_title` filter works for me without any problem.
```
add_action('after_setup_theme', function () {
add_theme_support('title-tag');
}, 20);
add_filter('pre_get_document_title', function ($title) {
return 'ORO!';
});
```
Result is, that I see `ORO!` as the page title. |
353,742 | <p>While working with <code>ServerSideRender</code> wordpress gutenberg component, I am seeing the following notice.</p>
<p><code>wp.components.ServerSideRender is deprecated. Please use wp.serverSideRender instead.</code></p>
<p>Here is my test code:</p>
<pre><code>const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
const { Fragment } = wp.element;
const { InspectorControls } = wp.blockEditor;
const {
PanelBody, SelectControl, ServerSideRender, TextControl, ToggleControl,
} = wp.components;
registerBlockType( 'test-me/test-to-block', {
title: __( 'Test Me' ),
icon: 'shield',
category: 'common',
keywords: [
__( 'Test Me' ),
__( 'Test' ),
__( 'msbd' ),
],
attributes: {
adAlignment: {
type: 'string',
default: 'center-align',
},
isWrapper: {
type: 'boolean',
default: true,
},
},
edit: ( props ) => {
const { setAttributes, attributes } = props;
const { adAlignment, isWrapper } = attributes;
return (
<Fragment>
<div className={ `test-me ${ className }` }>
<ServerSideRender
block="test-me/test-to-block"
attributes={ attributes }
/>
</div>
</Fragment>
);
},
save: ( props ) => {
const { attributes, className = '' } = props;
return (
<div className={ `test-me ${ className }` }>
<ServerSideRender
block="test-me/test-to-block"
attributes={ attributes }
/>
</div>
);
},
} );
</code></pre>
<p>How to modify this script to work with new <code>wp.serverSideRender</code> component?</p>
| [
{
"answer_id": 353778,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 2,
"selected": false,
"text": "<p>This just means they moved the component. Replace this part:</p>\n\n<pre><code>const {\n PanelBody, SelectControl, ServerSideRender, TextControl, ToggleControl,\n} = wp.components;\n</code></pre>\n\n<p>with</p>\n\n<pre><code>const { serverSideRender } = wp;\nconst {\n PanelBody, SelectControl, TextControl, ToggleControl,\n} = wp.components;\n</code></pre>\n\n<p>Unless they've changed anything else about the component, the location you're importing it from should be the only update needed.</p>\n\n<p><strong>Be careful with the first letter of 'serverSideRender', lower case!!</strong></p>\n"
},
{
"answer_id": 353781,
"author": "Welcher",
"author_id": 27210,
"author_profile": "https://wordpress.stackexchange.com/users/27210",
"pm_score": 3,
"selected": false,
"text": "<p>The component is still functional, the issue is due to how it was pulled out into its own package. It is no longer uppercase and in order to use it in JSX, you will need to alias it:</p>\n\n<p><code>const { serverSideRender: ServerSideRender } = wp;</code></p>\n\n<p>See <a href=\"https://github.com/WordPress/gutenberg/pull/18722\" rel=\"noreferrer\">this issue</a> for more details.</p>\n"
}
] | 2019/12/02 | [
"https://wordpress.stackexchange.com/questions/353742",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130217/"
] | While working with `ServerSideRender` wordpress gutenberg component, I am seeing the following notice.
`wp.components.ServerSideRender is deprecated. Please use wp.serverSideRender instead.`
Here is my test code:
```
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
const { Fragment } = wp.element;
const { InspectorControls } = wp.blockEditor;
const {
PanelBody, SelectControl, ServerSideRender, TextControl, ToggleControl,
} = wp.components;
registerBlockType( 'test-me/test-to-block', {
title: __( 'Test Me' ),
icon: 'shield',
category: 'common',
keywords: [
__( 'Test Me' ),
__( 'Test' ),
__( 'msbd' ),
],
attributes: {
adAlignment: {
type: 'string',
default: 'center-align',
},
isWrapper: {
type: 'boolean',
default: true,
},
},
edit: ( props ) => {
const { setAttributes, attributes } = props;
const { adAlignment, isWrapper } = attributes;
return (
<Fragment>
<div className={ `test-me ${ className }` }>
<ServerSideRender
block="test-me/test-to-block"
attributes={ attributes }
/>
</div>
</Fragment>
);
},
save: ( props ) => {
const { attributes, className = '' } = props;
return (
<div className={ `test-me ${ className }` }>
<ServerSideRender
block="test-me/test-to-block"
attributes={ attributes }
/>
</div>
);
},
} );
```
How to modify this script to work with new `wp.serverSideRender` component? | The component is still functional, the issue is due to how it was pulled out into its own package. It is no longer uppercase and in order to use it in JSX, you will need to alias it:
`const { serverSideRender: ServerSideRender } = wp;`
See [this issue](https://github.com/WordPress/gutenberg/pull/18722) for more details. |
353,764 | <p>I need to have the client's theme colors here so he doesn't have to remember the color codes each time he's using them. </p>
<p><a href="https://i.stack.imgur.com/gJ0PN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gJ0PN.png" alt="enter image description here"></a>
Is </p>
<p>is there any way to Add/Remove/Change some colors from the default "Paragraph" block color settings side panel?</p>
<p>Thank you in advance!</p>
| [
{
"answer_id": 353769,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 2,
"selected": true,
"text": "<p>Rather than adjusting the default palette, you can define (and enforce) a custom palette.</p>\n\n<pre><code><?php\n// Add a custom palette\nadd_action( 'after_setup_theme', 'wpse_block_color_palette' );\nfunction wpse_block_color_palette() {\n add_theme_support(\n // Define the colors\n 'editor-color-palette', array(\n // First color - black\n array(\n 'name' => esc_html__( 'Black', 'textdomain' ),\n 'slug' => 'black',\n 'color' => '#2a2a2a',\n ),\n // Second color - blue\n array(\n 'name' => esc_html__( 'Blue', 'textdomain' ),\n 'slug' => 'blue',\n 'color' => '#0000ff',\n )\n // And so on and so forth\n )\n );\n}\n?>\n</code></pre>\n\n<p>You'll then want to add styling for the classes they'll generate. The palette applies to any block with core styling, which boils down to \"has-(slug)-background-color\" and \"has-(slug)-color\".</p>\n\n<pre><code>.has-black-background-color {\n background-color: #000;\n }\n.has-black-color {\n color: #000;\n}\n.has-blue-background-color {\n background-color: #00f;\n}\n.has-blue-color {\n color: #00f;\n}\n</code></pre>\n"
},
{
"answer_id": 367747,
"author": "Ooker",
"author_id": 64282,
"author_profile": "https://wordpress.stackexchange.com/users/64282",
"pm_score": 0,
"selected": false,
"text": "<p>You can use a color palette plugin. Here is a google search for the query <a href=\"https://www.google.com/search?client=firefox-b-d&q=+WordPress+palette\" rel=\"nofollow noreferrer\" title=\"WordPress palette - Google Search\"><code>WordPress palette</code></a></p>\n"
}
] | 2019/12/02 | [
"https://wordpress.stackexchange.com/questions/353764",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115614/"
] | I need to have the client's theme colors here so he doesn't have to remember the color codes each time he's using them.
[](https://i.stack.imgur.com/gJ0PN.png)
Is
is there any way to Add/Remove/Change some colors from the default "Paragraph" block color settings side panel?
Thank you in advance! | Rather than adjusting the default palette, you can define (and enforce) a custom palette.
```
<?php
// Add a custom palette
add_action( 'after_setup_theme', 'wpse_block_color_palette' );
function wpse_block_color_palette() {
add_theme_support(
// Define the colors
'editor-color-palette', array(
// First color - black
array(
'name' => esc_html__( 'Black', 'textdomain' ),
'slug' => 'black',
'color' => '#2a2a2a',
),
// Second color - blue
array(
'name' => esc_html__( 'Blue', 'textdomain' ),
'slug' => 'blue',
'color' => '#0000ff',
)
// And so on and so forth
)
);
}
?>
```
You'll then want to add styling for the classes they'll generate. The palette applies to any block with core styling, which boils down to "has-(slug)-background-color" and "has-(slug)-color".
```
.has-black-background-color {
background-color: #000;
}
.has-black-color {
color: #000;
}
.has-blue-background-color {
background-color: #00f;
}
.has-blue-color {
color: #00f;
}
``` |
353,776 | <p>I want to disable rss feed,my wordpress version is <strong>5.2.4</strong>.</p>
<p>see my code below to disable rss feed.</p>
<pre><code> function itsme_disable_feed() {
wp_die( __( 'No feed available' ) );
}
add_action('do_feed', 'itsme_disable_feed', 1);
add_action('do_feed_rdf', 'itsme_disable_feed', 1);
add_action('do_feed_rss', 'itsme_disable_feed', 1);
add_action('do_feed_rss2', 'itsme_disable_feed', 1);
add_action('do_feed_atom', 'itsme_disable_feed', 1);
add_action('do_feed_rss2_comments', 'itsme_disable_feed', 1);
add_action('do_feed_atom_comments', 'itsme_disable_feed', 1);
</code></pre>
<p>By the book,the feed page will show wp_die page.But it didn`t show it Expectantly.</p>
<p>It shows this,see the screenshot,and I don`t know how to solve it.</p>
<p><a href="https://i.stack.imgur.com/HtbXA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HtbXA.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 353789,
"author": "Eoin H",
"author_id": 86679,
"author_profile": "https://wordpress.stackexchange.com/users/86679",
"pm_score": 1,
"selected": false,
"text": "<p>have you tried using remove_action?</p>\n\n<p>Example:</p>\n\n<pre><code><?php\nadd_action('wp_head', 'remove_feeds_in_head', 1);\n\nfunction remove_feeds_in_head() {\n remove_action( 'wp_head', 'feed_links', 2 );\n remove_action( 'wp_head', 'feed_links_extra', 3 );\n}\n</code></pre>\n\n<p>EDIT: So disabling them doesn't remove them, to completely get rid of them, them you need to use remove_action aswell. Assuming this is what you want to do.</p>\n\n<p>\n\n<pre><code>add_action('do_feed', 'itsme_disable_feed', 1);\nadd_action('do_feed_rdf', 'itsme_disable_feed', 1);\nadd_action('do_feed_rss', 'itsme_disable_feed', 1);\nadd_action('do_feed_rss2', 'itsme_disable_feed', 1);\nadd_action('do_feed_atom', 'itsme_disable_feed', 1);\nadd_action('do_feed_rss2_comments', 'itsme_disable_feed', 1);\nadd_action('do_feed_atom_comments', 'itsme_disable_feed', 1);\n\nremove_action( 'wp_head', 'feed_links', 2 );\nremove_action( 'wp_head', 'feed_links_extra', 3 );\nremove_action('wp_head', 'rsd_link');\n// Add whatever other things you want to remove\n</code></pre>\n"
},
{
"answer_id": 381502,
"author": "sanjay ojha",
"author_id": 109152,
"author_profile": "https://wordpress.stackexchange.com/users/109152",
"pm_score": 2,
"selected": false,
"text": "<p>You need to define the HTTP Response code in <code>wp_die</code> function.</p>\n<pre class=\"lang-php prettyprint-override\"><code>wp_die( __('No feed available'), '', 404 );\n</code></pre>\n<p>Also set custom header to get HTML page instead of xml page. So the code should be like below.</p>\n<pre class=\"lang-php prettyprint-override\"><code>function itsme_disable_feed() {\n global $wp_query;\n $wp_query->is_feed = false;\n $wp_query->set_404();\n status_header( 404 );\n nocache_headers();\n wp_die( __('No feed available'), '', 404 );\n}\n</code></pre>\n"
}
] | 2019/12/02 | [
"https://wordpress.stackexchange.com/questions/353776",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157283/"
] | I want to disable rss feed,my wordpress version is **5.2.4**.
see my code below to disable rss feed.
```
function itsme_disable_feed() {
wp_die( __( 'No feed available' ) );
}
add_action('do_feed', 'itsme_disable_feed', 1);
add_action('do_feed_rdf', 'itsme_disable_feed', 1);
add_action('do_feed_rss', 'itsme_disable_feed', 1);
add_action('do_feed_rss2', 'itsme_disable_feed', 1);
add_action('do_feed_atom', 'itsme_disable_feed', 1);
add_action('do_feed_rss2_comments', 'itsme_disable_feed', 1);
add_action('do_feed_atom_comments', 'itsme_disable_feed', 1);
```
By the book,the feed page will show wp\_die page.But it didn`t show it Expectantly.
It shows this,see the screenshot,and I don`t know how to solve it.
[](https://i.stack.imgur.com/HtbXA.png) | You need to define the HTTP Response code in `wp_die` function.
```php
wp_die( __('No feed available'), '', 404 );
```
Also set custom header to get HTML page instead of xml page. So the code should be like below.
```php
function itsme_disable_feed() {
global $wp_query;
$wp_query->is_feed = false;
$wp_query->set_404();
status_header( 404 );
nocache_headers();
wp_die( __('No feed available'), '', 404 );
}
``` |
353,785 | <p>WordPress is amazing and I am a very big fan of it.</p>
<p>But the version 5.3 brought me (an many others, <a href="https://wordpress.org/support/topic/unable-to-upload-images-67/" rel="nofollow noreferrer">1</a>, <a href="https://wordpress.org/support/topic/cant-upload-to-media-library-4/" rel="nofollow noreferrer">2</a>, <a href="https://stackoverflow.com/questions/58849039/wordpress-image-upload-time-error-post-processing-of-the-image-failed">3</a>, <a href="https://wppathfinder.com/post-processing-of-the-image-failed/" rel="nofollow noreferrer">4</a>...) a big problem with its new forced feature for auto-scaling down big images.</p>
<p>I am trying to disable it (because I do not need/want it and because it is not working) with the following filter:</p>
<pre><code>add_filter( 'big_image_size_threshold', '__return_false' );
</code></pre>
<p>Where the callback function __return_false() is just a WordPress wrapper function to return <em>false</em>.</p>
<p>But it is not working, I still get an error, which means the feature is not disabled.</p>
<p>Same happens with <a href="https://wordpress.org/plugins/disable-big-image-threshold/" rel="nofollow noreferrer">the recommended plugin</a>. It's not fixing the error.</p>
<p><strong>What error?</strong>: Postprocessing failed, please scale your image under 2500px.</p>
<p>I did clean the browser cache, set PHP version to 7.2 and activated mbstring (<a href="https://stackoverflow.com/questions/58849039/wordpress-image-upload-time-error-post-processing-of-the-image-failed">as suggested by others</a> regarding the same problem).</p>
<p><strong>The error happens for some uploads, not for all of them</strong>:</p>
<p>And it has nothing to do with uploading big images.</p>
<p>Here are a few facts describing the issue:</p>
<ul>
<li>I am doing random screenshots of random areas (means random sizes).</li>
<li>I am always doing small rectangles (max 800px x 400px)</li>
<li>Some images will upload fine.</li>
<li>Other images will not.</li>
<li>But the specific images that work always work if I retry uploading several times.</li>
<li>And the specific images that don't always don't if I retry uploading several times (even when renamig the file).</li>
</ul>
| [
{
"answer_id": 353815,
"author": "user3135691",
"author_id": 59755,
"author_profile": "https://wordpress.stackexchange.com/users/59755",
"pm_score": -1,
"selected": false,
"text": "<p>You need to remove the quotes around '__return_false'.</p>\n\n<pre><code><?php\n// Remove the quotes around __return_false\nadd_filter( 'big_image_size_threshold', __return_false); \n</code></pre>\n\n<p>You are giving the function a string, hence the filter is not executing.</p>\n"
},
{
"answer_id": 356242,
"author": "Pitchpole",
"author_id": 180718,
"author_profile": "https://wordpress.stackexchange.com/users/180718",
"pm_score": 1,
"selected": false,
"text": "<p>I have the same issue with not being able to turn off big_image_size_threshold (one of the worst new features WordPress has ever put out) for kicks I tried removing the quotes around return false but it doesn't resolve the issue. The example in Codex does in fact show quotes. <a href=\"https://codex.wordpress.org/Function_Reference/_return_false\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/_return_false</a></p>\n\n<p>I have opened a ticket in core tracker for this, possible bug.</p>\n"
},
{
"answer_id": 365188,
"author": "Álvaro Franz",
"author_id": 155394,
"author_profile": "https://wordpress.stackexchange.com/users/155394",
"pm_score": 2,
"selected": true,
"text": "<p>Now it is working as expected <em>(disabled scaling)</em>, under the following settings:</p>\n\n<p>In my theme <strong>functions.php</strong></p>\n\n<pre><code>add_filter( 'big_image_size_threshold', '__return_false' );\n</code></pre>\n\n<p>In the <strong>WP Media Settings</strong>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/CgKQr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CgKQr.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 382309,
"author": "ZeroGravity",
"author_id": 141006,
"author_profile": "https://wordpress.stackexchange.com/users/141006",
"pm_score": 1,
"selected": false,
"text": "<p>I found a client's site where the filter wasn't working. I did a lot of testing on a sandbox site and the filter worked. The website in question is using the Avada theme. Avada has the threshold size built into the theme settings so you can customize what size you would like the scaled image to be. This was overriding where I was trying turn it off in my core plugin.</p>\n<p>I first tried adding a priority to the add_filter of 9999 so it would hopefully run later but this doesn't seem to work in this instance (I'm still testing this). I set the threshold size to 0 in Avada and it successfully turned the big image scaling off.</p>\n<p>I suggest try adding a priority to see if that helps. If not search the theme and the plugins to see if it is being set there. I know this can be difficult on a live site but I would try using one of the WP default themes and deactivating all the plugins to see if it works. Then reactivate the theme and plugins 1 by 1 to see if there is one causing the issue.</p>\n<p>I have used this plugin to test this type of thing on live sites, <a href=\"https://wordpress.org/plugins/wp-staging\" rel=\"nofollow noreferrer\">WP-Staging</a></p>\n<p>To remove the other sizes I found it wasn't enough to set the filter, you also need to unset the new sizes.</p>\n<pre><code>// Remove images sizes\nfunction zgwd1010_filter_image_sizes( $sizes) {\n unset( $sizes['1536x1536']); // disable 2x medium-large size\n unset( $sizes['2048x2048']); // disable 2x large size\n return $sizes;\n}\nadd_filter('intermediate_image_sizes_advanced', 'zgwd1010_filter_image_sizes');\n</code></pre>\n"
},
{
"answer_id": 388744,
"author": "Garconis",
"author_id": 91826,
"author_profile": "https://wordpress.stackexchange.com/users/91826",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know why the <code>__return_false</code> doesns't work, but something like this does:</p>\n<pre><code>function gc_big_image_size_threshold( $threshold ) {\n return 9999; // new threshold\n}\nadd_filter('big_image_size_threshold', 'gc_big_image_size_threshold', 100, 1);\n</code></pre>\n"
}
] | 2019/12/02 | [
"https://wordpress.stackexchange.com/questions/353785",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155394/"
] | WordPress is amazing and I am a very big fan of it.
But the version 5.3 brought me (an many others, [1](https://wordpress.org/support/topic/unable-to-upload-images-67/), [2](https://wordpress.org/support/topic/cant-upload-to-media-library-4/), [3](https://stackoverflow.com/questions/58849039/wordpress-image-upload-time-error-post-processing-of-the-image-failed), [4](https://wppathfinder.com/post-processing-of-the-image-failed/)...) a big problem with its new forced feature for auto-scaling down big images.
I am trying to disable it (because I do not need/want it and because it is not working) with the following filter:
```
add_filter( 'big_image_size_threshold', '__return_false' );
```
Where the callback function \_\_return\_false() is just a WordPress wrapper function to return *false*.
But it is not working, I still get an error, which means the feature is not disabled.
Same happens with [the recommended plugin](https://wordpress.org/plugins/disable-big-image-threshold/). It's not fixing the error.
**What error?**: Postprocessing failed, please scale your image under 2500px.
I did clean the browser cache, set PHP version to 7.2 and activated mbstring ([as suggested by others](https://stackoverflow.com/questions/58849039/wordpress-image-upload-time-error-post-processing-of-the-image-failed) regarding the same problem).
**The error happens for some uploads, not for all of them**:
And it has nothing to do with uploading big images.
Here are a few facts describing the issue:
* I am doing random screenshots of random areas (means random sizes).
* I am always doing small rectangles (max 800px x 400px)
* Some images will upload fine.
* Other images will not.
* But the specific images that work always work if I retry uploading several times.
* And the specific images that don't always don't if I retry uploading several times (even when renamig the file). | Now it is working as expected *(disabled scaling)*, under the following settings:
In my theme **functions.php**
```
add_filter( 'big_image_size_threshold', '__return_false' );
```
In the **WP Media Settings**:
[](https://i.stack.imgur.com/CgKQr.png) |
353,845 | <p>I don't know why, but now, Wordpress is adding a suffix "-scaled" at the end of each newly uploaded image.</p>
<p><a href="https://i.stack.imgur.com/Di2gL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Di2gL.png" alt="enter image description here"></a></p>
<p>And, instead of keeping the original image link, it changes it to the "-scaled" version:</p>
<p><a href="https://i.stack.imgur.com/kwDZn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kwDZn.png" alt="enter image description here"></a></p>
<p>I found the culprit in <code>/wp-admin/includes/image.php</code> which has this:</p>
<pre><code> if ( ! is_wp_error( $resized ) ) {
// Append "-scaled" to the image file name. It will look like "my_image-scaled.jpg".
// This doesn't affect the sub-sizes names as they are generated from the original image (for best quality).
$saved = $editor->save( $editor->generate_filename( 'scaled' ) );
</code></pre>
<p>How to get rid of this behavior?</p>
| [
{
"answer_id": 354318,
"author": "Ivan Ivan",
"author_id": 179574,
"author_profile": "https://wordpress.stackexchange.com/users/179574",
"pm_score": 1,
"selected": false,
"text": "<p>This plugin helped me: <a href=\"https://wordpress.org/plugins/wp-smushit/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-smushit/</a>\nIt allows to make max size of images larger than 2560x2560. </p>\n\n<p>After installing go to Bulk Smush's settings and there toggle on \"Resize my full size images\". I just set Max width and height 9999x9999</p>\n\n<p>As a result suffix \"-scaled\" won't be added anymore.</p>\n\n<p>PS I found one more plugin with the similar purpose, but didn't check it since the first helped: <a href=\"https://wordpress.org/plugins/disable-big-image-threshold/\" rel=\"nofollow noreferrer\">Disable \"BIG Image\" Threshold</a></p>\n\n<p>To learn more about the cause go to: <a href=\"https://make.wordpress.org/core/2019/10/09/introducing-handling-of-big-images-in-wordpress-5-3/\" rel=\"nofollow noreferrer\">https://make.wordpress.org/core/2019/10/09/introducing-handling-of-big-images-in-wordpress-5-3/</a></p>\n"
},
{
"answer_id": 388518,
"author": "ericek111",
"author_id": 175203,
"author_profile": "https://wordpress.stackexchange.com/users/175203",
"pm_score": 2,
"selected": false,
"text": "<h3>How to disable this behaviour?</h3>\n<p>Add this to your <code>functions.php</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'big_image_size_threshold', '__return_false' );\n</code></pre>\n<h3>How does it work?</h3>\n<p>When a new image is uploaded, WordPress will detect if it is a “big” image by checking if its height or width exceeds the big_image threshold. The default threshold value is <strong>2560px</strong>, filterable with the new <a href=\"https://developer.wordpress.org/reference/hooks/big_image_size_threshold/\" rel=\"nofollow noreferrer\"><code>big_image_size_threshold</code></a> filter.</p>\n<p>If the image's height or width is above this threshold, it will be scaled down, with the threshold being used for maximum height and max. width value. The scaled down image will be used as the largest available size.</p>\n<p>In this case, the original image file is stored in the uploads directory and its name is stored in another array key in the <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_metadata/\" rel=\"nofollow noreferrer\">image meta array</a>: original_image. To be able to always get the path to an originally uploaded image a new function <a href=\"https://developer.wordpress.org/reference/functions/wp_get_original_image_path/\" rel=\"nofollow noreferrer\"><code>wp_get_original_image_path()</code></a> was introduced.</p>\n<p>Source: <a href=\"https://make.wordpress.org/core/2019/10/09/introducing-handling-of-big-images-in-wordpress-5-3/\" rel=\"nofollow noreferrer\">Introducing handling of big images in WordPress 5.3 by Justin Ahinon</a></p>\n"
}
] | 2019/12/03 | [
"https://wordpress.stackexchange.com/questions/353845",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143330/"
] | I don't know why, but now, Wordpress is adding a suffix "-scaled" at the end of each newly uploaded image.
[](https://i.stack.imgur.com/Di2gL.png)
And, instead of keeping the original image link, it changes it to the "-scaled" version:
[](https://i.stack.imgur.com/kwDZn.png)
I found the culprit in `/wp-admin/includes/image.php` which has this:
```
if ( ! is_wp_error( $resized ) ) {
// Append "-scaled" to the image file name. It will look like "my_image-scaled.jpg".
// This doesn't affect the sub-sizes names as they are generated from the original image (for best quality).
$saved = $editor->save( $editor->generate_filename( 'scaled' ) );
```
How to get rid of this behavior? | ### How to disable this behaviour?
Add this to your `functions.php`:
```php
add_filter( 'big_image_size_threshold', '__return_false' );
```
### How does it work?
When a new image is uploaded, WordPress will detect if it is a “big” image by checking if its height or width exceeds the big\_image threshold. The default threshold value is **2560px**, filterable with the new [`big_image_size_threshold`](https://developer.wordpress.org/reference/hooks/big_image_size_threshold/) filter.
If the image's height or width is above this threshold, it will be scaled down, with the threshold being used for maximum height and max. width value. The scaled down image will be used as the largest available size.
In this case, the original image file is stored in the uploads directory and its name is stored in another array key in the [image meta array](https://developer.wordpress.org/reference/functions/wp_get_attachment_metadata/): original\_image. To be able to always get the path to an originally uploaded image a new function [`wp_get_original_image_path()`](https://developer.wordpress.org/reference/functions/wp_get_original_image_path/) was introduced.
Source: [Introducing handling of big images in WordPress 5.3 by Justin Ahinon](https://make.wordpress.org/core/2019/10/09/introducing-handling-of-big-images-in-wordpress-5-3/) |
353,865 | <p>The <code>wp_mail()</code> function is not running when scheduled in a cron function. I have added the following function: </p>
<pre><code>add_filter( 'cron_schedules', 'isa_add_every_one_minutes' );
function isa_add_every_one_minutes( $schedules ) {
$schedules['every_sixty_seconds'] = array(
'interval' => 60,
'display' => __( 'Every 1 Minutes', 'textdomain' )
);
return $schedules;
}
// Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'isa_add_every_one_minutes' ) ) {
wp_schedule_event( time(), 'every_sixty_seconds', 'isa_add_every_one_minutes' );
}
// Hook into that action that'll fire every three minutes
add_action( 'isa_add_every_one_minutes', 'only_debug_admin' );
function only_debug_admin(){
$message = "Test message";
wp_mail( '[email protected]', $message, $message );
update_option('default_role','customer');
}
</code></pre>
<p>When I run the cron manually via wp-control plugin, I receive a mail and wp-mail works fine. However, when the cron job is run. To debug, I add this line below the mail function:</p>
<pre><code>update_option('default_role','customer');
</code></pre>
<p>I set the default role to subscriber in WordPress settings. On cron run, the setting gets updated to 'customer' but the mail is not received. On manually running the function, the mail is received. Any idea why this is happening? </p>
| [
{
"answer_id": 353906,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 2,
"selected": false,
"text": "<p>This one is a bit of a puzzler. I was originally going to say you need to determine if there's something wrong <em>after</em> the mail is sent since you're getting the hit in the next operation. But then I re-read it and caught the part about the email being received when it's run manually.</p>\n\n<p>What you need to do is find out if there's an error occurring. Since it's not a manual process, that's not quite straight forward; but there are ways to do it. This answer won't specifically <strong>solve</strong> the problem you're having, but it should give you way to determine what that issue actually is.</p>\n\n<p>I would set up to catch any errors and then log them. You can do that by making sure WP is set up for debugging and to log any errors. Make sure the following is in your wp-config.php:</p>\n\n<pre><code>define( 'WP_DEBUG', true );\ndefine( 'WP_DEBUG_LOG', true );\n</code></pre>\n\n<p>Now you can use WP's <code>error_log()</code> function to write any errors to the log file.</p>\n\n<p><code>wp_mail()</code> returns a true|false boolean when run. If there are any errors, it will return false. So we can write to the log depending on the result.</p>\n\n<p>So in your function, write the to the error log based on the returned result. </p>\n\n<pre><code>function only_debug_admin(){\n $message = \"Test message\";\n\n $wp_mail_result = wp_mail( '[email protected]', $message, $message );\n\n if ( true === $wp_mail_result ) {\n error_log( 'wp_mail returned true!' );\n } else {\n error_log( 'wp_mail had an error!' );\n }\n}\n</code></pre>\n\n<p>If <code>wp_mail()</code> errors (returns false), then you want to be able to capture any errors in <code>phpMailer</code> to see if that gives you any insight as to why.</p>\n\n<pre><code>add_action( 'phpmailer_init', 'my_log_phpmailer_init' );\nfunction my_log_phpmailer_init( $phpmailer ) {\n error_log( print_r( $phpmailer, true ) );\n}\n</code></pre>\n\n<p>Now when the cron runs, you can check the error log (/wp-content/debug.log) for what happened. If <code>wp_mail()</code> returned true, the issue is an email issue with either the sending host or the receiver (outside of WP). If it was false, review the errors from phpMailer (which should also be in the log).</p>\n\n<p>This doesn't <strong>solve</strong> your problem, but it gets you on track to figure out what it actually is.</p>\n"
},
{
"answer_id": 401158,
"author": "zabatonni",
"author_id": 101690,
"author_profile": "https://wordpress.stackexchange.com/users/101690",
"pm_score": 0,
"selected": false,
"text": "<p>This is really common when using CLI to run cron jobs (preferred). Wordpress uses PHPMailer and it tries to get SERVER_NAME from $_SERVER variable which is not defined and then it tries few callbacks, resulting in not valid email address. Easiest hacky fix I can think of, define it for example in your wp-config.php</p>\n<pre><code>if(empty($_SERVER['SERVER_NAME'])) $_SERVER['SERVER_NAME']='www.yourdomain.tld';\n</code></pre>\n"
}
] | 2019/12/03 | [
"https://wordpress.stackexchange.com/questions/353865",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142821/"
] | The `wp_mail()` function is not running when scheduled in a cron function. I have added the following function:
```
add_filter( 'cron_schedules', 'isa_add_every_one_minutes' );
function isa_add_every_one_minutes( $schedules ) {
$schedules['every_sixty_seconds'] = array(
'interval' => 60,
'display' => __( 'Every 1 Minutes', 'textdomain' )
);
return $schedules;
}
// Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'isa_add_every_one_minutes' ) ) {
wp_schedule_event( time(), 'every_sixty_seconds', 'isa_add_every_one_minutes' );
}
// Hook into that action that'll fire every three minutes
add_action( 'isa_add_every_one_minutes', 'only_debug_admin' );
function only_debug_admin(){
$message = "Test message";
wp_mail( '[email protected]', $message, $message );
update_option('default_role','customer');
}
```
When I run the cron manually via wp-control plugin, I receive a mail and wp-mail works fine. However, when the cron job is run. To debug, I add this line below the mail function:
```
update_option('default_role','customer');
```
I set the default role to subscriber in WordPress settings. On cron run, the setting gets updated to 'customer' but the mail is not received. On manually running the function, the mail is received. Any idea why this is happening? | This one is a bit of a puzzler. I was originally going to say you need to determine if there's something wrong *after* the mail is sent since you're getting the hit in the next operation. But then I re-read it and caught the part about the email being received when it's run manually.
What you need to do is find out if there's an error occurring. Since it's not a manual process, that's not quite straight forward; but there are ways to do it. This answer won't specifically **solve** the problem you're having, but it should give you way to determine what that issue actually is.
I would set up to catch any errors and then log them. You can do that by making sure WP is set up for debugging and to log any errors. Make sure the following is in your wp-config.php:
```
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
```
Now you can use WP's `error_log()` function to write any errors to the log file.
`wp_mail()` returns a true|false boolean when run. If there are any errors, it will return false. So we can write to the log depending on the result.
So in your function, write the to the error log based on the returned result.
```
function only_debug_admin(){
$message = "Test message";
$wp_mail_result = wp_mail( '[email protected]', $message, $message );
if ( true === $wp_mail_result ) {
error_log( 'wp_mail returned true!' );
} else {
error_log( 'wp_mail had an error!' );
}
}
```
If `wp_mail()` errors (returns false), then you want to be able to capture any errors in `phpMailer` to see if that gives you any insight as to why.
```
add_action( 'phpmailer_init', 'my_log_phpmailer_init' );
function my_log_phpmailer_init( $phpmailer ) {
error_log( print_r( $phpmailer, true ) );
}
```
Now when the cron runs, you can check the error log (/wp-content/debug.log) for what happened. If `wp_mail()` returned true, the issue is an email issue with either the sending host or the receiver (outside of WP). If it was false, review the errors from phpMailer (which should also be in the log).
This doesn't **solve** your problem, but it gets you on track to figure out what it actually is. |
353,867 | <p>I want to create a custom category page, only for the first page, displaying an article, related posts, latest posts. How can I do that? </p>
| [
{
"answer_id": 353871,
"author": "Steffen Görg",
"author_id": 131265,
"author_profile": "https://wordpress.stackexchange.com/users/131265",
"pm_score": 2,
"selected": false,
"text": "<p>I don´t think you can do this within the template overwrite structure of wordpress but you can include a custom template based on the pagination number. </p>\n\n<pre><code>if(get_query_var('paged') == 0){\n echo \"Include your custom theme here\";\n}else{\n echo \"standard\";\n}\n</code></pre>\n"
},
{
"answer_id": 353997,
"author": "juniorbra",
"author_id": 176650,
"author_profile": "https://wordpress.stackexchange.com/users/176650",
"pm_score": 0,
"selected": false,
"text": "<p>The solution I found was using category description field in Wordpress to create a custom page, and limit the number os posts in the first page of some categories for 8, keeping 16 on the remaining pages</p>\n\n<pre><code> add_action( 'pre_get_posts', function( $query ) {\n if ( ! is_main_query() || is_admin() ) {\n return;\n }\n\n if ( ! is_paged() && is_category(array (2 , 3) )) {\n $query->set( 'posts_per_page', 8 );\n }\n} );\n</code></pre>\n"
}
] | 2019/12/03 | [
"https://wordpress.stackexchange.com/questions/353867",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/176650/"
] | I want to create a custom category page, only for the first page, displaying an article, related posts, latest posts. How can I do that? | I don´t think you can do this within the template overwrite structure of wordpress but you can include a custom template based on the pagination number.
```
if(get_query_var('paged') == 0){
echo "Include your custom theme here";
}else{
echo "standard";
}
``` |
353,869 | <p>I want to put this:</p>
<pre><code>[products ids="17,32,12,1,57"]
</code></pre>
<p>And I want them to display in EXACTLY this order. </p>
<p>Is this possible?</p>
| [
{
"answer_id": 353870,
"author": "Steffen Görg",
"author_id": 131265,
"author_profile": "https://wordpress.stackexchange.com/users/131265",
"pm_score": -1,
"selected": false,
"text": "<p>Have you tried to use the \norderby=\"menu_order\"\nparameter in the shortcode? You can set the menu order inside each pruduct.</p>\n"
},
{
"answer_id": 353880,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <code>woocommerce_shortcode_products_query</code> filter to change <code>orderby</code> argument. it will set <code>orderby</code> as <code>post__in</code> in <code>[products]</code> shortcode query. I have tested and it is working fine for me. you can take reference from below code and adjust code as per your need. Let me know if this works for you!</p>\n\n<pre><code>add_filter( 'woocommerce_shortcode_products_query', 'woocommerce_shortcode_products_orderby_post_in' );\nfunction woocommerce_shortcode_products_orderby_post_in( $args ) {\n if( isset( $args['orderby'] ) ) {\n $args['orderby'] = 'post__in'; \n }\n return $args;\n}\n</code></pre>\n"
}
] | 2019/12/03 | [
"https://wordpress.stackexchange.com/questions/353869",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/14825/"
] | I want to put this:
```
[products ids="17,32,12,1,57"]
```
And I want them to display in EXACTLY this order.
Is this possible? | You can use `woocommerce_shortcode_products_query` filter to change `orderby` argument. it will set `orderby` as `post__in` in `[products]` shortcode query. I have tested and it is working fine for me. you can take reference from below code and adjust code as per your need. Let me know if this works for you!
```
add_filter( 'woocommerce_shortcode_products_query', 'woocommerce_shortcode_products_orderby_post_in' );
function woocommerce_shortcode_products_orderby_post_in( $args ) {
if( isset( $args['orderby'] ) ) {
$args['orderby'] = 'post__in';
}
return $args;
}
``` |
353,929 | <p>Is there a function that would return the equivalent of <code>plugin_dir_path</code> but it being agnostic of a plugin / theme? JS scripts need to be enqueued as resources, as such, you cannot include their on-server path which is, say <code>/var/www/html/wordpress/thing/thing2/script.js</code>, it needs to be the <code>http://www.example.com/thing/thing2/script.js</code> counterpart.</p>
| [
{
"answer_id": 353932,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 1,
"selected": false,
"text": "<p>This is kind of a hacky way to do this; but unfortunately, there is not a WP function that will do both (theme and/or plugin). It's only an either/or proposition.</p>\n\n<p>On the surface, you'd think it wouldn't be difficult. You could just get the path and compare it with the site URL or something like that. But you run into problems when WP is installed somewhere other than the root (such as in a directory).</p>\n\n<p>If you look at my setup in the function, the \"else\" condition is the simple. If WP was always in the root, that would be all you need to do. Everything else is done to handle the other possibility (that WP is in a directory - or lower).</p>\n\n<p>In that case, it explodes the site URL to determine if there is more than just the root domain (an array bigger than 3). If so, it loops through the parts of the URL we got from the <code>explode()</code> process. We can skip the first three elements of the array as those should be the root of the domain (<a href=\"https://example.com\" rel=\"nofollow noreferrer\">https://example.com</a>). Then it builds the path (in case it's more than just one directory below).</p>\n\n<p>Using that it strips out everything below the root URL so you get just a clean URL you can use. Then it appends the path to the file.</p>\n\n<pre><code>function my_get_file_url_path() {\n\n // Account for WP being installed in a directory.\n $path_info = '';\n $site_url = site_url();\n $url_parts = explode( '/', $site_url );\n\n if ( array_count_values( $url_parts ) > 3 ) {\n $x = 0;\n foreach ( $url_parts as $this_part ) {\n if ( $x > 2 ) {\n $path_info = $this_part . '/';\n }\n $x++;\n }\n\n $site_actual_url = str_replace( $path_info, '', trailingslashit( $site_url ) );\n\n return $site_actual_url . trim( str_replace( $_SERVER['DOCUMENT_ROOT'], '', __DIR__ ), '/' );\n\n } else {\n return str_replace( $_SERVER['DOCUMENT_ROOT'], $site_url, __DIR__ );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 353979,
"author": "Daniel Smith",
"author_id": 177618,
"author_profile": "https://wordpress.stackexchange.com/users/177618",
"pm_score": 2,
"selected": true,
"text": "<p>Although @butlerblog's answer works, I find it unecessarily complex. I've checked above and beyond, <code>site_url</code> will always give you the current site's link, it will resolve the schemas for you, whether or not it's <code>http</code> or <code>https</code>, etc and as such, there's no issues with it.</p>\n\n<p>I've written a simpler, easier to understand function:</p>\n\n<pre><code>/**\n * Retrieves the full front-facing URL for a given path. In other words, it transforms an absolute path\n * into an URI.\n *\n * Note: when allowing direct access to your files, if there is any I/O (there shouldn't be, but, you know) operations,\n * you must check whether or not ABSPATH is defined.\n *\n * @see https://stackoverflow.com/a/44857254/12297763\n *\n * @param string $from An absolute path. You can just call this function with the parameter __FILE__ and it will give you a front-facing URI for that file.\n * @param boolean $strict Flag that the function uses to see if it needs to do additional checks.\n *\n * @return string|false Returns a string in the form of an URI if all checks were passed or False if checks failed.\n */\nfunction getURIFromPath( $from, $strict = False )\n{\n if( $strict ) {\n if( !\\file_exists( $from ) ) {\n return False;\n }\n }\n\n $abspath = untrailingslashit( ABSPATH ) ;\n\n $directory = dirname( $from );\n\n return str_replace( \"//\", \"\\\\\", site_url() . str_replace( $abspath, '', $directory ) );\n}\n</code></pre>\n\n<p>The reasoning for naming it <code>URI...</code> is that there's no case where you're going to build a link to include a PHP file. This is to be used in the case where you're distributing your code as a package and cannot rely on your framework's / main plugin CONSTANTS. In other words, when you don't know the install path of your package, use this. It'll work similarly to CSS' <code>../</code> (always relative).</p>\n"
},
{
"answer_id": 393933,
"author": "Miguel V.",
"author_id": 210837,
"author_profile": "https://wordpress.stackexchange.com/users/210837",
"pm_score": 0,
"selected": false,
"text": "<p>A Simple utility function that does exactly what everyone here is looking for, get the current plugin's root url path.</p>\n<pre><code>function get_plugin_url()\n{\n \n $uri = plugin_basename(__DIR__);\n $path = explode('/', $uri);\n \n return WP_PLUGIN_URL.'/'.$path[0].'/';\n \n}\n</code></pre>\n<p>Example output: <code>https://example.com/wp-content/plugins/your-plugin-slug/</code></p>\n"
}
] | 2019/12/04 | [
"https://wordpress.stackexchange.com/questions/353929",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/177618/"
] | Is there a function that would return the equivalent of `plugin_dir_path` but it being agnostic of a plugin / theme? JS scripts need to be enqueued as resources, as such, you cannot include their on-server path which is, say `/var/www/html/wordpress/thing/thing2/script.js`, it needs to be the `http://www.example.com/thing/thing2/script.js` counterpart. | Although @butlerblog's answer works, I find it unecessarily complex. I've checked above and beyond, `site_url` will always give you the current site's link, it will resolve the schemas for you, whether or not it's `http` or `https`, etc and as such, there's no issues with it.
I've written a simpler, easier to understand function:
```
/**
* Retrieves the full front-facing URL for a given path. In other words, it transforms an absolute path
* into an URI.
*
* Note: when allowing direct access to your files, if there is any I/O (there shouldn't be, but, you know) operations,
* you must check whether or not ABSPATH is defined.
*
* @see https://stackoverflow.com/a/44857254/12297763
*
* @param string $from An absolute path. You can just call this function with the parameter __FILE__ and it will give you a front-facing URI for that file.
* @param boolean $strict Flag that the function uses to see if it needs to do additional checks.
*
* @return string|false Returns a string in the form of an URI if all checks were passed or False if checks failed.
*/
function getURIFromPath( $from, $strict = False )
{
if( $strict ) {
if( !\file_exists( $from ) ) {
return False;
}
}
$abspath = untrailingslashit( ABSPATH ) ;
$directory = dirname( $from );
return str_replace( "//", "\\", site_url() . str_replace( $abspath, '', $directory ) );
}
```
The reasoning for naming it `URI...` is that there's no case where you're going to build a link to include a PHP file. This is to be used in the case where you're distributing your code as a package and cannot rely on your framework's / main plugin CONSTANTS. In other words, when you don't know the install path of your package, use this. It'll work similarly to CSS' `../` (always relative). |
353,995 | <p>I have a custom post type called 'event'. An event has multiple subpages like registration, speakers, contact us, etc. Currently the content is saved as one or more custom fields. </p>
<p>I would like to have an url structure like</p>
<ul>
<li><code>events/{event_slug}/registration</code> </li>
<li><code>events/{event_slug}/speakers</code></li>
<li><code>events/{event_slug}/contactus</code></li>
</ul>
<p>With each URL displaying the information from each custom field, respectively. </p>
<p>Is there a way, we can achieve this in WordPress?</p>
| [
{
"answer_id": 353932,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 1,
"selected": false,
"text": "<p>This is kind of a hacky way to do this; but unfortunately, there is not a WP function that will do both (theme and/or plugin). It's only an either/or proposition.</p>\n\n<p>On the surface, you'd think it wouldn't be difficult. You could just get the path and compare it with the site URL or something like that. But you run into problems when WP is installed somewhere other than the root (such as in a directory).</p>\n\n<p>If you look at my setup in the function, the \"else\" condition is the simple. If WP was always in the root, that would be all you need to do. Everything else is done to handle the other possibility (that WP is in a directory - or lower).</p>\n\n<p>In that case, it explodes the site URL to determine if there is more than just the root domain (an array bigger than 3). If so, it loops through the parts of the URL we got from the <code>explode()</code> process. We can skip the first three elements of the array as those should be the root of the domain (<a href=\"https://example.com\" rel=\"nofollow noreferrer\">https://example.com</a>). Then it builds the path (in case it's more than just one directory below).</p>\n\n<p>Using that it strips out everything below the root URL so you get just a clean URL you can use. Then it appends the path to the file.</p>\n\n<pre><code>function my_get_file_url_path() {\n\n // Account for WP being installed in a directory.\n $path_info = '';\n $site_url = site_url();\n $url_parts = explode( '/', $site_url );\n\n if ( array_count_values( $url_parts ) > 3 ) {\n $x = 0;\n foreach ( $url_parts as $this_part ) {\n if ( $x > 2 ) {\n $path_info = $this_part . '/';\n }\n $x++;\n }\n\n $site_actual_url = str_replace( $path_info, '', trailingslashit( $site_url ) );\n\n return $site_actual_url . trim( str_replace( $_SERVER['DOCUMENT_ROOT'], '', __DIR__ ), '/' );\n\n } else {\n return str_replace( $_SERVER['DOCUMENT_ROOT'], $site_url, __DIR__ );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 353979,
"author": "Daniel Smith",
"author_id": 177618,
"author_profile": "https://wordpress.stackexchange.com/users/177618",
"pm_score": 2,
"selected": true,
"text": "<p>Although @butlerblog's answer works, I find it unecessarily complex. I've checked above and beyond, <code>site_url</code> will always give you the current site's link, it will resolve the schemas for you, whether or not it's <code>http</code> or <code>https</code>, etc and as such, there's no issues with it.</p>\n\n<p>I've written a simpler, easier to understand function:</p>\n\n<pre><code>/**\n * Retrieves the full front-facing URL for a given path. In other words, it transforms an absolute path\n * into an URI.\n *\n * Note: when allowing direct access to your files, if there is any I/O (there shouldn't be, but, you know) operations,\n * you must check whether or not ABSPATH is defined.\n *\n * @see https://stackoverflow.com/a/44857254/12297763\n *\n * @param string $from An absolute path. You can just call this function with the parameter __FILE__ and it will give you a front-facing URI for that file.\n * @param boolean $strict Flag that the function uses to see if it needs to do additional checks.\n *\n * @return string|false Returns a string in the form of an URI if all checks were passed or False if checks failed.\n */\nfunction getURIFromPath( $from, $strict = False )\n{\n if( $strict ) {\n if( !\\file_exists( $from ) ) {\n return False;\n }\n }\n\n $abspath = untrailingslashit( ABSPATH ) ;\n\n $directory = dirname( $from );\n\n return str_replace( \"//\", \"\\\\\", site_url() . str_replace( $abspath, '', $directory ) );\n}\n</code></pre>\n\n<p>The reasoning for naming it <code>URI...</code> is that there's no case where you're going to build a link to include a PHP file. This is to be used in the case where you're distributing your code as a package and cannot rely on your framework's / main plugin CONSTANTS. In other words, when you don't know the install path of your package, use this. It'll work similarly to CSS' <code>../</code> (always relative).</p>\n"
},
{
"answer_id": 393933,
"author": "Miguel V.",
"author_id": 210837,
"author_profile": "https://wordpress.stackexchange.com/users/210837",
"pm_score": 0,
"selected": false,
"text": "<p>A Simple utility function that does exactly what everyone here is looking for, get the current plugin's root url path.</p>\n<pre><code>function get_plugin_url()\n{\n \n $uri = plugin_basename(__DIR__);\n $path = explode('/', $uri);\n \n return WP_PLUGIN_URL.'/'.$path[0].'/';\n \n}\n</code></pre>\n<p>Example output: <code>https://example.com/wp-content/plugins/your-plugin-slug/</code></p>\n"
}
] | 2019/12/05 | [
"https://wordpress.stackexchange.com/questions/353995",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111408/"
] | I have a custom post type called 'event'. An event has multiple subpages like registration, speakers, contact us, etc. Currently the content is saved as one or more custom fields.
I would like to have an url structure like
* `events/{event_slug}/registration`
* `events/{event_slug}/speakers`
* `events/{event_slug}/contactus`
With each URL displaying the information from each custom field, respectively.
Is there a way, we can achieve this in WordPress? | Although @butlerblog's answer works, I find it unecessarily complex. I've checked above and beyond, `site_url` will always give you the current site's link, it will resolve the schemas for you, whether or not it's `http` or `https`, etc and as such, there's no issues with it.
I've written a simpler, easier to understand function:
```
/**
* Retrieves the full front-facing URL for a given path. In other words, it transforms an absolute path
* into an URI.
*
* Note: when allowing direct access to your files, if there is any I/O (there shouldn't be, but, you know) operations,
* you must check whether or not ABSPATH is defined.
*
* @see https://stackoverflow.com/a/44857254/12297763
*
* @param string $from An absolute path. You can just call this function with the parameter __FILE__ and it will give you a front-facing URI for that file.
* @param boolean $strict Flag that the function uses to see if it needs to do additional checks.
*
* @return string|false Returns a string in the form of an URI if all checks were passed or False if checks failed.
*/
function getURIFromPath( $from, $strict = False )
{
if( $strict ) {
if( !\file_exists( $from ) ) {
return False;
}
}
$abspath = untrailingslashit( ABSPATH ) ;
$directory = dirname( $from );
return str_replace( "//", "\\", site_url() . str_replace( $abspath, '', $directory ) );
}
```
The reasoning for naming it `URI...` is that there's no case where you're going to build a link to include a PHP file. This is to be used in the case where you're distributing your code as a package and cannot rely on your framework's / main plugin CONSTANTS. In other words, when you don't know the install path of your package, use this. It'll work similarly to CSS' `../` (always relative). |
354,085 | <p>I need to do something like that:</p>
<pre><code> $postsOrder = get_sub_field('posts-ordering');
if ($postsOrder = 'post_views_count') {
$queryPopular = array (
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
);
}
$query = new WP_Query(
array(
'posts_per_page' => $postsCount,
'post_type' => $postsType->name,
'order' => 'DESC',
'orderby' => $postsOrder,
'taxonomy' => $postsTaxonomy,
$queryPopular
),
);
</code></pre>
<p>The point is that if $postsOrder is equal 'post_views_count', then in $query should be added two another parameters. How to do it right?</p>
| [
{
"answer_id": 354084,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>I've been looking in the DB to see where WP stores the modified dates for taxonomies but I've been unable to find the right table. </p>\n</blockquote>\n\n<p>It doesn't. There is no last modified date for terms, that data simply doesn't exist in the tables in vanilla WP. If you want it, you're going to have to track and store it yourself in code via hooks, preferably term meta.</p>\n\n<blockquote>\n <p>when I call get_the_modified_date($term_id)</p>\n</blockquote>\n\n<p>You can't call that function on term IDs, it only works for post IDs, which gives us a clue to why you're getting strange results. The documentation and that functions signature clearly state they want a post ID.</p>\n\n<blockquote>\n <p>some of the taxonomy terms return the date but others return false.</p>\n</blockquote>\n\n<p>Because any ID you pass in will be a post ID, passing in the term with ID 4, will give you the modified date for the post with ID 4. If you check again, saving terms in WP Admin has no bearing at all on those dates, due to the aforementioned fact that terms don't have modified and publish dates.</p>\n\n<p>Naturally, there are term IDs that don't match posts, so you'll get <code>false</code>. e.g. request the modified date and pass in 200000000, there won't be a post with that ID, even if there is a term with that ID.</p>\n"
},
{
"answer_id": 412209,
"author": "Ali Heydari",
"author_id": 228435,
"author_profile": "https://wordpress.stackexchange.com/users/228435",
"pm_score": 0,
"selected": false,
"text": "<ul>\n<li><p>If you want show "modified_date" for your posts, as Tom J Nowell said, you should use <code>$post->ID</code> instead of <code>$term_id</code></p>\n</li>\n<li><p>If you want to show "modified_date" for your taxonomy (for example: this taxonomy's posts were updated in this time ...") you can easily create a WP_Query for your custom taxonomy like this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$modif = new WP_Query(array(\n 'taxonomy' => 'your taxonomy here',\n 'showposts' => 1\n)\n);\n</code></pre>\n<p>, and get just 1 post (attention to order by date), and get the\nmodified_date and show it everywhere you want ...</p>\n</li>\n</ul>\n"
}
] | 2019/12/07 | [
"https://wordpress.stackexchange.com/questions/354085",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116847/"
] | I need to do something like that:
```
$postsOrder = get_sub_field('posts-ordering');
if ($postsOrder = 'post_views_count') {
$queryPopular = array (
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
);
}
$query = new WP_Query(
array(
'posts_per_page' => $postsCount,
'post_type' => $postsType->name,
'order' => 'DESC',
'orderby' => $postsOrder,
'taxonomy' => $postsTaxonomy,
$queryPopular
),
);
```
The point is that if $postsOrder is equal 'post\_views\_count', then in $query should be added two another parameters. How to do it right? | >
> I've been looking in the DB to see where WP stores the modified dates for taxonomies but I've been unable to find the right table.
>
>
>
It doesn't. There is no last modified date for terms, that data simply doesn't exist in the tables in vanilla WP. If you want it, you're going to have to track and store it yourself in code via hooks, preferably term meta.
>
> when I call get\_the\_modified\_date($term\_id)
>
>
>
You can't call that function on term IDs, it only works for post IDs, which gives us a clue to why you're getting strange results. The documentation and that functions signature clearly state they want a post ID.
>
> some of the taxonomy terms return the date but others return false.
>
>
>
Because any ID you pass in will be a post ID, passing in the term with ID 4, will give you the modified date for the post with ID 4. If you check again, saving terms in WP Admin has no bearing at all on those dates, due to the aforementioned fact that terms don't have modified and publish dates.
Naturally, there are term IDs that don't match posts, so you'll get `false`. e.g. request the modified date and pass in 200000000, there won't be a post with that ID, even if there is a term with that ID. |
354,137 | <p>I'm trying to develop a simple plugin but I'm having a problem: I have a custom <code>WP_List_Table</code> in an admin page, but when I click on a button like "Edit Row" or "Delete Row" it performs some expected action and try to refresh the page using <code>wp_redirect()</code>. This is causing a problem:</p>
<pre><code>Warning: Cannot modify header information - headers already sent by (output started at /opt/lampp/htdocs/wordpress/wp-includes/formatting.php:5652) in /opt/lampp/htdocs/wordpress/wp-includes/pluggable.php on line 1265
Warning: Cannot modify header information - headers already sent by (output started at /opt/lampp/htdocs/wordpress/wp-includes/formatting.php:5652) in /opt/lampp/htdocs/wordpress/wp-includes/pluggable.php on line 1268
</code></pre>
<p>I have just the Advanced Custom Fields plugin installed and I'm using the default theme. At the moment, my plugin is JUST this code below (I got it here <a href="https://www.sitepoint.com/using-wp_list_table-to-create-wordpress-admin-tables/" rel="nofollow noreferrer">https://www.sitepoint.com/using-wp_list_table-to-create-wordpress-admin-tables/</a>):</p>
<pre><code>if ( ! class_exists( 'WP_List_Table' ) ) {
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
class Customers_List extends WP_List_Table {
/** Class constructor */
public function __construct() {
parent::__construct( [
'singular' => __( 'Customer', 'sp' ), //singular name of the listed records
'plural' => __( 'Customers', 'sp' ), //plural name of the listed records
'ajax' => false //does this table support ajax?
] );
}
/**
* Retrieve customers data from the database
*
* @param int $per_page
* @param int $page_number
*
* @return mixed
*/
public static function get_customers() {
$result = array();
$args = array(
'role' => 'Inscrito',
);
$users = get_users( $args );
foreach($users as $user){
$user_form = 'user_'. $user->ID;
$image = get_field('receipt', $user_form);
$size = 'full'; // (thumbnail, medium, large, full or custom size)
if( $image ) {
$image_url = '<a href="' .$image['url'] . '"> a </a>';
}else{
$image_url = 'False';
}
array_push($result,
array( 'ID' => $user->ID,
'name' => $user->status,
'address' => $image_url,
'city' => $image_url,
)
);
}
return $result;
}
/**
* Delete a customer record.
*
* @param int $id customer ID
*/
public static function delete_customer( $id ) {
global $wpdb;
$wpdb->delete(
"{$wpdb->prefix}customers",
[ 'ID' => $id ],
[ '%d' ]
);
}
/** Text displayed when no customer data is available */
public function no_items() {
_e( 'No customers avaliable.', 'sp' );
}
/**
* Render a column when no column specific method exist.
*
* @param array $item
* @param string $column_name
*
* @return mixed
*/
public function column_default( $item, $column_name ) {
switch ( $column_name ) {
case 'address':
case 'city':
return $item[ $column_name ];
default:
return print_r( $item, true ); //Show the whole array for troubleshooting purposes
}
}
/**
* Render the bulk edit checkbox
*
* @param array $item
*
* @return string
*/
function column_cb( $item ) {
return sprintf(
'<input type="checkbox" name="bulk-delete[]" value="%s" />', $item['ID']
);
}
/**
* Method for name column
*
* @param array $item an array of DB data
*
* @return string
*/
function column_name( $item ) {
$delete_nonce = wp_create_nonce( 'sp_delete_customer' );
$title = '<strong>' . $item['name'] . '</strong>';
$actions = [
'delete' => sprintf( '<a href="?page=%s&action=%s&customer=%s&_wpnonce=%s">Delete</a>', esc_attr( $_REQUEST['page'] ), 'delete', absint( $item['ID'] ), $delete_nonce )
];
return $title . $this->row_actions( $actions );
}
/**
* Associative array of columns
*
* @return array
*/
function get_columns() {
$columns = [
'cb' => '<input type="checkbox" />',
'name' => __( 'Name', 'sp' ),
'address' => __( 'Address', 'sp' ),
'city' => __( 'City', 'sp' )
];
return $columns;
}
/**
* Columns to make sortable.
*
* @return array
*/
public function get_sortable_columns() {
$sortable_columns = array(
'name' => array( 'name', true ),
'city' => array( 'city', false )
);
return $sortable_columns;
}
/**
* Returns an associative array containing the bulk action
*
* @return array
*/
public function get_bulk_actions() {
$actions = [
'bulk-delete' => 'Delete'
];
return $actions;
}
/**
* Handles data query and filter, sorting, and pagination.
*/
public function prepare_items() {
$this->_column_headers = $this->get_column_info();
/** Process bulk action */
$this->process_bulk_action();
$users = self::get_customers();
$per_page = $this->get_items_per_page( 'customers_per_page', 5 );
$current_page = $this->get_pagenum();
$total_items = self::record_count();
$slice_offset = ( ( $current_page-1 )* $per_page );
$slice_limit = $slice_offset+$per_page;
// only ncessary because we have sample data
$found_data = array_slice( $users, $slice_offset, $slice_limit);
$this->set_pagination_args( [
'total_items' => $total_items, //WE have to calculate the total number of items
'per_page' => $per_page //WE have to determine how many items to show on a page
] );
$this->items = $found_data;
}
public function process_bulk_action() {
//Detect when a bulk action is being triggered...
if ( 'delete' === $this->current_action() ) {
// In our file that handles the request, verify the nonce.
$nonce = esc_attr( $_REQUEST['_wpnonce'] );
if ( ! wp_verify_nonce( $nonce, 'sp_delete_customer' ) ) {
die( 'Go get a life script kiddies' );
}
else {
self::delete_customer( absint( $_GET['customer'] ) );
// esc_url_raw() is used to prevent converting ampersand in url to "#038;"
// add_query_arg() return the current url
wp_redirect( esc_url_raw(add_query_arg()) );
exit;
}
}
// If the delete bulk action is triggered
if ( ( isset( $_POST['action'] ) && $_POST['action'] == 'bulk-delete' )
|| ( isset( $_POST['action2'] ) && $_POST['action2'] == 'bulk-delete' )
) {
$delete_ids = esc_sql( $_POST['bulk-delete'] );
// loop over the array of record IDs and delete them
foreach ( $delete_ids as $id ) {
self::delete_customer( $id );
}
// esc_url_raw() is used to prevent converting ampersand in url to "#038;"
// add_query_arg() return the current url
wp_redirect( esc_url_raw(add_query_arg()) );
exit;
}
}
}
class SP_Plugin {
// class instance
static $instance;
// customer WP_List_Table object
public $customers_obj;
// class constructor
public function __construct() {
add_filter( 'set-screen-option', [ __CLASS__, 'set_screen' ], 10, 3 );
add_action( 'admin_menu', [ $this, 'plugin_menu' ] );
}
public static function set_screen( $status, $option, $value ) {
return $value;
}
public function plugin_menu() {
$hook = add_menu_page(
'Sitepoint WP_List_Table Example',
'SP WP_List_Table',
'manage_options',
'wp_list_table_class',
[ $this, 'plugin_settings_page' ]
);
add_action( "load-$hook", [ $this, 'screen_option' ] );
}
/**
* Plugin settings page
*/
public function plugin_settings_page() {
?>
<div class="wrap">
<h2>WP_List_Table Class Example</h2>
<div id="poststuff">
<div id="post-body" class="metabox-holder columns-2">
<div id="post-body-content">
<div class="meta-box-sortables ui-sortable">
<form method="post">
<?php
$this->customers_obj->prepare_items();
$this->customers_obj->display(); ?>
</form>
</div>
</div>
</div>
<br class="clear">
</div>
</div>
<?php
}
/**
* Screen options
*/
public function screen_option() {
$option = 'per_page';
$args = [
'label' => 'Customers',
'default' => 5,
'option' => 'customers_per_page'
];
add_screen_option( $option, $args );
$this->customers_obj = new Customers_List();
}
/** Singleton instance */
public static function get_instance() {
if ( ! isset( self::$instance ) ) {
self::$instance = new self();
}
return self::$instance;
}
}
add_action( 'plugins_loaded', function () {
SP_Plugin::get_instance();
} );
</code></pre>
<p>I know this is a frequently asked question here, but I tried to search a lot before asking and nothing helped me.</p>
| [
{
"answer_id": 354169,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not 100% certain <em>this</em> is your problem, <em>but</em>... I believe your \"no_items\" function should return the value, not echo it. If there are no items, that would lead to a \"headers already sent\" when the redirect is fired. Try it like this:</p>\n\n<pre><code>/** Text displayed when no customer data is available */\npublic function no_items() {\n return __( 'No customers avaliable.', 'sp' );\n}\n</code></pre>\n"
},
{
"answer_id": 354830,
"author": "Julio Cesar de Azeredo",
"author_id": 179378,
"author_profile": "https://wordpress.stackexchange.com/users/179378",
"pm_score": 1,
"selected": true,
"text": "<p>This code uses another method to show a \"sucess\" or \"deleted\" message without using wp_redirect: <a href=\"https://github.com/pmbaldha/WP-Custom-List-Table-With-Database-Example\" rel=\"nofollow noreferrer\">https://github.com/pmbaldha/WP-Custom-List-Table-With-Database-Example</a></p>\n"
}
] | 2019/12/07 | [
"https://wordpress.stackexchange.com/questions/354137",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/179378/"
] | I'm trying to develop a simple plugin but I'm having a problem: I have a custom `WP_List_Table` in an admin page, but when I click on a button like "Edit Row" or "Delete Row" it performs some expected action and try to refresh the page using `wp_redirect()`. This is causing a problem:
```
Warning: Cannot modify header information - headers already sent by (output started at /opt/lampp/htdocs/wordpress/wp-includes/formatting.php:5652) in /opt/lampp/htdocs/wordpress/wp-includes/pluggable.php on line 1265
Warning: Cannot modify header information - headers already sent by (output started at /opt/lampp/htdocs/wordpress/wp-includes/formatting.php:5652) in /opt/lampp/htdocs/wordpress/wp-includes/pluggable.php on line 1268
```
I have just the Advanced Custom Fields plugin installed and I'm using the default theme. At the moment, my plugin is JUST this code below (I got it here <https://www.sitepoint.com/using-wp_list_table-to-create-wordpress-admin-tables/>):
```
if ( ! class_exists( 'WP_List_Table' ) ) {
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
class Customers_List extends WP_List_Table {
/** Class constructor */
public function __construct() {
parent::__construct( [
'singular' => __( 'Customer', 'sp' ), //singular name of the listed records
'plural' => __( 'Customers', 'sp' ), //plural name of the listed records
'ajax' => false //does this table support ajax?
] );
}
/**
* Retrieve customers data from the database
*
* @param int $per_page
* @param int $page_number
*
* @return mixed
*/
public static function get_customers() {
$result = array();
$args = array(
'role' => 'Inscrito',
);
$users = get_users( $args );
foreach($users as $user){
$user_form = 'user_'. $user->ID;
$image = get_field('receipt', $user_form);
$size = 'full'; // (thumbnail, medium, large, full or custom size)
if( $image ) {
$image_url = '<a href="' .$image['url'] . '"> a </a>';
}else{
$image_url = 'False';
}
array_push($result,
array( 'ID' => $user->ID,
'name' => $user->status,
'address' => $image_url,
'city' => $image_url,
)
);
}
return $result;
}
/**
* Delete a customer record.
*
* @param int $id customer ID
*/
public static function delete_customer( $id ) {
global $wpdb;
$wpdb->delete(
"{$wpdb->prefix}customers",
[ 'ID' => $id ],
[ '%d' ]
);
}
/** Text displayed when no customer data is available */
public function no_items() {
_e( 'No customers avaliable.', 'sp' );
}
/**
* Render a column when no column specific method exist.
*
* @param array $item
* @param string $column_name
*
* @return mixed
*/
public function column_default( $item, $column_name ) {
switch ( $column_name ) {
case 'address':
case 'city':
return $item[ $column_name ];
default:
return print_r( $item, true ); //Show the whole array for troubleshooting purposes
}
}
/**
* Render the bulk edit checkbox
*
* @param array $item
*
* @return string
*/
function column_cb( $item ) {
return sprintf(
'<input type="checkbox" name="bulk-delete[]" value="%s" />', $item['ID']
);
}
/**
* Method for name column
*
* @param array $item an array of DB data
*
* @return string
*/
function column_name( $item ) {
$delete_nonce = wp_create_nonce( 'sp_delete_customer' );
$title = '<strong>' . $item['name'] . '</strong>';
$actions = [
'delete' => sprintf( '<a href="?page=%s&action=%s&customer=%s&_wpnonce=%s">Delete</a>', esc_attr( $_REQUEST['page'] ), 'delete', absint( $item['ID'] ), $delete_nonce )
];
return $title . $this->row_actions( $actions );
}
/**
* Associative array of columns
*
* @return array
*/
function get_columns() {
$columns = [
'cb' => '<input type="checkbox" />',
'name' => __( 'Name', 'sp' ),
'address' => __( 'Address', 'sp' ),
'city' => __( 'City', 'sp' )
];
return $columns;
}
/**
* Columns to make sortable.
*
* @return array
*/
public function get_sortable_columns() {
$sortable_columns = array(
'name' => array( 'name', true ),
'city' => array( 'city', false )
);
return $sortable_columns;
}
/**
* Returns an associative array containing the bulk action
*
* @return array
*/
public function get_bulk_actions() {
$actions = [
'bulk-delete' => 'Delete'
];
return $actions;
}
/**
* Handles data query and filter, sorting, and pagination.
*/
public function prepare_items() {
$this->_column_headers = $this->get_column_info();
/** Process bulk action */
$this->process_bulk_action();
$users = self::get_customers();
$per_page = $this->get_items_per_page( 'customers_per_page', 5 );
$current_page = $this->get_pagenum();
$total_items = self::record_count();
$slice_offset = ( ( $current_page-1 )* $per_page );
$slice_limit = $slice_offset+$per_page;
// only ncessary because we have sample data
$found_data = array_slice( $users, $slice_offset, $slice_limit);
$this->set_pagination_args( [
'total_items' => $total_items, //WE have to calculate the total number of items
'per_page' => $per_page //WE have to determine how many items to show on a page
] );
$this->items = $found_data;
}
public function process_bulk_action() {
//Detect when a bulk action is being triggered...
if ( 'delete' === $this->current_action() ) {
// In our file that handles the request, verify the nonce.
$nonce = esc_attr( $_REQUEST['_wpnonce'] );
if ( ! wp_verify_nonce( $nonce, 'sp_delete_customer' ) ) {
die( 'Go get a life script kiddies' );
}
else {
self::delete_customer( absint( $_GET['customer'] ) );
// esc_url_raw() is used to prevent converting ampersand in url to "#038;"
// add_query_arg() return the current url
wp_redirect( esc_url_raw(add_query_arg()) );
exit;
}
}
// If the delete bulk action is triggered
if ( ( isset( $_POST['action'] ) && $_POST['action'] == 'bulk-delete' )
|| ( isset( $_POST['action2'] ) && $_POST['action2'] == 'bulk-delete' )
) {
$delete_ids = esc_sql( $_POST['bulk-delete'] );
// loop over the array of record IDs and delete them
foreach ( $delete_ids as $id ) {
self::delete_customer( $id );
}
// esc_url_raw() is used to prevent converting ampersand in url to "#038;"
// add_query_arg() return the current url
wp_redirect( esc_url_raw(add_query_arg()) );
exit;
}
}
}
class SP_Plugin {
// class instance
static $instance;
// customer WP_List_Table object
public $customers_obj;
// class constructor
public function __construct() {
add_filter( 'set-screen-option', [ __CLASS__, 'set_screen' ], 10, 3 );
add_action( 'admin_menu', [ $this, 'plugin_menu' ] );
}
public static function set_screen( $status, $option, $value ) {
return $value;
}
public function plugin_menu() {
$hook = add_menu_page(
'Sitepoint WP_List_Table Example',
'SP WP_List_Table',
'manage_options',
'wp_list_table_class',
[ $this, 'plugin_settings_page' ]
);
add_action( "load-$hook", [ $this, 'screen_option' ] );
}
/**
* Plugin settings page
*/
public function plugin_settings_page() {
?>
<div class="wrap">
<h2>WP_List_Table Class Example</h2>
<div id="poststuff">
<div id="post-body" class="metabox-holder columns-2">
<div id="post-body-content">
<div class="meta-box-sortables ui-sortable">
<form method="post">
<?php
$this->customers_obj->prepare_items();
$this->customers_obj->display(); ?>
</form>
</div>
</div>
</div>
<br class="clear">
</div>
</div>
<?php
}
/**
* Screen options
*/
public function screen_option() {
$option = 'per_page';
$args = [
'label' => 'Customers',
'default' => 5,
'option' => 'customers_per_page'
];
add_screen_option( $option, $args );
$this->customers_obj = new Customers_List();
}
/** Singleton instance */
public static function get_instance() {
if ( ! isset( self::$instance ) ) {
self::$instance = new self();
}
return self::$instance;
}
}
add_action( 'plugins_loaded', function () {
SP_Plugin::get_instance();
} );
```
I know this is a frequently asked question here, but I tried to search a lot before asking and nothing helped me. | This code uses another method to show a "sucess" or "deleted" message without using wp\_redirect: <https://github.com/pmbaldha/WP-Custom-List-Table-With-Database-Example> |
354,143 | <p>hi i am looking to combing to pieces of code into 1 both work but not together keep no matter what i try it keeps crashing the site </p>
<pre><code><?php
$t=date("H");
if ($t<"12")
{
echo " Have a good morning! $display_name ";
}
else if ($t<"18")
{
echo " Have a good afternoon! $display_name ";
}
else
{
echo " Have a good evening! $display_name ";
} ?>
</code></pre>
<p>and </p>
<pre><code><?php global $current_user; wp_get_current_user(); ?>
<?php if ( is_user_logged_in() ) {
echo 'Welcome Brother: ' . $current_user->user_login . "\n"; }
else { wp_loginout(); } ?>
</code></pre>
<p>other user parameters would be great to swap out </p>
| [
{
"answer_id": 354169,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not 100% certain <em>this</em> is your problem, <em>but</em>... I believe your \"no_items\" function should return the value, not echo it. If there are no items, that would lead to a \"headers already sent\" when the redirect is fired. Try it like this:</p>\n\n<pre><code>/** Text displayed when no customer data is available */\npublic function no_items() {\n return __( 'No customers avaliable.', 'sp' );\n}\n</code></pre>\n"
},
{
"answer_id": 354830,
"author": "Julio Cesar de Azeredo",
"author_id": 179378,
"author_profile": "https://wordpress.stackexchange.com/users/179378",
"pm_score": 1,
"selected": true,
"text": "<p>This code uses another method to show a \"sucess\" or \"deleted\" message without using wp_redirect: <a href=\"https://github.com/pmbaldha/WP-Custom-List-Table-With-Database-Example\" rel=\"nofollow noreferrer\">https://github.com/pmbaldha/WP-Custom-List-Table-With-Database-Example</a></p>\n"
}
] | 2019/12/07 | [
"https://wordpress.stackexchange.com/questions/354143",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69081/"
] | hi i am looking to combing to pieces of code into 1 both work but not together keep no matter what i try it keeps crashing the site
```
<?php
$t=date("H");
if ($t<"12")
{
echo " Have a good morning! $display_name ";
}
else if ($t<"18")
{
echo " Have a good afternoon! $display_name ";
}
else
{
echo " Have a good evening! $display_name ";
} ?>
```
and
```
<?php global $current_user; wp_get_current_user(); ?>
<?php if ( is_user_logged_in() ) {
echo 'Welcome Brother: ' . $current_user->user_login . "\n"; }
else { wp_loginout(); } ?>
```
other user parameters would be great to swap out | This code uses another method to show a "sucess" or "deleted" message without using wp\_redirect: <https://github.com/pmbaldha/WP-Custom-List-Table-With-Database-Example> |
354,179 | <p>It's been asked a gazillion times but it's still not working in my Wordpress. I want to redirect everything to <a href="https://website.com" rel="nofollow noreferrer">https://website.com</a>.
Current code been used:</p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
</IfModule>
</code></pre>
<p>based on <a href="https://stackoverflow.com/questions/54070927/apache-2-htaccess-wont-redirect-www-non-www">this one</a> but I also tried <a href="https://stackoverflow.com/questions/234723/generic-htaccess-redirect-www-to-non-www/235064#235064">all in this page</a> and of course <a href="https://wordpress.stackexchange.com/questions/256038/htaccess-https-redirect-from-www-to-non-www">this other one</a>. Maybe I am missing something but this is what happens no matter what combination I tried:</p>
<pre><code># http://website.com -> https://website.com
# https://website.com -> https://website.com
# http://www.website.com -> https://www.website.com #wrong#
# https://www.website.com -> https://www.website.com #wrong#
</code></pre>
<p>I am starting to wonder whether the let's encrypt installation has something to do... or even some other modification done in wp-config.php... I added this in the past:</p>
<pre><code>if ( defined( 'WP_CLI' ) ) {
$_SERVER['HTTP_HOST'] = 'localhost';
}
define('WP_SITEURL', 'https://' . $_SERVER['HTTP_HOST'] . '/');
define('WP_HOME', 'https://' . $_SERVER['HTTP_HOST'] . '/');
</code></pre>
<p>Any idea?
Thanks</p>
| [
{
"answer_id": 354182,
"author": "Elgoots",
"author_id": 179379,
"author_profile": "https://wordpress.stackexchange.com/users/179379",
"pm_score": 0,
"selected": false,
"text": "<p>Setting the wordpress home and site url manually to <a href=\"https://website.com\" rel=\"nofollow noreferrer\">https://website.com</a></p>\n\n<p>Then remove all other rules in .htaccess and have:</p>\n\n<pre><code>RewriteEngine On \nRewriteCond %{HTTPS} off \nRewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n\n<p>The htaccess will redirect to https for all traffic and all pages/posts/categories etc.</p>\n\n<p>As for dropping the www infront, the site url and homepage url should take care of that in the wordpress framework.</p>\n\n<p>Give it a try and report back.</p>\n\n<p>If that does not work, try the following and manually set the request uri. Obviously change website.com with your domain:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP_HOST} ^www.website.com$ [NC]\nRewriteRule ^(.*)$ https://website.com/$1 [R=301,L]\nRewriteCond %{HTTPS} off\nRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]\n</code></pre>\n"
},
{
"answer_id": 354311,
"author": "Trisha",
"author_id": 56458,
"author_profile": "https://wordpress.stackexchange.com/users/56458",
"pm_score": 2,
"selected": true,
"text": "<p>This is what you want:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP_HOST} website\\.com [NC]\nRewriteCond %{SERVER_PORT} 80\nRewriteRule ^(.*)$ https://website.com/$1 [R,L]\n</code></pre>\n\n<p>@elgoots, the reason yours was close but still had trouble is your HTTP_HOST has the www in it. </p>\n"
}
] | 2019/12/08 | [
"https://wordpress.stackexchange.com/questions/354179",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/179485/"
] | It's been asked a gazillion times but it's still not working in my Wordpress. I want to redirect everything to <https://website.com>.
Current code been used:
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
</IfModule>
```
based on [this one](https://stackoverflow.com/questions/54070927/apache-2-htaccess-wont-redirect-www-non-www) but I also tried [all in this page](https://stackoverflow.com/questions/234723/generic-htaccess-redirect-www-to-non-www/235064#235064) and of course [this other one](https://wordpress.stackexchange.com/questions/256038/htaccess-https-redirect-from-www-to-non-www). Maybe I am missing something but this is what happens no matter what combination I tried:
```
# http://website.com -> https://website.com
# https://website.com -> https://website.com
# http://www.website.com -> https://www.website.com #wrong#
# https://www.website.com -> https://www.website.com #wrong#
```
I am starting to wonder whether the let's encrypt installation has something to do... or even some other modification done in wp-config.php... I added this in the past:
```
if ( defined( 'WP_CLI' ) ) {
$_SERVER['HTTP_HOST'] = 'localhost';
}
define('WP_SITEURL', 'https://' . $_SERVER['HTTP_HOST'] . '/');
define('WP_HOME', 'https://' . $_SERVER['HTTP_HOST'] . '/');
```
Any idea?
Thanks | This is what you want:
```
RewriteEngine On
RewriteCond %{HTTP_HOST} website\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://website.com/$1 [R,L]
```
@elgoots, the reason yours was close but still had trouble is your HTTP\_HOST has the www in it. |
354,184 | <p>I want to add a button on my wordpress page. When the user click on it, the text box above that button show a random number between 1-10000</p>
<p>I am quite new to Wordpress, I want to integrate some scripts to my Wordpress site to do this random number generation. For example I can call a php function when clicking that button. And the php code helps generate that random number and put it on the text box. but I don’t know where to begin. I googled that, but there isn’t a good reference for beginners at all</p>
| [
{
"answer_id": 354192,
"author": "Ali Qorbani",
"author_id": 73590,
"author_profile": "https://wordpress.stackexchange.com/users/73590",
"pm_score": 1,
"selected": false,
"text": "<p>all thing you have to do is use javaScript function</p>\n\n<p><strong>JavaScript Example:</strong></p>\n\n<pre><code>var random_number = function(){\n return Math.floor(Math.random() * 10000) + 1;\n};\ndocument.getElementById('button_text').onclick = function () {\n document.getElementById(\"input_box\").innerHTML = random_number();\n};\n</code></pre>\n\n<p><strong>jQuery Example:</strong></p>\n\n<pre><code>$.randomBetween(0,10000);\n</code></pre>\n"
},
{
"answer_id": 354202,
"author": "Gopala krishnan",
"author_id": 168404,
"author_profile": "https://wordpress.stackexchange.com/users/168404",
"pm_score": 0,
"selected": false,
"text": "<p>In Jquery we can written as,</p>\n\n<pre><code>jQuery('body').on('click', '#button_text',function(){\n var minNumber = 1;\n var maxNumber = 10000;\n var randomNumber = randomNumberFromRange(minNumber, maxNumber);\n jQuery('#input_box').val() = randomNumber;\n\n});\nfunction randomNumberFromRange(min,max){\n return Math.floor(Math.random()*(max-min+1)+min);\n}\n</code></pre>\n"
}
] | 2019/12/09 | [
"https://wordpress.stackexchange.com/questions/354184",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/179493/"
] | I want to add a button on my wordpress page. When the user click on it, the text box above that button show a random number between 1-10000
I am quite new to Wordpress, I want to integrate some scripts to my Wordpress site to do this random number generation. For example I can call a php function when clicking that button. And the php code helps generate that random number and put it on the text box. but I don’t know where to begin. I googled that, but there isn’t a good reference for beginners at all | all thing you have to do is use javaScript function
**JavaScript Example:**
```
var random_number = function(){
return Math.floor(Math.random() * 10000) + 1;
};
document.getElementById('button_text').onclick = function () {
document.getElementById("input_box").innerHTML = random_number();
};
```
**jQuery Example:**
```
$.randomBetween(0,10000);
``` |
354,207 | <p>I use "Digits (WordPress Mobile Number Signup and Login)" for signup by email & SMS ;
when non logged in user proceed to checkout , want to redirect to signup form of Digits (not usual woocommerce signup).</p>
<p>In case already logged-in users, they should go following the next step in the checkout process as normal.</p>
<p>appreciate if anybody help.</p>
| [
{
"answer_id": 354192,
"author": "Ali Qorbani",
"author_id": 73590,
"author_profile": "https://wordpress.stackexchange.com/users/73590",
"pm_score": 1,
"selected": false,
"text": "<p>all thing you have to do is use javaScript function</p>\n\n<p><strong>JavaScript Example:</strong></p>\n\n<pre><code>var random_number = function(){\n return Math.floor(Math.random() * 10000) + 1;\n};\ndocument.getElementById('button_text').onclick = function () {\n document.getElementById(\"input_box\").innerHTML = random_number();\n};\n</code></pre>\n\n<p><strong>jQuery Example:</strong></p>\n\n<pre><code>$.randomBetween(0,10000);\n</code></pre>\n"
},
{
"answer_id": 354202,
"author": "Gopala krishnan",
"author_id": 168404,
"author_profile": "https://wordpress.stackexchange.com/users/168404",
"pm_score": 0,
"selected": false,
"text": "<p>In Jquery we can written as,</p>\n\n<pre><code>jQuery('body').on('click', '#button_text',function(){\n var minNumber = 1;\n var maxNumber = 10000;\n var randomNumber = randomNumberFromRange(minNumber, maxNumber);\n jQuery('#input_box').val() = randomNumber;\n\n});\nfunction randomNumberFromRange(min,max){\n return Math.floor(Math.random()*(max-min+1)+min);\n}\n</code></pre>\n"
}
] | 2019/12/09 | [
"https://wordpress.stackexchange.com/questions/354207",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/179503/"
] | I use "Digits (WordPress Mobile Number Signup and Login)" for signup by email & SMS ;
when non logged in user proceed to checkout , want to redirect to signup form of Digits (not usual woocommerce signup).
In case already logged-in users, they should go following the next step in the checkout process as normal.
appreciate if anybody help. | all thing you have to do is use javaScript function
**JavaScript Example:**
```
var random_number = function(){
return Math.floor(Math.random() * 10000) + 1;
};
document.getElementById('button_text').onclick = function () {
document.getElementById("input_box").innerHTML = random_number();
};
```
**jQuery Example:**
```
$.randomBetween(0,10000);
``` |
354,281 | <p>I'm trying to add a button (its function is beyond the scope of this question, suffice it to say that it needs the refund id as an argument) to each refund line in a WooCommerce order. I found that those lines are created in woocommerce\includes\admin\meta-boxes\views\html-order-refund.php which can't be overridden. However there is an action:</p>
<pre><code>do_action( 'woocommerce_admin_order_item_values', null, $refund, $refund->get_id() );
</code></pre>
<p>This seemed perfect for my purpose, so I tried adding the following code to functions.php to test if it could work:</p>
<pre><code>add_filter('woocommerce_admin_order_item_values', 'test_refund_id');
function test_refund_id($nullvar, $refund, $refund_id) {
if ( !empty($refund->refunded_by) ){
echo '<td>Refund ID: '.$refund_id.'</td>';
}
}
</code></pre>
<p>I used <code>if ( !empty($refund->refunded_by) )</code> because <code>woocommerce_admin_order_item_values</code> also gets called in html-order-shipping.php, html-order-item.php and html-order-fee.php, with an "order item" object (instead of a "refund" object) as the second argument, so there's no <code>refunded_by</code> property and my instruction should be ignored.</p>
<p>Much to my disappointment, though, I get the following error:</p>
<blockquote>
<p>Fatal error: Uncaught ArgumentCountError: Too few arguments to
function test_refund_id(), 1 passed in \wp-includes\class-wp-hook.php
on line 290 and exactly 3 expected in
\wp-content\themes\mytheme\functions.php:1087</p>
</blockquote>
<p>I know that, as a matter of fact, three arguments are passed in the line I quoted above (namely a null, the refund object and the refund id), but I went and checked the script the error was referring to (\wp-includes\class-wp-hook.php) around line 290, and I found this in the <code>apply_filters()</code> function:</p>
<pre><code> // Avoid the array_slice if possible.
if ( $the_['accepted_args'] == 0 ) {
$value = call_user_func( $the_['function'] );
} elseif ( $the_['accepted_args'] >= $num_args ) {
$value = call_user_func_array( $the_['function'], $args );
} else {
$value = call_user_func_array( $the_['function'], array_slice( $args, 0, (int) $the_['accepted_args'] ) );
}
</code></pre>
<p>Just for testing purposes I tried to temporarily change the last "else" clause, replacing the "sliced" arguments array with the original one, thereby forcing the script to keep all the arguments anyway, so <code>array_slice( $args, 0, (int) $the_['accepted_args'] )</code> became simply <code>$args</code>. Surprise, surprise, now everything works smoothly! </p>
<p><a href="https://i.stack.imgur.com/6GmSo.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6GmSo.jpg" alt="enter image description here"></a></p>
<p>Now, I'm well aware that's of course not a solution since I can't edit a core WP script. I would just want to understand WHY <code>apply_filters()</code> thinks that the accepted arguments are less than the passed ones and therefore it trims the argument array down to just the first one.</p>
<p>Thanks a lot in advance to anyone who'd like to shed some light on the matter.</p>
| [
{
"answer_id": 354282,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 3,
"selected": true,
"text": "<p>Two inherent problems with your script as posted. I'm not certain this will solve your problem, but it's too big to address in the comments.</p>\n\n<p>First, you need to use <code>add_action()</code>, <em>not</em> <code>add_filter()</code>. That by itself is not a <em>huge</em> deal because <code>add_action()</code> is just a wrapper for <code>add_filter()</code>, but you should still use the correct one.</p>\n\n<p>The other problem may be your passed arguments. </p>\n\n<blockquote>\n <p>I know that, as a matter of fact, three arguments are passed in the\n line I quoted above (namely a null, the refund object and the refund\n id),</p>\n</blockquote>\n\n<p>Actually, the way you have it, you're not passing three arguments, you're only passing one. But your function as written is expecting three.</p>\n\n<p>Your <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow noreferrer\"><code>add_action()</code></a> uses the required <code>$tag</code> and <code>$function_to_add</code> values, but leaves off the optional <code>$priority</code> and <code>$accepted_args</code>. The default of <code>$accepted_args</code> is \"1\", so anytime you're passing more than a single value with <code>add_action()</code> or <code>add_filter()</code>, you <strong><em>must</em></strong> define the <code>$accepted_args</code> value.</p>\n\n<p>Try it as follows, noting the final value of \"3\" - that's the <code>$accepted_args</code> value that tells it to pass more than 1 argument:</p>\n\n<pre><code>add_action('woocommerce_admin_order_item_values', 'test_refund_id', 10, 3 );\nfunction test_refund_id($nullvar, $refund, $refund_id) {\n if ( !empty($refund->refunded_by) ){\n echo '<td>Refund ID: '.$refund_id.'</td>'; \n }\n}\n</code></pre>\n"
},
{
"answer_id": 354283,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": false,
"text": "<p>There's a fundamental misunderstanding here about how filters and actions work, here is the flaw in your thinking:</p>\n\n<blockquote>\n <p>I know that, as a matter of fact, three arguments are passed in</p>\n</blockquote>\n\n<p>A closer inspection of <code>add_action</code> and <code>add_filter</code> reveals:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )\n</code></pre>\n\n<p>Notice the <code>$accepted_args</code> parameter. Because it isn't present in the call to <code>add_filter</code> in your question, it defaults to 1. To get 3 all parameters you need to specify 3. This is because not all filters need all parameters, and it can be useful to use other functions that can't accept all the parameters when only the first is needed. E.g. PHP internal math functions</p>\n\n<p>Additional notes:</p>\n\n<ul>\n<li>you used <code>add_filter</code>, but it was an action that got called, <code>add_action</code> should be used for actions, and <code>add_filter</code> for filters</li>\n<li>3rd party plugins are offtopic, the only reason your Q could be answered here is because it can be answered without knowledge of WooCommerce. The specifics about how that plugins internals work are not on topic here</li>\n<li>You need to add escaping to <code>$refund_id</code>, the lack of escaping is a security hole. <code>esc_html</code> should do the job</li>\n<li>Never modify WP Core internals, a quick look at the documentation almost always gives the answer</li>\n</ul>\n"
}
] | 2019/12/10 | [
"https://wordpress.stackexchange.com/questions/354281",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97921/"
] | I'm trying to add a button (its function is beyond the scope of this question, suffice it to say that it needs the refund id as an argument) to each refund line in a WooCommerce order. I found that those lines are created in woocommerce\includes\admin\meta-boxes\views\html-order-refund.php which can't be overridden. However there is an action:
```
do_action( 'woocommerce_admin_order_item_values', null, $refund, $refund->get_id() );
```
This seemed perfect for my purpose, so I tried adding the following code to functions.php to test if it could work:
```
add_filter('woocommerce_admin_order_item_values', 'test_refund_id');
function test_refund_id($nullvar, $refund, $refund_id) {
if ( !empty($refund->refunded_by) ){
echo '<td>Refund ID: '.$refund_id.'</td>';
}
}
```
I used `if ( !empty($refund->refunded_by) )` because `woocommerce_admin_order_item_values` also gets called in html-order-shipping.php, html-order-item.php and html-order-fee.php, with an "order item" object (instead of a "refund" object) as the second argument, so there's no `refunded_by` property and my instruction should be ignored.
Much to my disappointment, though, I get the following error:
>
> Fatal error: Uncaught ArgumentCountError: Too few arguments to
> function test\_refund\_id(), 1 passed in \wp-includes\class-wp-hook.php
> on line 290 and exactly 3 expected in
> \wp-content\themes\mytheme\functions.php:1087
>
>
>
I know that, as a matter of fact, three arguments are passed in the line I quoted above (namely a null, the refund object and the refund id), but I went and checked the script the error was referring to (\wp-includes\class-wp-hook.php) around line 290, and I found this in the `apply_filters()` function:
```
// Avoid the array_slice if possible.
if ( $the_['accepted_args'] == 0 ) {
$value = call_user_func( $the_['function'] );
} elseif ( $the_['accepted_args'] >= $num_args ) {
$value = call_user_func_array( $the_['function'], $args );
} else {
$value = call_user_func_array( $the_['function'], array_slice( $args, 0, (int) $the_['accepted_args'] ) );
}
```
Just for testing purposes I tried to temporarily change the last "else" clause, replacing the "sliced" arguments array with the original one, thereby forcing the script to keep all the arguments anyway, so `array_slice( $args, 0, (int) $the_['accepted_args'] )` became simply `$args`. Surprise, surprise, now everything works smoothly!
[](https://i.stack.imgur.com/6GmSo.jpg)
Now, I'm well aware that's of course not a solution since I can't edit a core WP script. I would just want to understand WHY `apply_filters()` thinks that the accepted arguments are less than the passed ones and therefore it trims the argument array down to just the first one.
Thanks a lot in advance to anyone who'd like to shed some light on the matter. | Two inherent problems with your script as posted. I'm not certain this will solve your problem, but it's too big to address in the comments.
First, you need to use `add_action()`, *not* `add_filter()`. That by itself is not a *huge* deal because `add_action()` is just a wrapper for `add_filter()`, but you should still use the correct one.
The other problem may be your passed arguments.
>
> I know that, as a matter of fact, three arguments are passed in the
> line I quoted above (namely a null, the refund object and the refund
> id),
>
>
>
Actually, the way you have it, you're not passing three arguments, you're only passing one. But your function as written is expecting three.
Your [`add_action()`](https://developer.wordpress.org/reference/functions/add_action/) uses the required `$tag` and `$function_to_add` values, but leaves off the optional `$priority` and `$accepted_args`. The default of `$accepted_args` is "1", so anytime you're passing more than a single value with `add_action()` or `add_filter()`, you ***must*** define the `$accepted_args` value.
Try it as follows, noting the final value of "3" - that's the `$accepted_args` value that tells it to pass more than 1 argument:
```
add_action('woocommerce_admin_order_item_values', 'test_refund_id', 10, 3 );
function test_refund_id($nullvar, $refund, $refund_id) {
if ( !empty($refund->refunded_by) ){
echo '<td>Refund ID: '.$refund_id.'</td>';
}
}
``` |
354,353 | <p>I am having a filter for the content that adds a Table of Contents at the top of my posts. I took the basic idea from an answer at Stack Exchange itself.</p>
<p>I add the filter as follows:</p>
<pre><code>add_filter('the_content', array('TableOfContents', 'writeTOC'), 100);
</code></pre>
<p>And until here it is fine, but the problem comes in another function. There is a function in my plugin that takes the first 144 characters of the given post and coverts it into the Meta Description. Now due to the filter mentioned above, the Meta Description doesn't contain the actual content of my post.</p>
<pre><code> $meta = apply_filters('the_content', $post->post_content);
$meta = strip_tags($meta);
$meta = strip_shortcodes($meta );
$meta = str_replace(array("\n", "\r", "\t"), ' ', $meta);
$meta = substr($meta, 0, 144);
</code></pre>
<p>Rather, my meta description has the first 144 characters including the Table of Contents.</p>
<p>I want to exclude the Table of Contents from my Meta Description, but re-positioning the code did no help. </p>
<p>Below I have attached the full code:</p>
<pre><code><?php
function Milyin_Head(){
global $post;
if (!is_page()) {
if (!is_singular() ) {return; }
elseif (!empty( $post->post_excerpt)) {
$meta = $post->post_excerpt ;
}
else {
// THIS IS MY PROBLEM LINE, i USE Apply Filters for post content....
$meta = apply_filters('the_content', $post->post_content);
$meta = strip_tags($meta);
$meta = strip_shortcodes($meta );
$meta = str_replace(array("\n", "\r", "\t"), ' ', $meta);
$meta = substr($meta, 0, 175);
echo '<meta name="description" content="'. $meta . '"/>';
echo '<meta name="og:description" content="'. $meta . '"/>';
echo '<meta name="twitter:description" content="'. $meta . '"/>';
}
}
else {
echo '<meta name="description" content="Milyin Devotes to Make A World Having Vast Majority Of People Who are Passionate About There Work, Who feel proud to have different Thoughts, Beliefs and Opinions. Milyin Supports all those who Improve Society and bring a change."/>';
echo '<meta name="og:description" content="Milyin Devotes to Make A World Having Vast Majority Of People Who are Passionate About There Work, Who feel proud to have different Thoughts, Beliefs and Opinions. Milyin Supports all those who Improve Society and bring a change."/>';
echo '<meta name="twitter:description" content="Milyin Devotes to Make A World Having Vast Majority Of People Who are Passionate About There Work, Who feel proud to have different Thoughts, Beliefs and Opinions. Milyin Supports all those who Improve Society and bring a change."/>';
}
}
add_action('wp_head', 'Milyin_Head');
//This Function is Now Over, the Next Function Generates the Table Of Content
// Below is the Table Of Content Class, i added this for the sake of someone who wants to actually understand and in depth analyse my code. Its better to just move to bottom where i Apply The Filter
class TableOfContents {
/**
* Counts the occurence of header elements in Wordpress content
*
* @param type $content
* @return null|boolean|array
*/
static function hasToc($tiers, $content) {
$pattern = '/<h[1-' . $tiers . ']*[^>]*>(.*?)<\/h([1-' . $tiers . '])>/';
$return = array();
if (empty($content))
return null;
if (!preg_match_all($pattern, $content, $return)) {
return false;
}
return $return;
}
/**
* Generates a table of content only when singular pages are being viewed
*
* @param type $tiers
* @param type $text
*/
static function generateTableOfContents($tiers, $content, $draw = TRUE, $return = array()) {
if (!is_singular())
return $content;
$content = $toc . $content;
$searches = array();
$replaces = array();
$return = (is_array($return) && !empty($return) ) ? $return : TableOfContents::hasToc($tiers, $content);
if ($draw && !empty($return)):
$toc = '<div class="Milyin-Container">';
$toc .= "<span style=\"font-size:18px;\">Table of Contents</span>";
$toc .= "<span style=\"float:right; width: 30px;height: 30px;margin: 5px;\" data-toggle=\"collapse\" data-target=\".list\">";
$toc .= '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve"><g><g><path d="M491.318,235.318H20.682C9.26,235.318,0,244.577,0,256s9.26,20.682,20.682,20.682h470.636 c11.423,0,20.682-9.259,20.682-20.682C512,244.578,502.741,235.318,491.318,235.318z"/></g></g><g><g><path d="M491.318,78.439H20.682C9.26,78.439,0,87.699,0,99.121c0,11.422,9.26,20.682,20.682,20.682h470.636 c11.423,0,20.682-9.26,20.682-20.682C512,87.699,502.741,78.439,491.318,78.439z"/></g></g><g><g><path d="M491.318,392.197H20.682C9.26,392.197,0,401.456,0,412.879s9.26,20.682,20.682,20.682h470.636 c11.423,0,20.682-9.259,20.682-20.682S502.741,392.197,491.318,392.197z"/></g></g></svg></span>' ;
$toc .= "<div class=\"list collapse\">";
$toc .= "<ul class=\"parent start\">";
$tags = reset($return);
$titles = $return[1];
$url = $return[1];
$levels = end($return);
$_level = 2;
$chapters = array('0','0','0','0','0','0');
$count = 0;
foreach ($tags as $i => $htag) {
$count++;
$attributes = array();
$href = $url[$i];
$href = strtolower($href);
strip_tags($href);
$href = preg_replace("/[^a-z0-9_\s-]/", "", $href);
$href = preg_replace("/[\s-]+/", " ", $href);
$href = preg_replace("/[\s_]/", "-", $href);
$newId = 'id="' . $href . '"';
$newhtag = $newId . '>';
$htagr = str_replace('>' . $titles[$i], "\t" . $newhtag . $titles[$i], $htag);
$searches[] = $htag;
$replaces[] = $htagr;
if ((int)$levels[$i] === (int)$_level):
$chapters[$_level-1] = ((int)$chapters[$_level-1]+1);
$chapter = implode('.', array_slice($chapters, 1, ($levels[$i]-1) ) );
$toc .= '<li><span>' . strval($chapter) . '</span> <a href="#' . $href . '">' . $titles[$i] . '</a></li>';
endif;
if ($levels[$i] > $_level) {
$_steps = ((int) $levels[$i] - (int) $_level);
for ($j = 0; $j < $_steps; $j++):
$toc .= '<ol class="continue">';
$chapters[$levels[$i]-1+$j] = (int)$chapters[$levels[$i]-1+$j]+1;
$_level++;
endfor;
$chapter = implode('.', array_slice($chapters, 1, ($levels[$i]-1) ) );
$toc .= '<li><a href="#' . $href . '">' . $titles[$i] . '</a></li>';
}
if ($levels[$i] < $_level) {
$_steps = ((int) $_level - (int) $levels[$i]);
$chapters[$levels[$i]-1] = (int)$chapters[$levels[$i]-1]+1;
$_olevel = $_level;
for ($j = 0; $j < $_steps; $j++):
$chapters[$levels[$i]+$j] = 0;
$toc .= '</ol>';
$_level--;
endfor;
$chapters[$_olevel-1] = 0;
$chapter = implode('.', array_slice($chapters, 1, ($levels[$i]-1) ) );
$toc .= '<li><a href="#' . $href . '">' . $titles[$i] . '</a></li>';
}
}
$toc .= '</ul>';
$toc .= '</div></div><div class="clear"></div>';
$content = str_replace($searches, $replaces, $content);
$content = $toc . $content;
endif;
return $content;
}
/**
* Appends the table of content to the $content
* AKA. Executes our filter
*
* @param type $content
* @return type
*/
static function writeToc($content) {
$content = TableOfContents::generateTableOfContents(4, $content, TRUE);
return $content;
}
}
add_filter('the_content', array('TableOfContents', 'writeTOC'), 100);
// The Above Line Adds the Table Of Content Before The Post Content
// Problem is that in the first function of code, i want it to exclude this filter. I don't want the Table Of Content text to become my Meta Description
?>
</code></pre>
| [
{
"answer_id": 354354,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 0,
"selected": false,
"text": "<p>There might be a better way to do this, but without knowing the full extent of the process (other than the ToC), here's a quick and simple way that might solve the problem.</p>\n\n<p>Before the content is filtered for the ToC, why not put the original content into a variable you can pick up later?</p>\n\n<p>I edited your code an added a static variable <code>$pre_toc_content</code>. Then, when the <code>generateTableOfContents()</code> function is run, at the beginning before anything else is done to it, the unfiltered content is put into the variable.</p>\n\n<p>You can pick up the unfiltered content to use later, instead of the filtered result:</p>\n\n<pre><code> $meta = TableOfContents::$pre_toc_content;\n $meta = strip_tags($meta);\n $meta = strip_shortcodes($meta );\n $meta = str_replace(array(\"\\n\", \"\\r\", \"\\t\"), ' ', $meta);\n $meta = substr($meta, 0, 144);\n</code></pre>\n\n<p>Here's your code with the change (it's relatively minor, and commented accordingly):</p>\n\n<pre><code><?php\nfunction Milyin_Head(){ \n\nglobal $post; \nif (!is_page()) { \n if (!is_singular() ) {return; }\n elseif (!empty( $post->post_excerpt)) {\n $meta = $post->post_excerpt ; \n} \n else {\n // THIS IS MY PROBLEM LINE, i USE Apply Filters for post content....\n // $meta = apply_filters('the_content', $post->post_content);\n\n // Trying it here with a static variable \n $meta = TableOfContents::$pre_toc_content;\n\n // Or uncomment below to use a global variable\n global $global_pre_toc_content;\n // $meta = $global_pre_toc_content;\n\n $meta = strip_tags($meta);\n $meta = strip_shortcodes($meta );\n $meta = str_replace(array(\"\\n\", \"\\r\", \"\\t\"), ' ', $meta);\n $meta = substr($meta, 0, 175);\necho '<meta name=\"description\" content=\"'. $meta . '\"/>'; \necho '<meta name=\"og:description\" content=\"'. $meta . '\"/>';\necho '<meta name=\"twitter:description\" content=\"'. $meta . '\"/>';\n}\n}\nelse {\necho '<meta name=\"description\" content=\"Milyin Devotes to Make A World Having Vast Majority Of People Who are Passionate About There Work, Who feel proud to have different Thoughts, Beliefs and Opinions. Milyin Supports all those who Improve Society and bring a change.\"/>'; \necho '<meta name=\"og:description\" content=\"Milyin Devotes to Make A World Having Vast Majority Of People Who are Passionate About There Work, Who feel proud to have different Thoughts, Beliefs and Opinions. Milyin Supports all those who Improve Society and bring a change.\"/>';\necho '<meta name=\"twitter:description\" content=\"Milyin Devotes to Make A World Having Vast Majority Of People Who are Passionate About There Work, Who feel proud to have different Thoughts, Beliefs and Opinions. Milyin Supports all those who Improve Society and bring a change.\"/>';\n\n}\n }\nadd_action('wp_head', 'Milyin_Head');\n\n\n//This Function is Now Over, the Next Function Generates the Table Of Content\n\n// Below is the Table Of Content Class, i added this for the sake of someone who wants to actually understand and in depth analyse my code. Its better to just move to bottom where i Apply The Filter\n\nclass TableOfContents {\n\n /**\n * A container for the unfiltered content.\n */\n static $pre_toc_content;\n\n /**\n * Counts the occurence of header elements in Wordpress content\n * \n * @param type $content\n * @return null|boolean|array\n */\n static function hasToc($tiers, $content) {\n\n $pattern = '/<h[1-' . $tiers . ']*[^>]*>(.*?)<\\/h([1-' . $tiers . '])>/';\n $return = array();\n if (empty($content))\n return null;\n\n if (!preg_match_all($pattern, $content, $return)) {\n return false;\n }\n return $return;\n }\n\n /**\n * Generates a table of content only when singular pages are being viewed\n * \n * @param type $tiers\n * @param type $text\n */\n static function generateTableOfContents($tiers, $content, $draw = TRUE, $return = array()) {\n\n if (!is_singular())\n return $content;\n\n $content = $toc . $content;\n $searches = array();\n $replaces = array();\n $return = (is_array($return) && !empty($return) ) ? $return : TableOfContents::hasToc($tiers, $content);\n\n if ($draw && !empty($return)):\n $toc = '<div class=\"Milyin-Container\">';\n $toc .= \"<span style=\\\"font-size:18px;\\\">Table of Contents</span>\";\n $toc .= \"<span style=\\\"float:right; width: 30px;height: 30px;margin: 5px;\\\" data-toggle=\\\"collapse\\\" data-target=\\\".list\\\">\";\n $toc .= '<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.1\" id=\"Layer_1\" x=\"0px\" y=\"0px\" viewBox=\"0 0 512 512\" style=\"enable-background:new 0 0 512 512;\" xml:space=\"preserve\"><g><g><path d=\"M491.318,235.318H20.682C9.26,235.318,0,244.577,0,256s9.26,20.682,20.682,20.682h470.636 c11.423,0,20.682-9.259,20.682-20.682C512,244.578,502.741,235.318,491.318,235.318z\"/></g></g><g><g><path d=\"M491.318,78.439H20.682C9.26,78.439,0,87.699,0,99.121c0,11.422,9.26,20.682,20.682,20.682h470.636 c11.423,0,20.682-9.26,20.682-20.682C512,87.699,502.741,78.439,491.318,78.439z\"/></g></g><g><g><path d=\"M491.318,392.197H20.682C9.26,392.197,0,401.456,0,412.879s9.26,20.682,20.682,20.682h470.636 c11.423,0,20.682-9.259,20.682-20.682S502.741,392.197,491.318,392.197z\"/></g></g></svg></span>' ;\n $toc .= \"<div class=\\\"list collapse\\\">\";\n $toc .= \"<ul class=\\\"parent start\\\">\";\n $tags = reset($return);\n $titles = $return[1];\n $url = $return[1];\n $levels = end($return);\n $_level = 2;\n $chapters = array('0','0','0','0','0','0');\n\n $count = 0;\n foreach ($tags as $i => $htag) {\n $count++;\n $attributes = array();\n $href = $url[$i];\n $href = strtolower($href);\n strip_tags($href);\n $href = preg_replace(\"/[^a-z0-9_\\s-]/\", \"\", $href);\n $href = preg_replace(\"/[\\s-]+/\", \" \", $href);\n $href = preg_replace(\"/[\\s_]/\", \"-\", $href);\n\n\n $newId = 'id=\"' . $href . '\"';\n $newhtag = $newId . '>';\n $htagr = str_replace('>' . $titles[$i], \"\\t\" . $newhtag . $titles[$i], $htag);\n $searches[] = $htag;\n $replaces[] = $htagr;\n\n\n if ((int)$levels[$i] === (int)$_level):\n $chapters[$_level-1] = ((int)$chapters[$_level-1]+1);\n $chapter = implode('.', array_slice($chapters, 1, ($levels[$i]-1) ) );\n $toc .= '<li><span>' . strval($chapter) . '</span> <a href=\"#' . $href . '\">' . $titles[$i] . '</a></li>';\n endif;\n\n if ($levels[$i] > $_level) {\n $_steps = ((int) $levels[$i] - (int) $_level);\n\n for ($j = 0; $j < $_steps; $j++):\n $toc .= '<ol class=\"continue\">';\n $chapters[$levels[$i]-1+$j] = (int)$chapters[$levels[$i]-1+$j]+1;\n $_level++;\n endfor;\n $chapter = implode('.', array_slice($chapters, 1, ($levels[$i]-1) ) );\n $toc .= '<li><a href=\"#' . $href . '\">' . $titles[$i] . '</a></li>';\n }\n\n if ($levels[$i] < $_level) {\n\n $_steps = ((int) $_level - (int) $levels[$i]);\n $chapters[$levels[$i]-1] = (int)$chapters[$levels[$i]-1]+1;\n $_olevel = $_level;\n for ($j = 0; $j < $_steps; $j++):\n $chapters[$levels[$i]+$j] = 0;\n $toc .= '</ol>';\n $_level--;\n endfor;\n\n $chapters[$_olevel-1] = 0;\n $chapter = implode('.', array_slice($chapters, 1, ($levels[$i]-1) ) );\n\n $toc .= '<li><a href=\"#' . $href . '\">' . $titles[$i] . '</a></li>';\n\n }\n }\n $toc .= '</ul>';\n $toc .= '</div></div><div class=\"clear\"></div>';\n $content = str_replace($searches, $replaces, $content);\n $content = $toc . $content;\n endif;\n\n return $content;\n }\n\n /**\n * Appends the table of content to the $content\n * AKA. Executes our filter\n * \n * @param type $content\n * @return type\n */\n static function writeToc($content) {\n\n // Put original $content into a var you can pick up later\n self::$pre_toc_content = $content;\n\n // Or alternatively, use a global\n global $global_pre_toc_content;\n $global_pre_toc_content = $content;\n\n $content = TableOfContents::generateTableOfContents(4, $content, TRUE);\n return $content;\n }\n\n}\n\nadd_filter('the_content', array('TableOfContents', 'writeTOC'), 100);\n\n// The Above Line Adds the Table Of Content Before The Post Content\n// Problem is that in the first function of code, i want it to exclude this filter. I don't want the Table Of Content text to become my Meta Description\n\n\n?>\n</code></pre>\n"
},
{
"answer_id": 354395,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 3,
"selected": true,
"text": "<p>You can temporarily detach the function from the hook.</p>\n\n<pre><code> // THIS IS MY PROBLEM LINE, i USE Apply Filters for post content....\n\n $priority = has_filter('the_content', ['TableOfContents', 'writeTOC'] );\n if ( $priority !== false )\n remove_filter('the_content', ['TableOfContents', 'writeTOC'], $priority );\n\n $meta = apply_filters('the_content', $post->post_content);\n\n if ( $priority !== false )\n add_filter('the_content', ['TableOfContents', 'writeTOC'], $priority );\n\n\n $meta = strip_tags($meta);\n $meta = strip_shortcodes($meta );\n</code></pre>\n\n<p><strong>Codex:</strong> </p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/has_filter\" rel=\"nofollow noreferrer\">has_filter()</a> </li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/remove_filter/\" rel=\"nofollow noreferrer\">remove_filter()</a> </li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/add_filter/\" rel=\"nofollow noreferrer\">add_filter()</a> </li>\n</ul>\n"
}
] | 2019/12/11 | [
"https://wordpress.stackexchange.com/questions/354353",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/166927/"
] | I am having a filter for the content that adds a Table of Contents at the top of my posts. I took the basic idea from an answer at Stack Exchange itself.
I add the filter as follows:
```
add_filter('the_content', array('TableOfContents', 'writeTOC'), 100);
```
And until here it is fine, but the problem comes in another function. There is a function in my plugin that takes the first 144 characters of the given post and coverts it into the Meta Description. Now due to the filter mentioned above, the Meta Description doesn't contain the actual content of my post.
```
$meta = apply_filters('the_content', $post->post_content);
$meta = strip_tags($meta);
$meta = strip_shortcodes($meta );
$meta = str_replace(array("\n", "\r", "\t"), ' ', $meta);
$meta = substr($meta, 0, 144);
```
Rather, my meta description has the first 144 characters including the Table of Contents.
I want to exclude the Table of Contents from my Meta Description, but re-positioning the code did no help.
Below I have attached the full code:
```
<?php
function Milyin_Head(){
global $post;
if (!is_page()) {
if (!is_singular() ) {return; }
elseif (!empty( $post->post_excerpt)) {
$meta = $post->post_excerpt ;
}
else {
// THIS IS MY PROBLEM LINE, i USE Apply Filters for post content....
$meta = apply_filters('the_content', $post->post_content);
$meta = strip_tags($meta);
$meta = strip_shortcodes($meta );
$meta = str_replace(array("\n", "\r", "\t"), ' ', $meta);
$meta = substr($meta, 0, 175);
echo '<meta name="description" content="'. $meta . '"/>';
echo '<meta name="og:description" content="'. $meta . '"/>';
echo '<meta name="twitter:description" content="'. $meta . '"/>';
}
}
else {
echo '<meta name="description" content="Milyin Devotes to Make A World Having Vast Majority Of People Who are Passionate About There Work, Who feel proud to have different Thoughts, Beliefs and Opinions. Milyin Supports all those who Improve Society and bring a change."/>';
echo '<meta name="og:description" content="Milyin Devotes to Make A World Having Vast Majority Of People Who are Passionate About There Work, Who feel proud to have different Thoughts, Beliefs and Opinions. Milyin Supports all those who Improve Society and bring a change."/>';
echo '<meta name="twitter:description" content="Milyin Devotes to Make A World Having Vast Majority Of People Who are Passionate About There Work, Who feel proud to have different Thoughts, Beliefs and Opinions. Milyin Supports all those who Improve Society and bring a change."/>';
}
}
add_action('wp_head', 'Milyin_Head');
//This Function is Now Over, the Next Function Generates the Table Of Content
// Below is the Table Of Content Class, i added this for the sake of someone who wants to actually understand and in depth analyse my code. Its better to just move to bottom where i Apply The Filter
class TableOfContents {
/**
* Counts the occurence of header elements in Wordpress content
*
* @param type $content
* @return null|boolean|array
*/
static function hasToc($tiers, $content) {
$pattern = '/<h[1-' . $tiers . ']*[^>]*>(.*?)<\/h([1-' . $tiers . '])>/';
$return = array();
if (empty($content))
return null;
if (!preg_match_all($pattern, $content, $return)) {
return false;
}
return $return;
}
/**
* Generates a table of content only when singular pages are being viewed
*
* @param type $tiers
* @param type $text
*/
static function generateTableOfContents($tiers, $content, $draw = TRUE, $return = array()) {
if (!is_singular())
return $content;
$content = $toc . $content;
$searches = array();
$replaces = array();
$return = (is_array($return) && !empty($return) ) ? $return : TableOfContents::hasToc($tiers, $content);
if ($draw && !empty($return)):
$toc = '<div class="Milyin-Container">';
$toc .= "<span style=\"font-size:18px;\">Table of Contents</span>";
$toc .= "<span style=\"float:right; width: 30px;height: 30px;margin: 5px;\" data-toggle=\"collapse\" data-target=\".list\">";
$toc .= '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve"><g><g><path d="M491.318,235.318H20.682C9.26,235.318,0,244.577,0,256s9.26,20.682,20.682,20.682h470.636 c11.423,0,20.682-9.259,20.682-20.682C512,244.578,502.741,235.318,491.318,235.318z"/></g></g><g><g><path d="M491.318,78.439H20.682C9.26,78.439,0,87.699,0,99.121c0,11.422,9.26,20.682,20.682,20.682h470.636 c11.423,0,20.682-9.26,20.682-20.682C512,87.699,502.741,78.439,491.318,78.439z"/></g></g><g><g><path d="M491.318,392.197H20.682C9.26,392.197,0,401.456,0,412.879s9.26,20.682,20.682,20.682h470.636 c11.423,0,20.682-9.259,20.682-20.682S502.741,392.197,491.318,392.197z"/></g></g></svg></span>' ;
$toc .= "<div class=\"list collapse\">";
$toc .= "<ul class=\"parent start\">";
$tags = reset($return);
$titles = $return[1];
$url = $return[1];
$levels = end($return);
$_level = 2;
$chapters = array('0','0','0','0','0','0');
$count = 0;
foreach ($tags as $i => $htag) {
$count++;
$attributes = array();
$href = $url[$i];
$href = strtolower($href);
strip_tags($href);
$href = preg_replace("/[^a-z0-9_\s-]/", "", $href);
$href = preg_replace("/[\s-]+/", " ", $href);
$href = preg_replace("/[\s_]/", "-", $href);
$newId = 'id="' . $href . '"';
$newhtag = $newId . '>';
$htagr = str_replace('>' . $titles[$i], "\t" . $newhtag . $titles[$i], $htag);
$searches[] = $htag;
$replaces[] = $htagr;
if ((int)$levels[$i] === (int)$_level):
$chapters[$_level-1] = ((int)$chapters[$_level-1]+1);
$chapter = implode('.', array_slice($chapters, 1, ($levels[$i]-1) ) );
$toc .= '<li><span>' . strval($chapter) . '</span> <a href="#' . $href . '">' . $titles[$i] . '</a></li>';
endif;
if ($levels[$i] > $_level) {
$_steps = ((int) $levels[$i] - (int) $_level);
for ($j = 0; $j < $_steps; $j++):
$toc .= '<ol class="continue">';
$chapters[$levels[$i]-1+$j] = (int)$chapters[$levels[$i]-1+$j]+1;
$_level++;
endfor;
$chapter = implode('.', array_slice($chapters, 1, ($levels[$i]-1) ) );
$toc .= '<li><a href="#' . $href . '">' . $titles[$i] . '</a></li>';
}
if ($levels[$i] < $_level) {
$_steps = ((int) $_level - (int) $levels[$i]);
$chapters[$levels[$i]-1] = (int)$chapters[$levels[$i]-1]+1;
$_olevel = $_level;
for ($j = 0; $j < $_steps; $j++):
$chapters[$levels[$i]+$j] = 0;
$toc .= '</ol>';
$_level--;
endfor;
$chapters[$_olevel-1] = 0;
$chapter = implode('.', array_slice($chapters, 1, ($levels[$i]-1) ) );
$toc .= '<li><a href="#' . $href . '">' . $titles[$i] . '</a></li>';
}
}
$toc .= '</ul>';
$toc .= '</div></div><div class="clear"></div>';
$content = str_replace($searches, $replaces, $content);
$content = $toc . $content;
endif;
return $content;
}
/**
* Appends the table of content to the $content
* AKA. Executes our filter
*
* @param type $content
* @return type
*/
static function writeToc($content) {
$content = TableOfContents::generateTableOfContents(4, $content, TRUE);
return $content;
}
}
add_filter('the_content', array('TableOfContents', 'writeTOC'), 100);
// The Above Line Adds the Table Of Content Before The Post Content
// Problem is that in the first function of code, i want it to exclude this filter. I don't want the Table Of Content text to become my Meta Description
?>
``` | You can temporarily detach the function from the hook.
```
// THIS IS MY PROBLEM LINE, i USE Apply Filters for post content....
$priority = has_filter('the_content', ['TableOfContents', 'writeTOC'] );
if ( $priority !== false )
remove_filter('the_content', ['TableOfContents', 'writeTOC'], $priority );
$meta = apply_filters('the_content', $post->post_content);
if ( $priority !== false )
add_filter('the_content', ['TableOfContents', 'writeTOC'], $priority );
$meta = strip_tags($meta);
$meta = strip_shortcodes($meta );
```
**Codex:**
* [has\_filter()](https://codex.wordpress.org/Function_Reference/has_filter)
* [remove\_filter()](https://developer.wordpress.org/reference/functions/remove_filter/)
* [add\_filter()](https://developer.wordpress.org/reference/functions/add_filter/) |
354,357 | <p>In my plugin, I have a custom post type with a specific behaviour. </p>
<p>The administrator after to publish it, he should not be able to set the post as draft again.</p>
<p>How can I do this ?</p>
| [
{
"answer_id": 354354,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 0,
"selected": false,
"text": "<p>There might be a better way to do this, but without knowing the full extent of the process (other than the ToC), here's a quick and simple way that might solve the problem.</p>\n\n<p>Before the content is filtered for the ToC, why not put the original content into a variable you can pick up later?</p>\n\n<p>I edited your code an added a static variable <code>$pre_toc_content</code>. Then, when the <code>generateTableOfContents()</code> function is run, at the beginning before anything else is done to it, the unfiltered content is put into the variable.</p>\n\n<p>You can pick up the unfiltered content to use later, instead of the filtered result:</p>\n\n<pre><code> $meta = TableOfContents::$pre_toc_content;\n $meta = strip_tags($meta);\n $meta = strip_shortcodes($meta );\n $meta = str_replace(array(\"\\n\", \"\\r\", \"\\t\"), ' ', $meta);\n $meta = substr($meta, 0, 144);\n</code></pre>\n\n<p>Here's your code with the change (it's relatively minor, and commented accordingly):</p>\n\n<pre><code><?php\nfunction Milyin_Head(){ \n\nglobal $post; \nif (!is_page()) { \n if (!is_singular() ) {return; }\n elseif (!empty( $post->post_excerpt)) {\n $meta = $post->post_excerpt ; \n} \n else {\n // THIS IS MY PROBLEM LINE, i USE Apply Filters for post content....\n // $meta = apply_filters('the_content', $post->post_content);\n\n // Trying it here with a static variable \n $meta = TableOfContents::$pre_toc_content;\n\n // Or uncomment below to use a global variable\n global $global_pre_toc_content;\n // $meta = $global_pre_toc_content;\n\n $meta = strip_tags($meta);\n $meta = strip_shortcodes($meta );\n $meta = str_replace(array(\"\\n\", \"\\r\", \"\\t\"), ' ', $meta);\n $meta = substr($meta, 0, 175);\necho '<meta name=\"description\" content=\"'. $meta . '\"/>'; \necho '<meta name=\"og:description\" content=\"'. $meta . '\"/>';\necho '<meta name=\"twitter:description\" content=\"'. $meta . '\"/>';\n}\n}\nelse {\necho '<meta name=\"description\" content=\"Milyin Devotes to Make A World Having Vast Majority Of People Who are Passionate About There Work, Who feel proud to have different Thoughts, Beliefs and Opinions. Milyin Supports all those who Improve Society and bring a change.\"/>'; \necho '<meta name=\"og:description\" content=\"Milyin Devotes to Make A World Having Vast Majority Of People Who are Passionate About There Work, Who feel proud to have different Thoughts, Beliefs and Opinions. Milyin Supports all those who Improve Society and bring a change.\"/>';\necho '<meta name=\"twitter:description\" content=\"Milyin Devotes to Make A World Having Vast Majority Of People Who are Passionate About There Work, Who feel proud to have different Thoughts, Beliefs and Opinions. Milyin Supports all those who Improve Society and bring a change.\"/>';\n\n}\n }\nadd_action('wp_head', 'Milyin_Head');\n\n\n//This Function is Now Over, the Next Function Generates the Table Of Content\n\n// Below is the Table Of Content Class, i added this for the sake of someone who wants to actually understand and in depth analyse my code. Its better to just move to bottom where i Apply The Filter\n\nclass TableOfContents {\n\n /**\n * A container for the unfiltered content.\n */\n static $pre_toc_content;\n\n /**\n * Counts the occurence of header elements in Wordpress content\n * \n * @param type $content\n * @return null|boolean|array\n */\n static function hasToc($tiers, $content) {\n\n $pattern = '/<h[1-' . $tiers . ']*[^>]*>(.*?)<\\/h([1-' . $tiers . '])>/';\n $return = array();\n if (empty($content))\n return null;\n\n if (!preg_match_all($pattern, $content, $return)) {\n return false;\n }\n return $return;\n }\n\n /**\n * Generates a table of content only when singular pages are being viewed\n * \n * @param type $tiers\n * @param type $text\n */\n static function generateTableOfContents($tiers, $content, $draw = TRUE, $return = array()) {\n\n if (!is_singular())\n return $content;\n\n $content = $toc . $content;\n $searches = array();\n $replaces = array();\n $return = (is_array($return) && !empty($return) ) ? $return : TableOfContents::hasToc($tiers, $content);\n\n if ($draw && !empty($return)):\n $toc = '<div class=\"Milyin-Container\">';\n $toc .= \"<span style=\\\"font-size:18px;\\\">Table of Contents</span>\";\n $toc .= \"<span style=\\\"float:right; width: 30px;height: 30px;margin: 5px;\\\" data-toggle=\\\"collapse\\\" data-target=\\\".list\\\">\";\n $toc .= '<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.1\" id=\"Layer_1\" x=\"0px\" y=\"0px\" viewBox=\"0 0 512 512\" style=\"enable-background:new 0 0 512 512;\" xml:space=\"preserve\"><g><g><path d=\"M491.318,235.318H20.682C9.26,235.318,0,244.577,0,256s9.26,20.682,20.682,20.682h470.636 c11.423,0,20.682-9.259,20.682-20.682C512,244.578,502.741,235.318,491.318,235.318z\"/></g></g><g><g><path d=\"M491.318,78.439H20.682C9.26,78.439,0,87.699,0,99.121c0,11.422,9.26,20.682,20.682,20.682h470.636 c11.423,0,20.682-9.26,20.682-20.682C512,87.699,502.741,78.439,491.318,78.439z\"/></g></g><g><g><path d=\"M491.318,392.197H20.682C9.26,392.197,0,401.456,0,412.879s9.26,20.682,20.682,20.682h470.636 c11.423,0,20.682-9.259,20.682-20.682S502.741,392.197,491.318,392.197z\"/></g></g></svg></span>' ;\n $toc .= \"<div class=\\\"list collapse\\\">\";\n $toc .= \"<ul class=\\\"parent start\\\">\";\n $tags = reset($return);\n $titles = $return[1];\n $url = $return[1];\n $levels = end($return);\n $_level = 2;\n $chapters = array('0','0','0','0','0','0');\n\n $count = 0;\n foreach ($tags as $i => $htag) {\n $count++;\n $attributes = array();\n $href = $url[$i];\n $href = strtolower($href);\n strip_tags($href);\n $href = preg_replace(\"/[^a-z0-9_\\s-]/\", \"\", $href);\n $href = preg_replace(\"/[\\s-]+/\", \" \", $href);\n $href = preg_replace(\"/[\\s_]/\", \"-\", $href);\n\n\n $newId = 'id=\"' . $href . '\"';\n $newhtag = $newId . '>';\n $htagr = str_replace('>' . $titles[$i], \"\\t\" . $newhtag . $titles[$i], $htag);\n $searches[] = $htag;\n $replaces[] = $htagr;\n\n\n if ((int)$levels[$i] === (int)$_level):\n $chapters[$_level-1] = ((int)$chapters[$_level-1]+1);\n $chapter = implode('.', array_slice($chapters, 1, ($levels[$i]-1) ) );\n $toc .= '<li><span>' . strval($chapter) . '</span> <a href=\"#' . $href . '\">' . $titles[$i] . '</a></li>';\n endif;\n\n if ($levels[$i] > $_level) {\n $_steps = ((int) $levels[$i] - (int) $_level);\n\n for ($j = 0; $j < $_steps; $j++):\n $toc .= '<ol class=\"continue\">';\n $chapters[$levels[$i]-1+$j] = (int)$chapters[$levels[$i]-1+$j]+1;\n $_level++;\n endfor;\n $chapter = implode('.', array_slice($chapters, 1, ($levels[$i]-1) ) );\n $toc .= '<li><a href=\"#' . $href . '\">' . $titles[$i] . '</a></li>';\n }\n\n if ($levels[$i] < $_level) {\n\n $_steps = ((int) $_level - (int) $levels[$i]);\n $chapters[$levels[$i]-1] = (int)$chapters[$levels[$i]-1]+1;\n $_olevel = $_level;\n for ($j = 0; $j < $_steps; $j++):\n $chapters[$levels[$i]+$j] = 0;\n $toc .= '</ol>';\n $_level--;\n endfor;\n\n $chapters[$_olevel-1] = 0;\n $chapter = implode('.', array_slice($chapters, 1, ($levels[$i]-1) ) );\n\n $toc .= '<li><a href=\"#' . $href . '\">' . $titles[$i] . '</a></li>';\n\n }\n }\n $toc .= '</ul>';\n $toc .= '</div></div><div class=\"clear\"></div>';\n $content = str_replace($searches, $replaces, $content);\n $content = $toc . $content;\n endif;\n\n return $content;\n }\n\n /**\n * Appends the table of content to the $content\n * AKA. Executes our filter\n * \n * @param type $content\n * @return type\n */\n static function writeToc($content) {\n\n // Put original $content into a var you can pick up later\n self::$pre_toc_content = $content;\n\n // Or alternatively, use a global\n global $global_pre_toc_content;\n $global_pre_toc_content = $content;\n\n $content = TableOfContents::generateTableOfContents(4, $content, TRUE);\n return $content;\n }\n\n}\n\nadd_filter('the_content', array('TableOfContents', 'writeTOC'), 100);\n\n// The Above Line Adds the Table Of Content Before The Post Content\n// Problem is that in the first function of code, i want it to exclude this filter. I don't want the Table Of Content text to become my Meta Description\n\n\n?>\n</code></pre>\n"
},
{
"answer_id": 354395,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 3,
"selected": true,
"text": "<p>You can temporarily detach the function from the hook.</p>\n\n<pre><code> // THIS IS MY PROBLEM LINE, i USE Apply Filters for post content....\n\n $priority = has_filter('the_content', ['TableOfContents', 'writeTOC'] );\n if ( $priority !== false )\n remove_filter('the_content', ['TableOfContents', 'writeTOC'], $priority );\n\n $meta = apply_filters('the_content', $post->post_content);\n\n if ( $priority !== false )\n add_filter('the_content', ['TableOfContents', 'writeTOC'], $priority );\n\n\n $meta = strip_tags($meta);\n $meta = strip_shortcodes($meta );\n</code></pre>\n\n<p><strong>Codex:</strong> </p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/has_filter\" rel=\"nofollow noreferrer\">has_filter()</a> </li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/remove_filter/\" rel=\"nofollow noreferrer\">remove_filter()</a> </li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/add_filter/\" rel=\"nofollow noreferrer\">add_filter()</a> </li>\n</ul>\n"
}
] | 2019/12/11 | [
"https://wordpress.stackexchange.com/questions/354357",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128094/"
] | In my plugin, I have a custom post type with a specific behaviour.
The administrator after to publish it, he should not be able to set the post as draft again.
How can I do this ? | You can temporarily detach the function from the hook.
```
// THIS IS MY PROBLEM LINE, i USE Apply Filters for post content....
$priority = has_filter('the_content', ['TableOfContents', 'writeTOC'] );
if ( $priority !== false )
remove_filter('the_content', ['TableOfContents', 'writeTOC'], $priority );
$meta = apply_filters('the_content', $post->post_content);
if ( $priority !== false )
add_filter('the_content', ['TableOfContents', 'writeTOC'], $priority );
$meta = strip_tags($meta);
$meta = strip_shortcodes($meta );
```
**Codex:**
* [has\_filter()](https://codex.wordpress.org/Function_Reference/has_filter)
* [remove\_filter()](https://developer.wordpress.org/reference/functions/remove_filter/)
* [add\_filter()](https://developer.wordpress.org/reference/functions/add_filter/) |
354,370 | <p>I'm using the following function to add a custom field called "price_1_50" to each product variation:</p>
<pre><code>add_action( 'woocommerce_variation_options_pricing', 'bbloomer_add_custom_field_to_variations', 10, 3 );
function bbloomer_add_custom_field_to_variations( $loop, $variation_data, $variation ) {
woocommerce_wp_text_input( array(
'id' => 'price_1_50[' . $loop . ']',
'class' => 'short',
'label' => __( 'Price 1-50:', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, 'price_1_50', true )
));
}
add_action( 'woocommerce_save_product_variation', 'bbloomer_save_custom_field_variations', 10, 2 );
function bbloomer_save_custom_field_variations( $variation_id, $i ) {
$price_1_50 = $_POST['price_1_50'][$i];
if ( isset( $price_1_50 ) ) update_post_meta( $variation_id, 'price_1_50', esc_attr( $price_1_50 ) );
}
add_filter( 'woocommerce_available_variation', 'bbloomer_add_custom_field_variation_data' );
function bbloomer_add_custom_field_variation_data( $variations ) {
$variations['price_1_50'] = '<div class="woocommerce_custom_field">Price 1-50:
<span>'get_post_meta( $variations[ 'variation_id' ], 'price_1_50', true ) . '</span></div>';
return $variations;
}
</code></pre>
<p>In functions.php i've wrote a function which replaces the product price with the custom field "price_1_50" but i think i can't get the variation ID to display the custom field in the frontend.</p>
<p>I've tried</p>
<pre><code>var price = <?php echo get_post_meta( $variation_id, 'price_1_50', true ); ?>;
</code></pre>
<pre><code>var price = <?php echo get_post_meta( get_the_ID(), 'price_1_50', true ); ?>;
</code></pre>
<pre><code>$arrvariations = $variation->get_children (); $price_1_50 = get_post_meta( $arrvariations, 'price_1_50', true ); echo $price_1_50;
</code></pre>
<p>The only way to get a result in the frontend in single product page is if i write the variation ID.</p>
<pre><code>var price = <?php echo get_post_meta( 10652, 'price_1_50', true ); ?>;
</code></pre>
| [
{
"answer_id": 354377,
"author": "TomC",
"author_id": 36980,
"author_profile": "https://wordpress.stackexchange.com/users/36980",
"pm_score": 0,
"selected": false,
"text": "<p>Try using the following:</p>\n\n<pre><code>$post = $wp_query->post;\nglobal $post; \n</code></pre>\n\n<p>Then use:</p>\n\n<pre><code>$price = get_post_meta($post->ID,'price_1_50',true);\necho $price;\n</code></pre>\n"
},
{
"answer_id": 354449,
"author": "Billy",
"author_id": 107745,
"author_profile": "https://wordpress.stackexchange.com/users/107745",
"pm_score": 3,
"selected": true,
"text": "<p>Ok, I've managed to solve this. This is how i finally created variations custom field:</p>\n\n<pre><code>add_action( 'woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3 );\n\nadd_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );\n\nfunction variation_settings_fields( $loop, $variation_data, $variation ) {\n woocommerce_wp_text_input( \n array( \n 'id' => 'price_1_50[' . $variation->ID . ']',\n 'class' => 'price_1_50',\n 'type' => 'text', \n 'label' => __( 'Price | Product amount: 1-49', 'woocommerce' ), \n 'placeholder' => '',\n 'desc_tip' => 'true',\n 'description' => __( 'Enter price for product amount 1-49 (if available)', 'woocommerce' ),\n 'value' => get_post_meta( $variation->ID, 'price_1_50', true )\n )\n );\n}\n\nfunction save_variation_settings_fields( $post_id ) {\n $text_field = $_POST['_price_1_50'][ $post_id ];\n if( ! empty( $text_field ) ) {\n update_post_meta( $post_id, 'price_1_50', esc_attr( $text_field ) );\n }\n}\n</code></pre>\n\n<p>And this is how i got the desired result in frontend (based on: <a href=\"https://stackoverflow.com/questions/47646939/how-to-get-woocommerce-variation-id\">https://stackoverflow.com/questions/47646939/how-to-get-woocommerce-variation-id</a>)</p>\n\n<pre><code>$args = array(\n 'post_type' => 'product_variation',\n 'post_status' => array( 'private', 'publish' ),\n 'numberposts' => -1,\n 'orderby' => 'menu_order',\n 'order' => 'asc',\n 'post_parent' => get_the_ID() // get parent post-ID\n);\n$variations = get_posts( $args );\n\nforeach ( $variations as $variation ) {\n\n $variation_ID = $variation->ID;\n\n $product_variation = new WC_Product_Variation( $variation_ID );\n\n get_post_meta( $variation_ID , 'price_1_50', true );\n\n}\n</code></pre>\n"
}
] | 2019/12/11 | [
"https://wordpress.stackexchange.com/questions/354370",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107745/"
] | I'm using the following function to add a custom field called "price\_1\_50" to each product variation:
```
add_action( 'woocommerce_variation_options_pricing', 'bbloomer_add_custom_field_to_variations', 10, 3 );
function bbloomer_add_custom_field_to_variations( $loop, $variation_data, $variation ) {
woocommerce_wp_text_input( array(
'id' => 'price_1_50[' . $loop . ']',
'class' => 'short',
'label' => __( 'Price 1-50:', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, 'price_1_50', true )
));
}
add_action( 'woocommerce_save_product_variation', 'bbloomer_save_custom_field_variations', 10, 2 );
function bbloomer_save_custom_field_variations( $variation_id, $i ) {
$price_1_50 = $_POST['price_1_50'][$i];
if ( isset( $price_1_50 ) ) update_post_meta( $variation_id, 'price_1_50', esc_attr( $price_1_50 ) );
}
add_filter( 'woocommerce_available_variation', 'bbloomer_add_custom_field_variation_data' );
function bbloomer_add_custom_field_variation_data( $variations ) {
$variations['price_1_50'] = '<div class="woocommerce_custom_field">Price 1-50:
<span>'get_post_meta( $variations[ 'variation_id' ], 'price_1_50', true ) . '</span></div>';
return $variations;
}
```
In functions.php i've wrote a function which replaces the product price with the custom field "price\_1\_50" but i think i can't get the variation ID to display the custom field in the frontend.
I've tried
```
var price = <?php echo get_post_meta( $variation_id, 'price_1_50', true ); ?>;
```
```
var price = <?php echo get_post_meta( get_the_ID(), 'price_1_50', true ); ?>;
```
```
$arrvariations = $variation->get_children (); $price_1_50 = get_post_meta( $arrvariations, 'price_1_50', true ); echo $price_1_50;
```
The only way to get a result in the frontend in single product page is if i write the variation ID.
```
var price = <?php echo get_post_meta( 10652, 'price_1_50', true ); ?>;
``` | Ok, I've managed to solve this. This is how i finally created variations custom field:
```
add_action( 'woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3 );
add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );
function variation_settings_fields( $loop, $variation_data, $variation ) {
woocommerce_wp_text_input(
array(
'id' => 'price_1_50[' . $variation->ID . ']',
'class' => 'price_1_50',
'type' => 'text',
'label' => __( 'Price | Product amount: 1-49', 'woocommerce' ),
'placeholder' => '',
'desc_tip' => 'true',
'description' => __( 'Enter price for product amount 1-49 (if available)', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, 'price_1_50', true )
)
);
}
function save_variation_settings_fields( $post_id ) {
$text_field = $_POST['_price_1_50'][ $post_id ];
if( ! empty( $text_field ) ) {
update_post_meta( $post_id, 'price_1_50', esc_attr( $text_field ) );
}
}
```
And this is how i got the desired result in frontend (based on: <https://stackoverflow.com/questions/47646939/how-to-get-woocommerce-variation-id>)
```
$args = array(
'post_type' => 'product_variation',
'post_status' => array( 'private', 'publish' ),
'numberposts' => -1,
'orderby' => 'menu_order',
'order' => 'asc',
'post_parent' => get_the_ID() // get parent post-ID
);
$variations = get_posts( $args );
foreach ( $variations as $variation ) {
$variation_ID = $variation->ID;
$product_variation = new WC_Product_Variation( $variation_ID );
get_post_meta( $variation_ID , 'price_1_50', true );
}
``` |
354,378 | <p>I'm building a theme in _S and using native Gutenberg blocks.</p>
<p>I have the following code via my functions.php file to set my image sizes:</p>
<pre><code>add_theme_support( 'post-thumbnails' );
add_image_size( 'carousel', 1366, 550, true );
add_image_size( 'hero', 1366, 400, true );
add_image_size( 'large-square', 392, 340, true );
add_image_size( 'medium-square', 279, 314, true );
add_image_size( 'small-square', 215, 170, true );
add_image_size( 'diagram', 650 );
add_image_size( 'full-width', 884 );
add_image_size( 'half', 430 );
add_image_size( 'third', 279 );
add_image_size( 'quarter', 203 );
</code></pre>
<p>I also have this code to remove the default image sizes:</p>
<pre><code>function remove_default_image_sizes( $sizes) {
unset( $sizes['thumbnail']);
unset( $sizes['medium']);
unset( $sizes['medium_large']);
return $sizes;
}
add_filter('intermediate_image_sizes_advanced', 'remove_default_image_sizes');
</code></pre>
<p>When adding new images or regenerating my thumbnails via WP CLI, there are a number of generated image sizes that appear and do not recognise:</p>
<pre><code>image-scaled-2048x600.jpg
image-scaled-1536x450.jpg
image-scaled-1024x300.jpg
</code></pre>
<p>I initially thought it could be down to the <a href="https://make.wordpress.org/core/2019/10/09/introducing-handling-of-big-images-in-wordpress-5-3/" rel="noreferrer">recent WordPress 5.3 update</a> that introduced a new way to manage large images.</p>
<p>I tried adding this to functions.php:</p>
<pre><code>add_filter( 'big_image_size_threshold', '__return_false' );
</code></pre>
<p>But I still get larger images that are scaled, like so:</p>
<pre><code>image-scaled-2048x600.jpg
</code></pre>
<p>Where could WordPress be getting these image sizes from? I'm running a single plugin for the build (<a href="https://www.advancedcustomfields.com/" rel="noreferrer">ACF</a>).</p>
| [
{
"answer_id": 354379,
"author": "Sam",
"author_id": 37548,
"author_profile": "https://wordpress.stackexchange.com/users/37548",
"pm_score": 5,
"selected": true,
"text": "<p>I found the culprit! </p>\n\n<p>WordPress 5.3 introduced additional image sizes which can be found via <code>/wp-includes/media.php</code>.</p>\n\n<p>Updating my function, like so, removed the extra sizes:</p>\n\n<pre><code>function remove_default_image_sizes( $sizes) {\n unset( $sizes['large']); // Added to remove 1024\n unset( $sizes['thumbnail']);\n unset( $sizes['medium']);\n unset( $sizes['medium_large']);\n unset( $sizes['1536x1536']);\n unset( $sizes['2048x2048']);\n return $sizes;\n}\nadd_filter('intermediate_image_sizes_advanced', 'remove_default_image_sizes');\n</code></pre>\n"
},
{
"answer_id": 381247,
"author": "zighead",
"author_id": 200134,
"author_profile": "https://wordpress.stackexchange.com/users/200134",
"pm_score": 3,
"selected": false,
"text": "<p>You could also remove those image sizes completely using <code>remove_image_size</code> (see: <a href=\"https://developer.wordpress.org/reference/functions/remove_image_size/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/remove_image_size/</a>)</p>\n<p>Example (to be placed in your functions.php file):</p>\n<pre><code>remove_image_size('1536x1536');\nremove_image_size('2048x2048');\n</code></pre>\n<p>This function, however, won't work for default WP image sizes (e.g. 'thumbnail', 'medium', 'large', etc.). There's a work-around though. Simply set the sizes to 0:</p>\n<pre><code>update_option( 'thumbnail_size_h', 0 );\nupdate_option( 'thumbnail_size_w', 0 );\nupdate_option( 'medium_size_h', 0 );\nupdate_option( 'medium_size_w', 0 );\nupdate_option( 'medium_large_size_w', 0 );\nupdate_option( 'medium_large_size_h', 0 );\nupdate_option( 'large_size_h', 0 );\nupdate_option( 'large_size_w', 0 );\n</code></pre>\n"
},
{
"answer_id": 410208,
"author": "gtamborero",
"author_id": 52236,
"author_profile": "https://wordpress.stackexchange.com/users/52236",
"pm_score": 0,
"selected": false,
"text": "<p>This is an update that works with Wordpress 6.x</p>\n<p>2 functions:</p>\n<pre><code>// Remove certain image sizes or...\nfunction remove_some_image_sizes() {\n foreach ( get_intermediate_image_sizes() as $size ) {\n if ( in_array( $size, array( '1536x1536','2048x2048' ) ) ) {\n // Will remove '1536x1536','2048x2048'\n remove_image_size( $size );\n }\n }\n}\nadd_action('init', 'remove_some_image_sizes');\n\n// Remove all but not default\nfunction remove_extra_image_sizes() {\n foreach ( get_intermediate_image_sizes() as $size ) {\n if ( !in_array( $size, array( 'thumbnail', 'medium', 'medium_large', 'large' ) ) ) {\n // Will remove all except 'thumbnail', 'medium', 'medium_large', 'large'\n remove_image_size( $size );\n }\n }\n}\nadd_action('init', 'remove_extra_image_sizes');\n</code></pre>\n"
}
] | 2019/12/11 | [
"https://wordpress.stackexchange.com/questions/354378",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37548/"
] | I'm building a theme in \_S and using native Gutenberg blocks.
I have the following code via my functions.php file to set my image sizes:
```
add_theme_support( 'post-thumbnails' );
add_image_size( 'carousel', 1366, 550, true );
add_image_size( 'hero', 1366, 400, true );
add_image_size( 'large-square', 392, 340, true );
add_image_size( 'medium-square', 279, 314, true );
add_image_size( 'small-square', 215, 170, true );
add_image_size( 'diagram', 650 );
add_image_size( 'full-width', 884 );
add_image_size( 'half', 430 );
add_image_size( 'third', 279 );
add_image_size( 'quarter', 203 );
```
I also have this code to remove the default image sizes:
```
function remove_default_image_sizes( $sizes) {
unset( $sizes['thumbnail']);
unset( $sizes['medium']);
unset( $sizes['medium_large']);
return $sizes;
}
add_filter('intermediate_image_sizes_advanced', 'remove_default_image_sizes');
```
When adding new images or regenerating my thumbnails via WP CLI, there are a number of generated image sizes that appear and do not recognise:
```
image-scaled-2048x600.jpg
image-scaled-1536x450.jpg
image-scaled-1024x300.jpg
```
I initially thought it could be down to the [recent WordPress 5.3 update](https://make.wordpress.org/core/2019/10/09/introducing-handling-of-big-images-in-wordpress-5-3/) that introduced a new way to manage large images.
I tried adding this to functions.php:
```
add_filter( 'big_image_size_threshold', '__return_false' );
```
But I still get larger images that are scaled, like so:
```
image-scaled-2048x600.jpg
```
Where could WordPress be getting these image sizes from? I'm running a single plugin for the build ([ACF](https://www.advancedcustomfields.com/)). | I found the culprit!
WordPress 5.3 introduced additional image sizes which can be found via `/wp-includes/media.php`.
Updating my function, like so, removed the extra sizes:
```
function remove_default_image_sizes( $sizes) {
unset( $sizes['large']); // Added to remove 1024
unset( $sizes['thumbnail']);
unset( $sizes['medium']);
unset( $sizes['medium_large']);
unset( $sizes['1536x1536']);
unset( $sizes['2048x2048']);
return $sizes;
}
add_filter('intermediate_image_sizes_advanced', 'remove_default_image_sizes');
``` |
354,396 | <p>I need to get some random posts and order them by date.</p>
<p>To get random posts I used the following:</p>
<pre><code>$query = new WP_Query(
[
'post__in' => $post_id_array,
'posts_per_page' => $number,
'orderby' => 'rand'
]
);
</code></pre>
<p>To order by date I tried this:</p>
<pre><code>'orderby' => ['rand' => 'ASC', 'date' => 'DESC']
</code></pre>
<p>But it does not work correctly. How can I do this?</p>
| [
{
"answer_id": 354379,
"author": "Sam",
"author_id": 37548,
"author_profile": "https://wordpress.stackexchange.com/users/37548",
"pm_score": 5,
"selected": true,
"text": "<p>I found the culprit! </p>\n\n<p>WordPress 5.3 introduced additional image sizes which can be found via <code>/wp-includes/media.php</code>.</p>\n\n<p>Updating my function, like so, removed the extra sizes:</p>\n\n<pre><code>function remove_default_image_sizes( $sizes) {\n unset( $sizes['large']); // Added to remove 1024\n unset( $sizes['thumbnail']);\n unset( $sizes['medium']);\n unset( $sizes['medium_large']);\n unset( $sizes['1536x1536']);\n unset( $sizes['2048x2048']);\n return $sizes;\n}\nadd_filter('intermediate_image_sizes_advanced', 'remove_default_image_sizes');\n</code></pre>\n"
},
{
"answer_id": 381247,
"author": "zighead",
"author_id": 200134,
"author_profile": "https://wordpress.stackexchange.com/users/200134",
"pm_score": 3,
"selected": false,
"text": "<p>You could also remove those image sizes completely using <code>remove_image_size</code> (see: <a href=\"https://developer.wordpress.org/reference/functions/remove_image_size/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/remove_image_size/</a>)</p>\n<p>Example (to be placed in your functions.php file):</p>\n<pre><code>remove_image_size('1536x1536');\nremove_image_size('2048x2048');\n</code></pre>\n<p>This function, however, won't work for default WP image sizes (e.g. 'thumbnail', 'medium', 'large', etc.). There's a work-around though. Simply set the sizes to 0:</p>\n<pre><code>update_option( 'thumbnail_size_h', 0 );\nupdate_option( 'thumbnail_size_w', 0 );\nupdate_option( 'medium_size_h', 0 );\nupdate_option( 'medium_size_w', 0 );\nupdate_option( 'medium_large_size_w', 0 );\nupdate_option( 'medium_large_size_h', 0 );\nupdate_option( 'large_size_h', 0 );\nupdate_option( 'large_size_w', 0 );\n</code></pre>\n"
},
{
"answer_id": 410208,
"author": "gtamborero",
"author_id": 52236,
"author_profile": "https://wordpress.stackexchange.com/users/52236",
"pm_score": 0,
"selected": false,
"text": "<p>This is an update that works with Wordpress 6.x</p>\n<p>2 functions:</p>\n<pre><code>// Remove certain image sizes or...\nfunction remove_some_image_sizes() {\n foreach ( get_intermediate_image_sizes() as $size ) {\n if ( in_array( $size, array( '1536x1536','2048x2048' ) ) ) {\n // Will remove '1536x1536','2048x2048'\n remove_image_size( $size );\n }\n }\n}\nadd_action('init', 'remove_some_image_sizes');\n\n// Remove all but not default\nfunction remove_extra_image_sizes() {\n foreach ( get_intermediate_image_sizes() as $size ) {\n if ( !in_array( $size, array( 'thumbnail', 'medium', 'medium_large', 'large' ) ) ) {\n // Will remove all except 'thumbnail', 'medium', 'medium_large', 'large'\n remove_image_size( $size );\n }\n }\n}\nadd_action('init', 'remove_extra_image_sizes');\n</code></pre>\n"
}
] | 2019/12/11 | [
"https://wordpress.stackexchange.com/questions/354396",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/179639/"
] | I need to get some random posts and order them by date.
To get random posts I used the following:
```
$query = new WP_Query(
[
'post__in' => $post_id_array,
'posts_per_page' => $number,
'orderby' => 'rand'
]
);
```
To order by date I tried this:
```
'orderby' => ['rand' => 'ASC', 'date' => 'DESC']
```
But it does not work correctly. How can I do this? | I found the culprit!
WordPress 5.3 introduced additional image sizes which can be found via `/wp-includes/media.php`.
Updating my function, like so, removed the extra sizes:
```
function remove_default_image_sizes( $sizes) {
unset( $sizes['large']); // Added to remove 1024
unset( $sizes['thumbnail']);
unset( $sizes['medium']);
unset( $sizes['medium_large']);
unset( $sizes['1536x1536']);
unset( $sizes['2048x2048']);
return $sizes;
}
add_filter('intermediate_image_sizes_advanced', 'remove_default_image_sizes');
``` |
354,410 | <p>I have a class setup to run some database scripts on my mu-plugin.</p>
<pre><code>function activate_mjmc_core() {
require_once plugin_dir_path( __FILE__ ) . 'includes/class-mjmc-core-activator.php';
Mjmc_Core_Activator::activate();
Mjmc_Core_Activator::mjmc_database_version();
Mjmc_Core_Activator::mjmc_companies_table();
Mjmc_Core_Activator::mjmc_locations_table();
Mjmc_Core_Activator::mjmc_companies_insert();
}
register_activation_hook( __FILE__, 'activate_mjmc_core' );
</code></pre>
<p>Now these work just fine when i use this as a normal plugin where i have to activate it. </p>
<p>But when i use this in my mu-plugins, all the other plugin functions work, it just doenst run the database functions listed above on activate. Is there something else i need to do on these database functions? or run this on another wordpress hook?</p>
<p>thanks</p>
| [
{
"answer_id": 354411,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>MU plugins don't 'activate', or 'deactivate'. They're just present or not present. So you'll need a different approach. One option would be to just perform your activation functions on <code>init</code>, and store a record in the database to say whether or not it's already been done:</p>\n\n<pre><code>function activate_mjmc_core() {\n if ( '1' === get_option( 'mjmc_activated' ) ) {\n return;\n }\n\n require_once plugin_dir_path( __FILE__ ) . 'includes/class-mjmc-core-activator.php';\n\n Mjmc_Core_Activator::activate();\n Mjmc_Core_Activator::mjmc_database_version();\n Mjmc_Core_Activator::mjmc_companies_table();\n Mjmc_Core_Activator::mjmc_locations_table();\n Mjmc_Core_Activator::mjmc_companies_insert();\n\n update_option( 'mjmc_activated', '1' );\n}\nadd_action( 'init', 'activate_mjmc_core' );\n</code></pre>\n"
},
{
"answer_id": 354437,
"author": "Hasan Uj Jaman",
"author_id": 179656,
"author_profile": "https://wordpress.stackexchange.com/users/179656",
"pm_score": -1,
"selected": false,
"text": "<p>You need to switch to siite for run this activation hook.</p>\n\n<pre><code>function activate_mjmc_core() {\n$current_site_id = get_current_blog_id();\nswitch_to_blog($current_site_id);\nrequire_once plugin_dir_path( __FILE__ ) . 'includes/class-mjmc-core- \nactivator.php';\nMjmc_Core_Activator::activate();\nMjmc_Core_Activator::mjmc_database_version();\nMjmc_Core_Activator::mjmc_companies_table();\nMjmc_Core_Activator::mjmc_locations_table();\nMjmc_Core_Activator::mjmc_companies_insert();\nrestore_current_blog();\n}\n</code></pre>\n\n<p>Hope this work. :D</p>\n\n<p>register_activation_hook( <strong>FILE</strong>, 'activate_mjmc_core' );</p>\n"
}
] | 2019/12/12 | [
"https://wordpress.stackexchange.com/questions/354410",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/179644/"
] | I have a class setup to run some database scripts on my mu-plugin.
```
function activate_mjmc_core() {
require_once plugin_dir_path( __FILE__ ) . 'includes/class-mjmc-core-activator.php';
Mjmc_Core_Activator::activate();
Mjmc_Core_Activator::mjmc_database_version();
Mjmc_Core_Activator::mjmc_companies_table();
Mjmc_Core_Activator::mjmc_locations_table();
Mjmc_Core_Activator::mjmc_companies_insert();
}
register_activation_hook( __FILE__, 'activate_mjmc_core' );
```
Now these work just fine when i use this as a normal plugin where i have to activate it.
But when i use this in my mu-plugins, all the other plugin functions work, it just doenst run the database functions listed above on activate. Is there something else i need to do on these database functions? or run this on another wordpress hook?
thanks | MU plugins don't 'activate', or 'deactivate'. They're just present or not present. So you'll need a different approach. One option would be to just perform your activation functions on `init`, and store a record in the database to say whether or not it's already been done:
```
function activate_mjmc_core() {
if ( '1' === get_option( 'mjmc_activated' ) ) {
return;
}
require_once plugin_dir_path( __FILE__ ) . 'includes/class-mjmc-core-activator.php';
Mjmc_Core_Activator::activate();
Mjmc_Core_Activator::mjmc_database_version();
Mjmc_Core_Activator::mjmc_companies_table();
Mjmc_Core_Activator::mjmc_locations_table();
Mjmc_Core_Activator::mjmc_companies_insert();
update_option( 'mjmc_activated', '1' );
}
add_action( 'init', 'activate_mjmc_core' );
``` |
354,415 | <p>I currently have a front end part of a WP site that allows admins to create new users and assign then user roles from a drop down - that works perfectly.</p>
<p>However, I am using a plugin to also authenticate users against an AD/LDAP so I can use it on a corporate level too.</p>
<p>The problem is when the user authenticates against the LDAP for the first time, there is no user assignment and no where in the plugin that I can see on how to do that (using the <a href="https://active-directory-wp.com/docs/Getting_Started.html" rel="nofollow noreferrer">NextAD plugin</a>).</p>
<p>I however saw that I can do custom checks on the authorisation when logging in, and thought I could add the role there:</p>
<pre class="lang-php prettyprint-override"><code>function mb_authenticate_user( $user ) {
// get the user id from log in name
$mb_user_id = get_user_by('login', $_REQUEST['log'] );
$mb_user_id = $mb_user_id->ID;
// empty role on login
if( empty( mb_current_user_role() ) ) {
wp_update_user( array( 'ID' => $mb_user_id, 'role' => 'mbToBeAssigned' ) );
}
// other custom code checks here too
}
add_filter( 'wp_authenticate_user', 'mb_authenticate_user', 1 );
add_filter( 'authorize', 'mb_authenticate_user' ); // plugin authentication NextAD
</code></pre>
<p>However, in my <code>mb_current_user_role()</code> function,</p>
<pre class="lang-php prettyprint-override"><code>function mb_current_user_role( $echo = false ) {
$user = '';
$user = ( is_user_logged_in() ? array_values( wp_get_current_user()->roles ) : null );
$user = $user[0];
if( $echo ) {
echo $user;
} else {
return $user;
}
}
</code></pre>
<p>it is not correctly checking if the user has exisiting roles and is constantly overriding them with the authentication one: <code>mbToBeAssigned</code></p>
<p>Is there something I'm missing? Or is there a better way to do this? Running on a multisite too.</p>
| [
{
"answer_id": 354411,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>MU plugins don't 'activate', or 'deactivate'. They're just present or not present. So you'll need a different approach. One option would be to just perform your activation functions on <code>init</code>, and store a record in the database to say whether or not it's already been done:</p>\n\n<pre><code>function activate_mjmc_core() {\n if ( '1' === get_option( 'mjmc_activated' ) ) {\n return;\n }\n\n require_once plugin_dir_path( __FILE__ ) . 'includes/class-mjmc-core-activator.php';\n\n Mjmc_Core_Activator::activate();\n Mjmc_Core_Activator::mjmc_database_version();\n Mjmc_Core_Activator::mjmc_companies_table();\n Mjmc_Core_Activator::mjmc_locations_table();\n Mjmc_Core_Activator::mjmc_companies_insert();\n\n update_option( 'mjmc_activated', '1' );\n}\nadd_action( 'init', 'activate_mjmc_core' );\n</code></pre>\n"
},
{
"answer_id": 354437,
"author": "Hasan Uj Jaman",
"author_id": 179656,
"author_profile": "https://wordpress.stackexchange.com/users/179656",
"pm_score": -1,
"selected": false,
"text": "<p>You need to switch to siite for run this activation hook.</p>\n\n<pre><code>function activate_mjmc_core() {\n$current_site_id = get_current_blog_id();\nswitch_to_blog($current_site_id);\nrequire_once plugin_dir_path( __FILE__ ) . 'includes/class-mjmc-core- \nactivator.php';\nMjmc_Core_Activator::activate();\nMjmc_Core_Activator::mjmc_database_version();\nMjmc_Core_Activator::mjmc_companies_table();\nMjmc_Core_Activator::mjmc_locations_table();\nMjmc_Core_Activator::mjmc_companies_insert();\nrestore_current_blog();\n}\n</code></pre>\n\n<p>Hope this work. :D</p>\n\n<p>register_activation_hook( <strong>FILE</strong>, 'activate_mjmc_core' );</p>\n"
}
] | 2019/12/12 | [
"https://wordpress.stackexchange.com/questions/354415",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17411/"
] | I currently have a front end part of a WP site that allows admins to create new users and assign then user roles from a drop down - that works perfectly.
However, I am using a plugin to also authenticate users against an AD/LDAP so I can use it on a corporate level too.
The problem is when the user authenticates against the LDAP for the first time, there is no user assignment and no where in the plugin that I can see on how to do that (using the [NextAD plugin](https://active-directory-wp.com/docs/Getting_Started.html)).
I however saw that I can do custom checks on the authorisation when logging in, and thought I could add the role there:
```php
function mb_authenticate_user( $user ) {
// get the user id from log in name
$mb_user_id = get_user_by('login', $_REQUEST['log'] );
$mb_user_id = $mb_user_id->ID;
// empty role on login
if( empty( mb_current_user_role() ) ) {
wp_update_user( array( 'ID' => $mb_user_id, 'role' => 'mbToBeAssigned' ) );
}
// other custom code checks here too
}
add_filter( 'wp_authenticate_user', 'mb_authenticate_user', 1 );
add_filter( 'authorize', 'mb_authenticate_user' ); // plugin authentication NextAD
```
However, in my `mb_current_user_role()` function,
```php
function mb_current_user_role( $echo = false ) {
$user = '';
$user = ( is_user_logged_in() ? array_values( wp_get_current_user()->roles ) : null );
$user = $user[0];
if( $echo ) {
echo $user;
} else {
return $user;
}
}
```
it is not correctly checking if the user has exisiting roles and is constantly overriding them with the authentication one: `mbToBeAssigned`
Is there something I'm missing? Or is there a better way to do this? Running on a multisite too. | MU plugins don't 'activate', or 'deactivate'. They're just present or not present. So you'll need a different approach. One option would be to just perform your activation functions on `init`, and store a record in the database to say whether or not it's already been done:
```
function activate_mjmc_core() {
if ( '1' === get_option( 'mjmc_activated' ) ) {
return;
}
require_once plugin_dir_path( __FILE__ ) . 'includes/class-mjmc-core-activator.php';
Mjmc_Core_Activator::activate();
Mjmc_Core_Activator::mjmc_database_version();
Mjmc_Core_Activator::mjmc_companies_table();
Mjmc_Core_Activator::mjmc_locations_table();
Mjmc_Core_Activator::mjmc_companies_insert();
update_option( 'mjmc_activated', '1' );
}
add_action( 'init', 'activate_mjmc_core' );
``` |
354,418 | <p>I am working on search. I am trying to search the product by tag or category. I tried below code but it's not working. I am getting </p>
<blockquote>
<p>Nothing Found</p>
</blockquote>
<p>Also title and content is also not working.</p>
<p>Would you help me out in this?</p>
<pre><code><?php
/**
* The template for displaying search results pages
*
* @link https://developer.wordpress.org/themes/basics/template-hierarchy/#search-result
*
* @package CoolPickings
*/
get_header();
?>
<section id="primary" class="content-area mainSearch">
<main id="main" class="site-main">
<div class="equalPadding">
<div class="cp-seeWrapper">
<?php
$getSearch=get_search_query();
$args = array(
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'product_tag',
'field' => 'slug',
'terms' => $getSearch
),
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $getSearch
)
),
'post_type' => 'product'
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ):
get_search_form();//search form
?>
<div class="resultCount">
<?php global $wp_query;echo $wp_query->found_posts.' RESULTS';?>
</div>
<div class="row">
<?php
while ( $the_query->have_posts() ) {
$the_query->the_post();?>
<div class="col-xl-4 col-lg-4 col-md-4 col-sm-12 col-xs-12 ">
<div class="cp-shadow cp-seeSinglePostWrapper">
<?php the_post_thumbnail();?>
<div class="bg-white single-post-box">
<div class="d-flex cp-CategoryList">
<div class="seeDate"><?php echo get_the_date('F j, Y'); ?></div>
<div class="cp_cat_list">
<?php $cat = get_the_category();
?>
<a href="<?php echo esc_url( get_category_link( $cat[0]->term_id ) );?>"><?php echo $cat[0]->cat_name?></a>
</div>
</div>
<div class="cp-b-content"><h2><a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( the_title_attribute( 'echo=0' ) ); ?>"><?php echo wp_trim_words(get_the_title(), 12, '...'); ?></a></h2></div>
<p><?php echo wp_trim_words(get_the_excerpt(), 25, '...'); ?></p>
</div>
</div>
</div>
<?php }?>
<?php
else :
get_template_part( 'template-parts/content', 'none' );
endif;
?>
</div>
</div>
</div>
</main><!-- #main -->
</section><!-- #primary -->
<?php
get_sidebar();
get_footer();
</code></pre>
| [
{
"answer_id": 354411,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>MU plugins don't 'activate', or 'deactivate'. They're just present or not present. So you'll need a different approach. One option would be to just perform your activation functions on <code>init</code>, and store a record in the database to say whether or not it's already been done:</p>\n\n<pre><code>function activate_mjmc_core() {\n if ( '1' === get_option( 'mjmc_activated' ) ) {\n return;\n }\n\n require_once plugin_dir_path( __FILE__ ) . 'includes/class-mjmc-core-activator.php';\n\n Mjmc_Core_Activator::activate();\n Mjmc_Core_Activator::mjmc_database_version();\n Mjmc_Core_Activator::mjmc_companies_table();\n Mjmc_Core_Activator::mjmc_locations_table();\n Mjmc_Core_Activator::mjmc_companies_insert();\n\n update_option( 'mjmc_activated', '1' );\n}\nadd_action( 'init', 'activate_mjmc_core' );\n</code></pre>\n"
},
{
"answer_id": 354437,
"author": "Hasan Uj Jaman",
"author_id": 179656,
"author_profile": "https://wordpress.stackexchange.com/users/179656",
"pm_score": -1,
"selected": false,
"text": "<p>You need to switch to siite for run this activation hook.</p>\n\n<pre><code>function activate_mjmc_core() {\n$current_site_id = get_current_blog_id();\nswitch_to_blog($current_site_id);\nrequire_once plugin_dir_path( __FILE__ ) . 'includes/class-mjmc-core- \nactivator.php';\nMjmc_Core_Activator::activate();\nMjmc_Core_Activator::mjmc_database_version();\nMjmc_Core_Activator::mjmc_companies_table();\nMjmc_Core_Activator::mjmc_locations_table();\nMjmc_Core_Activator::mjmc_companies_insert();\nrestore_current_blog();\n}\n</code></pre>\n\n<p>Hope this work. :D</p>\n\n<p>register_activation_hook( <strong>FILE</strong>, 'activate_mjmc_core' );</p>\n"
}
] | 2019/12/12 | [
"https://wordpress.stackexchange.com/questions/354418",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/177715/"
] | I am working on search. I am trying to search the product by tag or category. I tried below code but it's not working. I am getting
>
> Nothing Found
>
>
>
Also title and content is also not working.
Would you help me out in this?
```
<?php
/**
* The template for displaying search results pages
*
* @link https://developer.wordpress.org/themes/basics/template-hierarchy/#search-result
*
* @package CoolPickings
*/
get_header();
?>
<section id="primary" class="content-area mainSearch">
<main id="main" class="site-main">
<div class="equalPadding">
<div class="cp-seeWrapper">
<?php
$getSearch=get_search_query();
$args = array(
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'product_tag',
'field' => 'slug',
'terms' => $getSearch
),
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $getSearch
)
),
'post_type' => 'product'
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ):
get_search_form();//search form
?>
<div class="resultCount">
<?php global $wp_query;echo $wp_query->found_posts.' RESULTS';?>
</div>
<div class="row">
<?php
while ( $the_query->have_posts() ) {
$the_query->the_post();?>
<div class="col-xl-4 col-lg-4 col-md-4 col-sm-12 col-xs-12 ">
<div class="cp-shadow cp-seeSinglePostWrapper">
<?php the_post_thumbnail();?>
<div class="bg-white single-post-box">
<div class="d-flex cp-CategoryList">
<div class="seeDate"><?php echo get_the_date('F j, Y'); ?></div>
<div class="cp_cat_list">
<?php $cat = get_the_category();
?>
<a href="<?php echo esc_url( get_category_link( $cat[0]->term_id ) );?>"><?php echo $cat[0]->cat_name?></a>
</div>
</div>
<div class="cp-b-content"><h2><a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( the_title_attribute( 'echo=0' ) ); ?>"><?php echo wp_trim_words(get_the_title(), 12, '...'); ?></a></h2></div>
<p><?php echo wp_trim_words(get_the_excerpt(), 25, '...'); ?></p>
</div>
</div>
</div>
<?php }?>
<?php
else :
get_template_part( 'template-parts/content', 'none' );
endif;
?>
</div>
</div>
</div>
</main><!-- #main -->
</section><!-- #primary -->
<?php
get_sidebar();
get_footer();
``` | MU plugins don't 'activate', or 'deactivate'. They're just present or not present. So you'll need a different approach. One option would be to just perform your activation functions on `init`, and store a record in the database to say whether or not it's already been done:
```
function activate_mjmc_core() {
if ( '1' === get_option( 'mjmc_activated' ) ) {
return;
}
require_once plugin_dir_path( __FILE__ ) . 'includes/class-mjmc-core-activator.php';
Mjmc_Core_Activator::activate();
Mjmc_Core_Activator::mjmc_database_version();
Mjmc_Core_Activator::mjmc_companies_table();
Mjmc_Core_Activator::mjmc_locations_table();
Mjmc_Core_Activator::mjmc_companies_insert();
update_option( 'mjmc_activated', '1' );
}
add_action( 'init', 'activate_mjmc_core' );
``` |
354,427 | <p>I'm using WPMU in my project, but I'm facing some problems to get the current post id from all sites. If I run this code, I receive the same post id of current site and not the different post id from all other sites. It's like that <code>switch_to_blog</code> doesn't work. How can I get all ids of current post from all sites?</p>
<pre><code>$sites = get_sites();
/** @var WP_Site $site */
foreach ($sites as $site) {
if ( $site->archived || $site->spam || $site->deleted ) {
continue;
}
switch_to_blog( $site->blog_id );
var_dump( get_the_ID() );
}
restore_current_blog();
die;
</code></pre>
| [
{
"answer_id": 354431,
"author": "Hasan Uj Jaman",
"author_id": 179656,
"author_profile": "https://wordpress.stackexchange.com/users/179656",
"pm_score": 0,
"selected": false,
"text": "<p>use <code>global $post</code>. And use <code>$post->ID</code></p>\n"
},
{
"answer_id": 354434,
"author": "Hasan Uj Jaman",
"author_id": 179656,
"author_profile": "https://wordpress.stackexchange.com/users/179656",
"pm_score": 1,
"selected": false,
"text": "<p>try this</p>\n\n<pre><code>$sites = get_sites();\nglobal $switched;\n\n/** @var WP_Site $site */\nforeach ($sites as $site) {\nif ( $site->archived || $site->spam || $site->deleted ) {\n continue;\n}\n\nswitch_to_blog( $site->blog_id );\n$all_posts = get_posts('category=-3&numberposts=6&orderby=post_name&order=DSC');\n?>\n<ul>\n<?php foreach($all_posts as $post) : setup_postdata($post);?>\n <li>\n <a href=\"<?php echo get_page_link($post->ID); ?>\" title=\"<?php echo \n $post->post_title; ?>\"><?php echo $post->post_title; ?></a>\n </li> \n<?php endforeach ; ?>\n</ul>\n<?php\n}\nrestore_current_blog();\ndie;\n</code></pre>\n"
}
] | 2019/12/12 | [
"https://wordpress.stackexchange.com/questions/354427",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/174178/"
] | I'm using WPMU in my project, but I'm facing some problems to get the current post id from all sites. If I run this code, I receive the same post id of current site and not the different post id from all other sites. It's like that `switch_to_blog` doesn't work. How can I get all ids of current post from all sites?
```
$sites = get_sites();
/** @var WP_Site $site */
foreach ($sites as $site) {
if ( $site->archived || $site->spam || $site->deleted ) {
continue;
}
switch_to_blog( $site->blog_id );
var_dump( get_the_ID() );
}
restore_current_blog();
die;
``` | try this
```
$sites = get_sites();
global $switched;
/** @var WP_Site $site */
foreach ($sites as $site) {
if ( $site->archived || $site->spam || $site->deleted ) {
continue;
}
switch_to_blog( $site->blog_id );
$all_posts = get_posts('category=-3&numberposts=6&orderby=post_name&order=DSC');
?>
<ul>
<?php foreach($all_posts as $post) : setup_postdata($post);?>
<li>
<a href="<?php echo get_page_link($post->ID); ?>" title="<?php echo
$post->post_title; ?>"><?php echo $post->post_title; ?></a>
</li>
<?php endforeach ; ?>
</ul>
<?php
}
restore_current_blog();
die;
``` |
354,433 | <p>I have Two Custom Post Types "Article " & "News" and they both use same categories
like [ audit , income , tax] . I want when i open audit category page then the post showsn like below: <a href="https://i.stack.imgur.com/CUG4T.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CUG4T.png" alt="enter image description here"></a></p>
<p>the code i already tried on archieve.php but isnt working:</p>
<pre><code><?php
$cats = get_the_category();
$args = array(
'post_type' => 'articles',
'post__not_in' => array( get_the_ID() ),
'posts_per_page' => 5,
'cat' => $cats[0]->term_id,
'meta_query' => array(
array(
'key' => 'recommended_article',
'value' => '1',
'compare' => '=='
)
)
);
$query = new WP_Query( $args );
?>
<?php if( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post(); ?>
<!--HTML-->
<?php endwhile; endif; wp_reset_postdata(); ?>
</code></pre>
| [
{
"answer_id": 354435,
"author": "Heba Fareed",
"author_id": 179666,
"author_profile": "https://wordpress.stackexchange.com/users/179666",
"pm_score": 1,
"selected": false,
"text": "<p>First, I would recommend making this change in Category.php file, as archive.php is affecting tags as well as other archives according to <a href=\"https://wphierarchy.com/\" rel=\"nofollow noreferrer\">Wordpress Theme Hierarchy</a> file system.</p>\n\n<p>Try adding the two queries like next:</p>\n\n<pre><code>$cats = get_the_category();\n $cat_id = $cats[0]->term_id;\n\n\n // news\n $args = array(\n 'post_type' => 'news',\n 'posts_per_page' => 5,\n 'cat' => $cat_id,\n);\n$query = new WP_Query($args);\n\nif($query->have_posts() ) : \n while( $query->have_posts() ) :\n $query->the_post();\n endwhile; \nendif; \n\nwp_reset_postdata(); \n\n // articles\n$args = array(\n 'post_type' => 'articles',\n 'posts_per_page' => 5,\n 'cat' => $cat_id,\n);\n$query = new WP_Query($args);\n\nif($query->have_posts() ) : \n while( $query->have_posts() ) :\n $query->the_post();\n endwhile; \nendif; \n\nwp_reset_postdata(); \n</code></pre>\n"
},
{
"answer_id": 354436,
"author": "Chetan Vaghela",
"author_id": 169856,
"author_profile": "https://wordpress.stackexchange.com/users/169856",
"pm_score": 1,
"selected": false,
"text": "<p>Create <code>taxonomy-categories.php</code> or In your <code>archive.php</code> add below code to get post of <code>article</code> and <code>news</code> post type for current category. I assume that your taxonomy for both post type is <code>categories</code>. change <code>categories</code> with your taxonomy and <code>post_type</code> with your post types for news and article from below code.</p>\n\n<pre><code> # Article \n $articleargs = array(\n 'post_type' => 'article',\n 'posts_per_page' => 5,\n 'tax_query' => array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'categories',\n 'field' => 'name',\n 'terms' => get_queried_object()\n )\n ),\n );\n $articlequery = new WP_Query( $articleargs );\n\n if( $articlequery->have_posts() ) : \n echo \"<h2>Articles</h2>\";\n echo \"<ul>\";\n while( $articlequery->have_posts() ) : $articlequery->the_post(); \n echo \"<li>\".get_the_title().\"</li>\";\n endwhile; \n echo \"</ul>\";\n endif; \n wp_reset_postdata(); \n\n # news\n $newsargs = array(\n 'post_type' => 'news',\n 'posts_per_page' => 5,\n 'tax_query' => array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'categories',\n 'field' => 'name',\n 'terms' => get_queried_object()\n )\n ),\n );\n $newsquery = new WP_Query( $newsargs );\n\n if( $newsquery->have_posts() ) : \n echo \"<h2>News</h2>\";\n echo \"<ul>\";\n while( $newsquery->have_posts() ) : $newsquery->the_post(); \n echo \"<li>\".get_the_title().\"</li>\";\n endwhile; \n echo \"</ul>\";\n endif; \n wp_reset_postdata(); \n</code></pre>\n"
},
{
"answer_id": 354442,
"author": "Hakimuddin Saifee",
"author_id": 165598,
"author_profile": "https://wordpress.stackexchange.com/users/165598",
"pm_score": 1,
"selected": true,
"text": "<p>Its Done Thank U so much Everyone Who Answered!</p>\n\n<pre><code><?php\n/*\n * dglib_breadcrumbs_section_template - hook\n *\n * @hooked - dglib_breadcrumbs_section_callback - 10\n *\n * @since 1.0.6\n */\n\ndo_action( 'dglib_breadcrumbs_section_template' );\n?>\n <div id=\"primary\" class=\"content-area\">\n <main id=\"main\" class=\"site-main\" role=\"main\">\n\n\n<header class=\"page-header\">\n <?php\n the_archive_title( '<h1 class=\"page-title\">', '</h1>' );\n the_archive_description( '<div class=\"archive-description\">', '</div>' );\n\n ?>\n </header>\n<div class=\"row\">\n <?php\n\n$category = get_queried_object();\n\n // news\n $args = array(\n 'post_type' => 'news',\n 'posts_per_page' => 5,\n 'cat' => $category->term_id,\n);\n\n$the_query = new WP_Query( $args ); \n?>\n<?php if ( $the_query->have_posts() ) : ?>\n <!-- .page-header -->\n\n<div class=\"col-md-6 col-sm-6\">\n <div class=\"panel panel-default\"> \n <div class=\"panel-heading\">\n <h3 class=\"sub_header\">News</h3>\n </div>\n <ul style=\"padding-left: 25px; padding-top:15px;list-style: disc; line-height:23px\">\n<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>\n<?php the_title( '<li class=\"entry-title\"><a href=\"' . esc_url( get_permalink() ) . '\" rel=\"bookmark\">', '</a></li>' ); ?>\n\n<?php wp_reset_postdata(); ?>\n<?php endwhile; ?>\n</ul>\n</div>\n</div>\n\n<?php else: ?>\n<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>\n<?php endif; ?>\n<?php\n\n\n\n // articles\n $args1 = array(\n 'post_type' => 'articles',\n 'posts_per_page' => 5,\n 'cat' => $category->term_id,\n);\n\n$the_query1 = new WP_Query( $args1 ); \n?>\n<?php if ( $the_query1->have_posts() ) : ?>\n <!-- .page-header -->\n\n<div class=\"col-md-6 col-sm-6\">\n <div class=\"panel panel-default\"> \n <div class=\"panel-heading\">\n <h3 class=\"sub_header\">Articles</h3>\n </div>\n <ul style=\"padding-left: 25px; padding-top:15px;list-style: disc; line-height:23px\">\n<?php while ( $the_query1->have_posts() ) : $the_query1->the_post(); ?>\n<?php the_title( '<li class=\"entry-title\"><a href=\"' . esc_url( get_permalink() ) . '\" rel=\"bookmark\">', '</a></li>' ); ?>\n\n<?php wp_reset_postdata(); ?>\n<?php endwhile; ?>\n</ul>\n</div>\n</div>\n\n<?php else: ?>\n<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>\n<?php endif; ?>\n</div>\n </main><!-- #main -->\n </div><!-- #primary -->\n<?php\nget_sidebar();\nget_footer();\n\n</code></pre>\n"
},
{
"answer_id": 354443,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 1,
"selected": false,
"text": "<p>The <a href=\"https://developer.wordpress.org/reference/functions/get_the_category/\" rel=\"nofollow noreferrer\"><code>get_the_category()</code></a> function retrieves the categories assigned to the first post from the loop, and that's not what you mean.\nI assume that <code>audit</code>, <code>income</code>, <code>tax</code>, etc. are built-in categories, not custom taxonomy (in this case you need to replace <code>cat</code> parameter of <code>WP_Query</code> to <code>tax_query</code>). </p>\n\n<p>Create <code>category.php</code> file if it doesn't exist by copying <code>archive.php</code>. This way the template will be used only on the category page. </p>\n\n<p>ID of the <strong>currently viewed</strong> category you can get with <a href=\"https://developer.wordpress.org/reference/functions/get_queried_object_id/\" rel=\"nofollow noreferrer\"><code>get_queried_object_id()</code></a>. You don't have to check type of the queried object in the <code>category.php</code> file, it will always be correct. Having a category ID, you insert them into the query parameters and you only receive posts belonging to it.</p>\n\n<p>If you intend to apply the template only to selected categories (audit, income, tax) instead of all use the <a href=\"https://developer.wordpress.org/reference/hooks/type_template/\" rel=\"nofollow noreferrer\"><code>{$type}_template</code></a> filter.</p>\n\n<pre><code>//\n// ge ID of the current category\n$cat_id = get_queried_object_id();\n\n//\n// get 'news' posts from current category \n$args = array(\n 'post_type' => 'news',\n 'posts_per_page' => 10,\n 'cat' => (int)$cat_id, // <==\n //'meta_query' => array(\n // array(\n // 'key' => 'recommended_article',\n // 'value' => '1',\n // 'compare' => '=', // <== \n // )\n )\n);\n$query = new WP_Query( $args );\n//\n// display posts\n// \nwp_reset_postdata();\n\n\n//\n// get 'articles' posts from current category \n$args = array(\n 'post_type' => 'articles', // <==\n 'posts_per_page' => 10,\n 'cat' => (int)$cat_id,\n //'meta_query' => array(\n // array(\n // 'key' => 'recommended_article',\n // 'value' => '1',\n // 'compare' => '=',\n // )\n )\n);\n$query = new WP_Query( $args );\n//\n// ...\n// \nwp_reset_postdata();\n</code></pre>\n"
}
] | 2019/12/12 | [
"https://wordpress.stackexchange.com/questions/354433",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165598/"
] | I have Two Custom Post Types "Article " & "News" and they both use same categories
like [ audit , income , tax] . I want when i open audit category page then the post showsn like below: [](https://i.stack.imgur.com/CUG4T.png)
the code i already tried on archieve.php but isnt working:
```
<?php
$cats = get_the_category();
$args = array(
'post_type' => 'articles',
'post__not_in' => array( get_the_ID() ),
'posts_per_page' => 5,
'cat' => $cats[0]->term_id,
'meta_query' => array(
array(
'key' => 'recommended_article',
'value' => '1',
'compare' => '=='
)
)
);
$query = new WP_Query( $args );
?>
<?php if( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post(); ?>
<!--HTML-->
<?php endwhile; endif; wp_reset_postdata(); ?>
``` | Its Done Thank U so much Everyone Who Answered!
```
<?php
/*
* dglib_breadcrumbs_section_template - hook
*
* @hooked - dglib_breadcrumbs_section_callback - 10
*
* @since 1.0.6
*/
do_action( 'dglib_breadcrumbs_section_template' );
?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<header class="page-header">
<?php
the_archive_title( '<h1 class="page-title">', '</h1>' );
the_archive_description( '<div class="archive-description">', '</div>' );
?>
</header>
<div class="row">
<?php
$category = get_queried_object();
// news
$args = array(
'post_type' => 'news',
'posts_per_page' => 5,
'cat' => $category->term_id,
);
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) : ?>
<!-- .page-header -->
<div class="col-md-6 col-sm-6">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="sub_header">News</h3>
</div>
<ul style="padding-left: 25px; padding-top:15px;list-style: disc; line-height:23px">
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php the_title( '<li class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></li>' ); ?>
<?php wp_reset_postdata(); ?>
<?php endwhile; ?>
</ul>
</div>
</div>
<?php else: ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
<?php
// articles
$args1 = array(
'post_type' => 'articles',
'posts_per_page' => 5,
'cat' => $category->term_id,
);
$the_query1 = new WP_Query( $args1 );
?>
<?php if ( $the_query1->have_posts() ) : ?>
<!-- .page-header -->
<div class="col-md-6 col-sm-6">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="sub_header">Articles</h3>
</div>
<ul style="padding-left: 25px; padding-top:15px;list-style: disc; line-height:23px">
<?php while ( $the_query1->have_posts() ) : $the_query1->the_post(); ?>
<?php the_title( '<li class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></li>' ); ?>
<?php wp_reset_postdata(); ?>
<?php endwhile; ?>
</ul>
</div>
</div>
<?php else: ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
</div>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_sidebar();
get_footer();
``` |
354,492 | <p>In .js file of a theme, there are the 2 events using one function:</p>
<pre><code>$j( window ).on( 'load', function() {
functionName();
} );
$j( document ).ajaxComplete( function() {
functionName();
} );
</code></pre>
<p>I would like to stop it from executing through either functions.php or my own plugin because I already have the same functionality coded. I don't want to edit the .js file of the theme. Is it doable at all?</p>
| [
{
"answer_id": 354503,
"author": "Raba",
"author_id": 127210,
"author_profile": "https://wordpress.stackexchange.com/users/127210",
"pm_score": 3,
"selected": true,
"text": "<p>We need to know how the script is being enqueued, but if it's done right, you will be able to remove that <code>.js</code> file using <code>wp_dequeue_script</code>.</p>\n\n<h3>How to correctly enqueue scripts</h3>\n\n<pre><code>function my_register_script()\n //Registers a script to be enqueued later\n wp_register_script('script-handle', plugins_url('script.js', __FILE__));\n}\nadd_action( 'wp_enqueue_scripts', 'my_register_script', 10);\n\n\nfunction my_enqueue_script(){\n //Enqueue the script\n wp_enqueue_script('script-handle');\n}\n//hook to another action\nadd_action('other_action', 'my_enqueue_script', 10);\n</code></pre>\n\n<p>The <code>wp_register_script</code> register the script to be used, passing a <code>$handle</code> (id) and the script <code>$src</code> (url to the script). The <code>wp_enqueue_script</code> adds that script to our page.</p>\n\n<p>It can also happen that the <code>wp_register_script</code> is not used. In that case, the <code>$src</code> is passed to the <code>wp_enqueue_script</code> like this.</p>\n\n<pre><code>wp_enqueue_script('script-handle', plugins_url('script.js', __FILE__));\n</code></pre>\n\n<h3>How to remove a correctly registered script</h3>\n\n<p>If the script is enqueued correctly, then you can remove it from your <code>functions.php</code> passing the <code>$handle</code> to <code>wp_dequeue_script</code>.</p>\n\n<pre><code>wp_dequeue_script('script-handle');\n</code></pre>\n\n<p><strong>Keep in mind</strong> that this function should be used after the script has been enqueued, so you should check to which action the <code>wp_enqueue_script</code> is hooked and run the <code>wp_dequeue_script</code> later, hooking it to the same action but with a higher priority.</p>\n\n<p>Following the same example, the <code>wp_enqueue_script</code> is hooked to an action with a <code>$priority</code> of 10, so you should hook the dequeue with a bigger priority</p>\n\n<pre><code>function my_dequeue_script(){\n //Removes the enqueued script\n wp_dequeue_script('script-handle');\n}\n//hook to another action\nadd_action('other_action', 'my_dequeue_script', 11);\n</code></pre>\n\n<p>Where 11 in the <code>add_action</code> function is the <code>$priority</code> (Bigger means later execution)</p>\n\n<p><strong>Do not forget</strong> that there may be some scripts that depends of the script you are dequeuing. If thats the case, those scripts won't load.</p>\n"
},
{
"answer_id": 354506,
"author": "Hasan Uj Jaman",
"author_id": 179656,
"author_profile": "https://wordpress.stackexchange.com/users/179656",
"pm_score": 0,
"selected": false,
"text": "<p>I think you just want to remove one of the event listener. For this you could use <strong>wp_enqueue_script</strong> hook. Because most of the wordpress plugin and template files loads here. So add a inline javascript code to after jquery load.</p>\n\n<pre><code>add_action( 'wp_enqueue_script', 'unbind_js_event' );\nfunction unbind_js_event() {\n $script = \"\n $j( document ).ready( function() {\n $j( document ).unbind( 'ajaxComplete' );\n $j( window ).unbind( 'load' );\n });\n \";\n wp_add_inline_script( 'jquery', $script );\n}\n</code></pre>\n"
}
] | 2019/12/12 | [
"https://wordpress.stackexchange.com/questions/354492",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153903/"
] | In .js file of a theme, there are the 2 events using one function:
```
$j( window ).on( 'load', function() {
functionName();
} );
$j( document ).ajaxComplete( function() {
functionName();
} );
```
I would like to stop it from executing through either functions.php or my own plugin because I already have the same functionality coded. I don't want to edit the .js file of the theme. Is it doable at all? | We need to know how the script is being enqueued, but if it's done right, you will be able to remove that `.js` file using `wp_dequeue_script`.
### How to correctly enqueue scripts
```
function my_register_script()
//Registers a script to be enqueued later
wp_register_script('script-handle', plugins_url('script.js', __FILE__));
}
add_action( 'wp_enqueue_scripts', 'my_register_script', 10);
function my_enqueue_script(){
//Enqueue the script
wp_enqueue_script('script-handle');
}
//hook to another action
add_action('other_action', 'my_enqueue_script', 10);
```
The `wp_register_script` register the script to be used, passing a `$handle` (id) and the script `$src` (url to the script). The `wp_enqueue_script` adds that script to our page.
It can also happen that the `wp_register_script` is not used. In that case, the `$src` is passed to the `wp_enqueue_script` like this.
```
wp_enqueue_script('script-handle', plugins_url('script.js', __FILE__));
```
### How to remove a correctly registered script
If the script is enqueued correctly, then you can remove it from your `functions.php` passing the `$handle` to `wp_dequeue_script`.
```
wp_dequeue_script('script-handle');
```
**Keep in mind** that this function should be used after the script has been enqueued, so you should check to which action the `wp_enqueue_script` is hooked and run the `wp_dequeue_script` later, hooking it to the same action but with a higher priority.
Following the same example, the `wp_enqueue_script` is hooked to an action with a `$priority` of 10, so you should hook the dequeue with a bigger priority
```
function my_dequeue_script(){
//Removes the enqueued script
wp_dequeue_script('script-handle');
}
//hook to another action
add_action('other_action', 'my_dequeue_script', 11);
```
Where 11 in the `add_action` function is the `$priority` (Bigger means later execution)
**Do not forget** that there may be some scripts that depends of the script you are dequeuing. If thats the case, those scripts won't load. |
354,639 | <p>I have a grid setup on my portfolio page and for whatever reason I keep getting these two errors:</p>
<blockquote>
<p>Notice: Undefined variable: thumbnail in
/home/hometo10/public_html/wp-content/themes/swank/archive-portfolio.php
on line 22</p>
<p>Notice: Trying to get property of non-object in
/home/hometo10/public_html/wp-content/themes/swank/archive-portfolio.php
on line 22</p>
</blockquote>
<p>Here is my archive-portfolio.php code</p>
<pre><code><?php
//* The custom portfolio post type archive template
//* Add the portfolio blurb section
add_action( 'genesis_before_content', 'swank_portfolioblurb_before_content' );
function swank_portfolioblurb_before_content() {
genesis_widget_area( 'portfolioblurb', array(
'before' => '<div class="portfolioblurb">',
) );
}
//* Add the featured image after post title
add_action( 'genesis_entry_header', 'swank_portfolio_grid' );
function swank_portfolio_grid() {
if ( has_post_thumbnail() ){
echo '<div class="portfolio-featured-image">';
echo '<a href="' . get_permalink() .'" title="' . the_title_attribute( 'echo=0' ) . '">';
echo get_the_post_thumbnail($thumbnail->ID, 'portfolio-featured');
echo '</a>';
echo '</div>';
}
}
//* Remove the ad widget
remove_action( 'genesis_before_loop', 'adspace_before_loop' );
//* Remove author box
remove_action( 'genesis_after_entry', 'genesis_do_author_box_single', 8 );
//* Remove the post meta function
remove_action( 'genesis_entry_footer', 'genesis_post_meta' );
//* Remove the post info function
remove_action( 'genesis_entry_header', 'genesis_post_info', 12 );
//* Force full width content layout
add_filter( 'genesis_pre_get_option_site_layout', '__genesis_return_full_width_content' );
//* Remove the post content
remove_action( 'genesis_entry_content', 'genesis_do_post_content' );
//* Remove the footer widgets
remove_action( 'genesis_before_footer', 'genesis_footer_widget_areas' );
genesis();
</code></pre>
| [
{
"answer_id": 354642,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>It is complaining that <code>$thumbnail</code> is undefined because it's undefined, unknown, it's been pulled out of thin air.</p>\n\n<pre><code>echo get_the_post_thumbnail($thumbnail->ID, 'portfolio-featured');\n</code></pre>\n\n<p>This, is the very first time <code>$thumbnail</code> is mentioned, where did it come from? ¯\\_(ツ)_/¯ I have no idea and neither does PHP, hence the warning. You could change it to <code>$thai_chicken_curry->ID</code> and it would behave the same way, and generate the same warning.</p>\n\n<blockquote>\n <p>You can easily fix this by <em>comungulatorianing</em> the code</p>\n</blockquote>\n\n<p>Notice that the word comungulatorianing doesn't exist, so you might have wondered what I was referring to. PHP did the same when it saw the undefined variable. </p>\n\n<p>When PHP encounters these kinds of issues, it substitutes a <code>null</code>-ish/falsey value, so that function will likely be retrieving the ID of the current post instead ( as defined in the WP docs )</p>\n\n<p><strong>So how do you fix it?</strong> You have several options:</p>\n\n<ul>\n<li>figure out where to get the thumbnail from somehow and assign that attachment post to a variable called <code>$thumbnail</code> so it's now defined/known</li>\n<li>replace that line with something that does what you want, aka display the thumbnail with the size <code>portfolio-featured</code>, which you can probably do via <code>the_post_thumbnail( 'postfolio-featured')</code> <a href=\"https://developer.wordpress.org/reference/functions/the_post_thumbnail/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/the_post_thumbnail/</a></li>\n<li>Go to where you got the code for that function from ( original theme author? ), and raise a support ticket for this bug</li>\n</ul>\n"
},
{
"answer_id": 354780,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 0,
"selected": false,
"text": "<p>If you haven't read <a href=\"https://wordpress.stackexchange.com/a/354642/38603\">Tom's answer to your question</a>, read that first. He gives a good explanation (as always!) of <em>why</em> you are getting an error. This is important information to understand when doing WP development, and he explains it well, so I won't repeat that here.</p>\n\n<p>I do have a suggestion that may fix your issue, which is the undefined <code>$thumbnail</code> value. </p>\n\n<p>In context of how it is used, it appears the original author (I assumed you got this from somewhere other than yourself) expects this to be an object (hence the <code>-></code>). I tried to find where you got it from, since there are a lot of \"re-used\" and \"re-hashed\" code snippets out there for just about everything WP related - some good, some bad.</p>\n\n<p>It appears to come <a href=\"https://gist.github.com/joshrogersdesign/08a1c2ee4bcbdb82e52a\" rel=\"nofollow noreferrer\">from here</a>. Unfortunately, that doesn't provide a solution. If he's the original author, the error originates there, and there's not enough context to determine where he intended <code>$thumbnail</code> to come from.</p>\n\n<p>So looking strictly at the WP functions involved, we can probably make a \"best guess\" that the author intended this to be the current <code>$post</code> object. (That's <em>my</em> guess anyway).</p>\n\n<p>The WP function <code>get_the_post_thumbnail()</code> expects the first parameter to be the <strong>post ID</strong> (<a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/\" rel=\"nofollow noreferrer\">see documentation here</a>). The ID is contained within the object (<code>$post->ID</code>).</p>\n\n<p>In this case, the original snippet author represented <code>$post->ID</code> with <code>$thumbnail->ID</code> which would be fine if <code>$thumbnail</code> was previously defined as the <code>$post</code> object, but it's not. </p>\n\n<p>So to fix this - or at least to attempt to fix it - we need to define the object being passed. We'll assume the current <code>$post</code> is the necessary object, and that it's available as a global. Here's the change you to that section you can try:</p>\n\n<pre><code>if ( has_post_thumbnail() ){\n\n global $post;\n\n echo '<div class=\"portfolio-featured-image\">';\n echo '<a href=\"' . get_permalink() .'\" title=\"' . the_title_attribute( 'echo=0' ) . '\">';\n echo get_the_post_thumbnail($post->ID, 'portfolio-featured');\n echo '</a>';\n echo '</div>';\n}\n</code></pre>\n\n<p>This answer took longer to write than looking these things up on the web (a total of about 2 minutes). So my suggestion is to learn some of these things, how they fit together, and how they are used. Knowing what Tom explained and what I explained, you'd be able to figure this out on your own relatively quickly. The most important part would be to learn how to use WP's documentation for its functions (note where I referenced the docs above). You can use that to figure out what the function is expecting and work backwards from there.</p>\n\n<p><strong>Update</strong></p>\n\n<p>Another possible approach would be to use WP's <code>get_the_ID()</code> function to get the post ID (<a href=\"https://developer.wordpress.org/reference/functions/get_the_id/\" rel=\"nofollow noreferrer\">see docs here</a>). So instead of using the <code>global $post</code>, you would use <code>get_the_ID()</code> to get the ID of the current post so you could pass that in <code>get_the_post_thumbnail()</code>.</p>\n\n<pre><code>if ( has_post_thumbnail() ){\n\n $post_id = get_the_ID();\n\n echo '<div class=\"portfolio-featured-image\">';\n echo '<a href=\"' . get_permalink() .'\" title=\"' . the_title_attribute( 'echo=0' ) . '\">';\n echo get_the_post_thumbnail($post_id, 'portfolio-featured');\n echo '</a>';\n echo '</div>';\n}\n</code></pre>\n"
},
{
"answer_id": 354796,
"author": "Kimberly Lightfoot",
"author_id": 179788,
"author_profile": "https://wordpress.stackexchange.com/users/179788",
"pm_score": 0,
"selected": false,
"text": "<p>This is ALL very helpful and useful information. I learned so much about the Wordpress functionality from troubleshooting this myself but you two both put \"human\" understanding into it and FIXED my problem. Thank you to you both, saved my website and sanity! </p>\n"
}
] | 2019/12/15 | [
"https://wordpress.stackexchange.com/questions/354639",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/179788/"
] | I have a grid setup on my portfolio page and for whatever reason I keep getting these two errors:
>
> Notice: Undefined variable: thumbnail in
> /home/hometo10/public\_html/wp-content/themes/swank/archive-portfolio.php
> on line 22
>
>
> Notice: Trying to get property of non-object in
> /home/hometo10/public\_html/wp-content/themes/swank/archive-portfolio.php
> on line 22
>
>
>
Here is my archive-portfolio.php code
```
<?php
//* The custom portfolio post type archive template
//* Add the portfolio blurb section
add_action( 'genesis_before_content', 'swank_portfolioblurb_before_content' );
function swank_portfolioblurb_before_content() {
genesis_widget_area( 'portfolioblurb', array(
'before' => '<div class="portfolioblurb">',
) );
}
//* Add the featured image after post title
add_action( 'genesis_entry_header', 'swank_portfolio_grid' );
function swank_portfolio_grid() {
if ( has_post_thumbnail() ){
echo '<div class="portfolio-featured-image">';
echo '<a href="' . get_permalink() .'" title="' . the_title_attribute( 'echo=0' ) . '">';
echo get_the_post_thumbnail($thumbnail->ID, 'portfolio-featured');
echo '</a>';
echo '</div>';
}
}
//* Remove the ad widget
remove_action( 'genesis_before_loop', 'adspace_before_loop' );
//* Remove author box
remove_action( 'genesis_after_entry', 'genesis_do_author_box_single', 8 );
//* Remove the post meta function
remove_action( 'genesis_entry_footer', 'genesis_post_meta' );
//* Remove the post info function
remove_action( 'genesis_entry_header', 'genesis_post_info', 12 );
//* Force full width content layout
add_filter( 'genesis_pre_get_option_site_layout', '__genesis_return_full_width_content' );
//* Remove the post content
remove_action( 'genesis_entry_content', 'genesis_do_post_content' );
//* Remove the footer widgets
remove_action( 'genesis_before_footer', 'genesis_footer_widget_areas' );
genesis();
``` | It is complaining that `$thumbnail` is undefined because it's undefined, unknown, it's been pulled out of thin air.
```
echo get_the_post_thumbnail($thumbnail->ID, 'portfolio-featured');
```
This, is the very first time `$thumbnail` is mentioned, where did it come from? ¯\\_(ツ)\_/¯ I have no idea and neither does PHP, hence the warning. You could change it to `$thai_chicken_curry->ID` and it would behave the same way, and generate the same warning.
>
> You can easily fix this by *comungulatorianing* the code
>
>
>
Notice that the word comungulatorianing doesn't exist, so you might have wondered what I was referring to. PHP did the same when it saw the undefined variable.
When PHP encounters these kinds of issues, it substitutes a `null`-ish/falsey value, so that function will likely be retrieving the ID of the current post instead ( as defined in the WP docs )
**So how do you fix it?** You have several options:
* figure out where to get the thumbnail from somehow and assign that attachment post to a variable called `$thumbnail` so it's now defined/known
* replace that line with something that does what you want, aka display the thumbnail with the size `portfolio-featured`, which you can probably do via `the_post_thumbnail( 'postfolio-featured')` <https://developer.wordpress.org/reference/functions/the_post_thumbnail/>
* Go to where you got the code for that function from ( original theme author? ), and raise a support ticket for this bug |
354,641 | <p>On a WordPress page I have a number of H2 headings followed by some text. </p>
<p>I'm trying to group all these blocks along with a common background color so that it looks neat and organized. </p>
<p>Here is a crude example of what I'm trying to achieve in WordPress. Notice the background color goes across the blocks:</p>
<pre><code> A Heading H2 block
A paragraph (containing the main body) block
A short code block
A short code block
</code></pre>
<p>The section highlighted above is a bunch of WordPress blocks with a common background color. This improves readability.</p>
<p>All my attempts color individual blocks with an ugly white space between them rather than a constant color across multiple blocks.</p>
<p><strong>How can I change the background color (or create a "visible panel" for lack of better words) in this manner?</strong> I would like to implement this without modifying the CSS file. I'm using a Hestia theme file in case that helps.</p>
| [
{
"answer_id": 354650,
"author": "Raba",
"author_id": 127210,
"author_profile": "https://wordpress.stackexchange.com/users/127210",
"pm_score": 3,
"selected": true,
"text": "<p>You should group your blocks inside a container block that lets you choose its background color.</p>\n\n<p>I'm going to give you a couple of options, ordered by accessibility.</p>\n\n<h1>Grouped Blocks</h1>\n\n<p>For <strong>WordPress 5.3+</strong>, there is the <strong>Group</strong> block that lets you group blocks and select a background color. Check Toms answer for some screenshots.</p>\n\n<h1>Cover Blocks</h1>\n\n<p>WordPress doesn't have a background color block, but it does have a block called <strong>Cover</strong>, from which you can choose a background image and a background color overlay. The overlay can have 100% opacity, hiding the background image and showing only the color as the background. The problem with this block is that it only lets you use paragraphs and headings inside.</p>\n\n<h1>Plugins</h1>\n\n<p>You could install a custom block that does what you are searching for. There is a plugin that adds a background block that works as a container. It's called <a href=\"https://wordpress.org/plugins/wp-munich-blocks/\" rel=\"nofollow noreferrer\">WP Munich Blocks – Gutenberg Blocks for WordPress</a>.</p>\n\n<h1>Building Your Own Block</h1>\n\n<p>If the previous options don't make you happy, you could create a block yourself.</p>\n\n<p>You can use <a href=\"https://github.com/ahmadawais/create-guten-block\" rel=\"nofollow noreferrer\">Create Gutenberg Block</a>, a developer toolkit that facilitates blocks creation. It may seem a little complicated, but there might be people out there looking for this kind of solution.</p>\n\n<p>This would be a way of doing it. Keep in mind that is a very simple example, but I think that it works pretty well in the editor. You would need to edit the front end look as you like, from CSS to layout.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code> const { __ } = wp.i18n; // Import __() from wp.i18n\n const { registerBlockType } = wp.blocks; // Import registerBlockType() from wp.blocks\n const { InspectorControls, InnerBlocks } = wp.editor;\n const { ColorPicker } = wp.components;\n\n registerBlockType( 'special/background-color', {\n // Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block.\n title: __( 'Background Color' ), // Block title.\n icon: 'media-document', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/.\n category: 'common', // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed.\n keywords: [\n __( 'Background' ),\n __( 'Color' ),\n __( 'Container' ),\n ],\n attributes: {\n color: {\n type: 'string',\n source: 'attribute',\n attribute: 'style',\n },\n },\n // The \"edit\" property must be a valid function.\n edit: function( props ) {\n const { attributes, setAttributes, className, isSelected } = props;\n\n const style = {\n backgroundColor: attributes.color,\n border: 'solid 1px',\n padding: '10px',\n };\n\n return (\n <div style={style} className={className + ' background-color-container-block'}>\n <InnerBlocks />\n <InspectorControls>\n <ColorPicker\n color={ attributes.color }\n onChangeComplete={ ( value ) => setAttributes( {color: value.hex} ) }\n />\n </InspectorControls>\n </div>\n );\n },\n // The \"save\" property must be specified and must be a valid function.\n save: function( { attributes } ) {\n const style = {\n backgroundColor: attributes.color,\n };\n\n return (\n <div style={style} className={'background-color-container-block'}>\n <InnerBlocks.Content />\n </div>\n );\n },\n } );\n</code></pre>\n\n<p>This is going to be a barebones explanation of what's going on here. If you need more information, you can always check out the <a href=\"https://developer.wordpress.org/block-editor/developers/\" rel=\"nofollow noreferrer\">official gutenberg block development documentation</a>.</p>\n\n<p>What we are doing here is registering a block of id <code>special/background-color</code> and name <code>Background Color</code> (you can change those if you want to).</p>\n\n<p>In <code>attributes</code>, we define the data this block works with, and that get saved with the content of the post. In this case we only use the attribute <code>color</code>, that stores the background color for the container.</p>\n\n<p>The <code>edit</code> function controls how the block works on the editor. In this case, we set a container with a <code>background-color</code> that changes with the <code>color</code> attribute. The <code>color</code> is manipulated using the <code>ColorPicker</code> component. When the color changes, we update the view storing the new value using <code>setAttributes</code>. `</p>\n\n<p>The <code>InnerBlocks</code> component is the one that lets us have nested blocks inside the container.</p>\n\n<p>The <code>save</code> function saves the content and controls how the block looks on the front end. Here we only render a div with a <code>background-color</code> equal to the color saved in the <code>attributes</code>. Inside of it, we render the nested blocks using <code>InnerBlocks.Content</code></p>\n\n<p><a href=\"https://i.stack.imgur.com/PlH2a.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PlH2a.png\" alt=\"block editor picture\"></a></p>\n"
},
{
"answer_id": 354715,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>In the latest versions of the block editor/WP 5.3+, you can select multiple blocks, group them, then assign a background colour:</p>\n\n<p><a href=\"https://i.stack.imgur.com/UyNUs.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UyNUs.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/LgbK3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LgbK3.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/PbcZq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PbcZq.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/VC3B8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VC3B8.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/g11u3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/g11u3.png\" alt=\"enter image description here\"></a></p>\n\n<p>You can also set it's width option when the group block is selected:</p>\n\n<p><a href=\"https://i.stack.imgur.com/0R07b.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0R07b.png\" alt=\"enter image description here\"></a></p>\n"
}
] | 2019/12/15 | [
"https://wordpress.stackexchange.com/questions/354641",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/167402/"
] | On a WordPress page I have a number of H2 headings followed by some text.
I'm trying to group all these blocks along with a common background color so that it looks neat and organized.
Here is a crude example of what I'm trying to achieve in WordPress. Notice the background color goes across the blocks:
```
A Heading H2 block
A paragraph (containing the main body) block
A short code block
A short code block
```
The section highlighted above is a bunch of WordPress blocks with a common background color. This improves readability.
All my attempts color individual blocks with an ugly white space between them rather than a constant color across multiple blocks.
**How can I change the background color (or create a "visible panel" for lack of better words) in this manner?** I would like to implement this without modifying the CSS file. I'm using a Hestia theme file in case that helps. | You should group your blocks inside a container block that lets you choose its background color.
I'm going to give you a couple of options, ordered by accessibility.
Grouped Blocks
==============
For **WordPress 5.3+**, there is the **Group** block that lets you group blocks and select a background color. Check Toms answer for some screenshots.
Cover Blocks
============
WordPress doesn't have a background color block, but it does have a block called **Cover**, from which you can choose a background image and a background color overlay. The overlay can have 100% opacity, hiding the background image and showing only the color as the background. The problem with this block is that it only lets you use paragraphs and headings inside.
Plugins
=======
You could install a custom block that does what you are searching for. There is a plugin that adds a background block that works as a container. It's called [WP Munich Blocks – Gutenberg Blocks for WordPress](https://wordpress.org/plugins/wp-munich-blocks/).
Building Your Own Block
=======================
If the previous options don't make you happy, you could create a block yourself.
You can use [Create Gutenberg Block](https://github.com/ahmadawais/create-guten-block), a developer toolkit that facilitates blocks creation. It may seem a little complicated, but there might be people out there looking for this kind of solution.
This would be a way of doing it. Keep in mind that is a very simple example, but I think that it works pretty well in the editor. You would need to edit the front end look as you like, from CSS to layout.
```js
const { __ } = wp.i18n; // Import __() from wp.i18n
const { registerBlockType } = wp.blocks; // Import registerBlockType() from wp.blocks
const { InspectorControls, InnerBlocks } = wp.editor;
const { ColorPicker } = wp.components;
registerBlockType( 'special/background-color', {
// Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block.
title: __( 'Background Color' ), // Block title.
icon: 'media-document', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/.
category: 'common', // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed.
keywords: [
__( 'Background' ),
__( 'Color' ),
__( 'Container' ),
],
attributes: {
color: {
type: 'string',
source: 'attribute',
attribute: 'style',
},
},
// The "edit" property must be a valid function.
edit: function( props ) {
const { attributes, setAttributes, className, isSelected } = props;
const style = {
backgroundColor: attributes.color,
border: 'solid 1px',
padding: '10px',
};
return (
<div style={style} className={className + ' background-color-container-block'}>
<InnerBlocks />
<InspectorControls>
<ColorPicker
color={ attributes.color }
onChangeComplete={ ( value ) => setAttributes( {color: value.hex} ) }
/>
</InspectorControls>
</div>
);
},
// The "save" property must be specified and must be a valid function.
save: function( { attributes } ) {
const style = {
backgroundColor: attributes.color,
};
return (
<div style={style} className={'background-color-container-block'}>
<InnerBlocks.Content />
</div>
);
},
} );
```
This is going to be a barebones explanation of what's going on here. If you need more information, you can always check out the [official gutenberg block development documentation](https://developer.wordpress.org/block-editor/developers/).
What we are doing here is registering a block of id `special/background-color` and name `Background Color` (you can change those if you want to).
In `attributes`, we define the data this block works with, and that get saved with the content of the post. In this case we only use the attribute `color`, that stores the background color for the container.
The `edit` function controls how the block works on the editor. In this case, we set a container with a `background-color` that changes with the `color` attribute. The `color` is manipulated using the `ColorPicker` component. When the color changes, we update the view storing the new value using `setAttributes`. `
The `InnerBlocks` component is the one that lets us have nested blocks inside the container.
The `save` function saves the content and controls how the block looks on the front end. Here we only render a div with a `background-color` equal to the color saved in the `attributes`. Inside of it, we render the nested blocks using `InnerBlocks.Content`
[](https://i.stack.imgur.com/PlH2a.png) |
354,655 | <p>I'm working on a personal project which includes multiple custom fields (created via ACF). A few of them are repeater types. </p>
<p>I want to to display 3 arrays/blocks of those repeater subfield values. For better understanding, I have this repeater field: open_workshops, and this field includes subfields: date, location, partnerships.</p>
<p>I want simply to show all values from those subfields stored in DB. Something like:</p>
<p>Open Workshops:</p>
<ul>
<li><p>Date: Jan 2017, Feb 2017...Dec 2019 etc</p></li>
<li><p>Location: New York, Warsaw...</p></li>
<li><p>Partnerships: EY, Google..</p></li>
</ul>
<p>What issues I've noticed - first of all, because of field type (repeater) it's damn hard to find those values in the DB. Because its not a single field but ACF replicates their names, so instead of looking for single field: open_workshops_date i need somehow to find: open_workshops_0_date, open_workshops_1_date etc. </p>
<p>My initial code was:</p>
<pre><code> if( have_rows('open_workshops') ):
while ( have_rows('open_workshops') ) : the_row();
$sub_value_1 = get_sub_field('date');
$sub_value_2 = get_sub_field('location');
$sub_value_3 = get_sub_field('partnerships');
echo '$sub_value_1';
echo '$sub_value_2';
echo '$sub_value_3';
endwhile;
else :
// no rows found
endif;
</code></pre>
<p>I've tried as well the suggestion from this post:
<a href="https://wordpress.stackexchange.com/questions/309602/retrieving-all-data-from-repeater-fields">Retrieving all data from repeater fields</a></p>
<p>but it shows nothing.</p>
| [
{
"answer_id": 354851,
"author": "Bhupen",
"author_id": 128529,
"author_profile": "https://wordpress.stackexchange.com/users/128529",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried passing post id? Please see below:</p>\n\n<pre><code>if( have_rows('parent_field', $post_id) ):\nwhile ( have_rows('parent_field', $post_id) ) : the_row();\n $sub_value = get_sub_field('sub_field');\n // Do something...\nendwhile;\nelse :\n // no rows found\nendif;\n</code></pre>\n"
},
{
"answer_id": 354855,
"author": "Guru Bhajan Singh",
"author_id": 132606,
"author_profile": "https://wordpress.stackexchange.com/users/132606",
"pm_score": -1,
"selected": false,
"text": "<p>the Repeater field of ACF follows a simple method, this set of code will help you.</p>\n\n<pre><code>if( get_field('open_workshops', get_the_ID()) ):\n\n$counter = 0;\nwhile( the_repeater_field('open_workshops', get_the_ID())):\n\n//this sets up the counter starting at 0\necho get_field('open_workshops_'.$counter.'_date', get_the_ID());\necho get_field('open_workshops_'.$counter.'_location', get_the_ID());\necho get_field('open_workshops_'.$counter.'_partnerships', get_the_ID());\n\n$counter++; // add one per row\nendwhile;\nendif;\n</code></pre>\n"
},
{
"answer_id": 354891,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 2,
"selected": true,
"text": "<p>I don't think ACF has a built-in function to do what you want. You can use <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\">get_field</a> to retrieve a value from any post, but it requires a post ID if you want the value from anything other than the current post.</p>\n\n<p>So instead, we can query posts using <a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">WP_Query</a> and pass the meta key of our custom field.</p>\n\n<p>Here is an example.</p>\n\n<pre><code>$args = array(\n 'post_type' => 'page', // Add your post type here\n 'meta_key' => 'test_repeater' // Add your repeater name here\n);\n\n$the_query = new WP_Query($args);\n\nif ($the_query->have_posts()):\n while ($the_query->have_posts()) : $the_query->the_post();\n if(have_rows('test_repeater')): // Add your repeater here\n while (have_rows('test_repeater')) : the_row(); // Add your repeater here\n // display your sub fields\n the_sub_field('sub_field_one');\n the_sub_field('sub_field_two');\n endwhile;\n else :\n // no rows found\n endif;\n endwhile;\nendif;\n</code></pre>\n\n<p>I added the above code to a page template, it will spit out the values of my <code>test_repeater</code> for any <code>page</code> that has those custom fields filled out.</p>\n\n<p>Tested and works.</p>\n"
}
] | 2019/12/15 | [
"https://wordpress.stackexchange.com/questions/354655",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25217/"
] | I'm working on a personal project which includes multiple custom fields (created via ACF). A few of them are repeater types.
I want to to display 3 arrays/blocks of those repeater subfield values. For better understanding, I have this repeater field: open\_workshops, and this field includes subfields: date, location, partnerships.
I want simply to show all values from those subfields stored in DB. Something like:
Open Workshops:
* Date: Jan 2017, Feb 2017...Dec 2019 etc
* Location: New York, Warsaw...
* Partnerships: EY, Google..
What issues I've noticed - first of all, because of field type (repeater) it's damn hard to find those values in the DB. Because its not a single field but ACF replicates their names, so instead of looking for single field: open\_workshops\_date i need somehow to find: open\_workshops\_0\_date, open\_workshops\_1\_date etc.
My initial code was:
```
if( have_rows('open_workshops') ):
while ( have_rows('open_workshops') ) : the_row();
$sub_value_1 = get_sub_field('date');
$sub_value_2 = get_sub_field('location');
$sub_value_3 = get_sub_field('partnerships');
echo '$sub_value_1';
echo '$sub_value_2';
echo '$sub_value_3';
endwhile;
else :
// no rows found
endif;
```
I've tried as well the suggestion from this post:
[Retrieving all data from repeater fields](https://wordpress.stackexchange.com/questions/309602/retrieving-all-data-from-repeater-fields)
but it shows nothing. | I don't think ACF has a built-in function to do what you want. You can use [get\_field](https://www.advancedcustomfields.com/resources/get_field/) to retrieve a value from any post, but it requires a post ID if you want the value from anything other than the current post.
So instead, we can query posts using [WP\_Query](https://developer.wordpress.org/reference/classes/wp_query/) and pass the meta key of our custom field.
Here is an example.
```
$args = array(
'post_type' => 'page', // Add your post type here
'meta_key' => 'test_repeater' // Add your repeater name here
);
$the_query = new WP_Query($args);
if ($the_query->have_posts()):
while ($the_query->have_posts()) : $the_query->the_post();
if(have_rows('test_repeater')): // Add your repeater here
while (have_rows('test_repeater')) : the_row(); // Add your repeater here
// display your sub fields
the_sub_field('sub_field_one');
the_sub_field('sub_field_two');
endwhile;
else :
// no rows found
endif;
endwhile;
endif;
```
I added the above code to a page template, it will spit out the values of my `test_repeater` for any `page` that has those custom fields filled out.
Tested and works. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.