qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
315,456
<p>I'm new to WordPress and have been developing a new website that will replace an old non-WordPress site. WordPress is currently installed in a subfolder whilst I've been creating the new site and it's now ready to go live. (Just to point out, it's a static website without any of the blog stuff going on).</p> <p>There are two things I want to accomplish now and I think I know what needs to be done but I just want to confirm that I'm on the right track:</p> <p>1) The current (old) website is on www.xyz.com and the new WordPress site is at www.xyz.com/wordpress. I want to make sure that when someone now goes to www.xyz.com, they get to the new WordPress site (i.e. www.xyz.com/wordpress). </p> <ul> <li>in WordPress admin, go to Settings => General</li> <li>change "Site Address (URL)" to be "www.xyz.com" (leave "WordPress Address (URL)" as "www.xyz.com/wordpress")</li> <li>save changes</li> <li>copy .htaccess and index.php from \wordpress subfolder into root (i.e. public_html)</li> <li><p>open index.php and change:</p> <pre><code>require( dirname( __FILE__ ) . '/wp-blog-header.php' ); </code></pre> <p>to be:</p> <pre><code>require( dirname( __FILE__ ) . '/wordpress/wp-blog-header.php' ); </code></pre></li> </ul> <p>2) I don't want to have to include "index.php" in links to the new site; i.e. I want to be able to go to www.xyz.com/some_page and not have to use www.xyz.com/index.php/some_page</p> <ul> <li><p>edit .htaccess file and include in it:</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>I'm not sure if that last RewriteRule line should include the /wordpress subfolder or whether it's not required due to the previous change to index.php? Or would I need to change it to:</p> <pre><code>RewriteRule . /wordpress/index.php [L] </code></pre></li> </ul> <p>Thanks</p>
[ { "answer_id": 315393, "author": "realloc", "author_id": 6972, "author_profile": "https://wordpress.stackexchange.com/users/6972", "pm_score": 0, "selected": false, "text": "<p>Yoast's SEO plugin has a <a href=\"https://yoast.com/wordpress/plugins/seo/api/\" rel=\"nofollow noreferrer\">n...
2018/09/28
[ "https://wordpress.stackexchange.com/questions/315456", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151091/" ]
I'm new to WordPress and have been developing a new website that will replace an old non-WordPress site. WordPress is currently installed in a subfolder whilst I've been creating the new site and it's now ready to go live. (Just to point out, it's a static website without any of the blog stuff going on). There are two things I want to accomplish now and I think I know what needs to be done but I just want to confirm that I'm on the right track: 1) The current (old) website is on www.xyz.com and the new WordPress site is at www.xyz.com/wordpress. I want to make sure that when someone now goes to www.xyz.com, they get to the new WordPress site (i.e. www.xyz.com/wordpress). * in WordPress admin, go to Settings => General * change "Site Address (URL)" to be "www.xyz.com" (leave "WordPress Address (URL)" as "www.xyz.com/wordpress") * save changes * copy .htaccess and index.php from \wordpress subfolder into root (i.e. public\_html) * open index.php and change: ``` require( dirname( __FILE__ ) . '/wp-blog-header.php' ); ``` to be: ``` require( dirname( __FILE__ ) . '/wordpress/wp-blog-header.php' ); ``` 2) I don't want to have to include "index.php" in links to the new site; i.e. I want to be able to go to www.xyz.com/some\_page and not have to use www.xyz.com/index.php/some\_page * edit .htaccess file and include in it: ``` # 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 ``` I'm not sure if that last RewriteRule line should include the /wordpress subfolder or whether it's not required due to the previous change to index.php? Or would I need to change it to: ``` RewriteRule . /wordpress/index.php [L] ``` Thanks
Basically this is the answer I was looking for from this question: ``` function yoastVariableToTitle( $post_id ) { $yoast_title = get_post_meta( $post_id, '_yoast_wpseo_title', true ); $title = strstr( $yoast_title, '%%', true ); if ( empty( $title ) ) { $title = get_the_title( $post_id ); } $wpseo_titles = get_option( 'wpseo_titles' ); $sep_options = WPSEO_Option_Titles::get_instance()->get_separator_options(); if ( isset( $wpseo_titles['separator'] ) && isset( $sep_options[ $wpseo_titles['separator'] ] ) ) { $sep = $sep_options[ $wpseo_titles['separator'] ]; } else { $sep = '-'; //setting default separator if Admin didn't set it from backed } $site_title = get_bloginfo( 'name' ); $meta_title = $title . ' ' . $sep . ' ' . $site_title; return $meta_title; } ``` <https://stackoverflow.com/questions/41361510/is-there-any-way-to-get-yoast-title-inside-page-using-their-variable-i-e-ti>
315,485
<p>I am trying to enable revisions for an existing custom post type. As the post type was already created about 2 years ago so where the post type was register I added <code>revisions</code> to the <code>supports</code> array.</p> <p>Earlier my code was like:</p> <pre><code> $labels = array( 'name' =&gt; 'Products', 'singular_name' =&gt; 'Product', 'all_items' =&gt; 'All Products', 'add_new' =&gt; 'Add New', 'add_new_item' =&gt; 'Add New Product', 'edit_item' =&gt; 'Edit Products', 'new_item' =&gt; 'New Product', 'view_item' =&gt; 'View Product', 'search_items' =&gt; 'Search Products', 'not_found' =&gt; 'No Prducsts Found', 'not_found_in_trash' =&gt; 'No Products in Trash', 'parent_item_colon' =&gt; '' ); $supports = array( 'title', 'custom-fields', 'editor', 'thumbnail' ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'menu_position' =&gt; 5, 'rewrite' =&gt; array( 'slug' =&gt; 'products' ), 'has_archive' =&gt; true, 'supports' =&gt; $supports ); register_post_type('products', $args); </code></pre> <p>And now it looks like:</p> <pre><code> $labels = array( 'name' =&gt; 'Products', 'singular_name' =&gt; 'Product', 'all_items' =&gt; 'All Products', 'add_new' =&gt; 'Add New', 'add_new_item' =&gt; 'Add New Product', 'edit_item' =&gt; 'Edit Products', 'new_item' =&gt; 'New Product', 'view_item' =&gt; 'View Product', 'search_items' =&gt; 'Search Products', 'not_found' =&gt; 'No Prducsts Found', 'not_found_in_trash' =&gt; 'No Products in Trash', 'parent_item_colon' =&gt; '' ); $supports = array( 'title', 'custom-fields', 'editor', 'thumbnail', 'revisions' ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'menu_position' =&gt; 5, 'rewrite' =&gt; array( 'slug' =&gt; 'products' ), 'has_archive' =&gt; true, 'supports' =&gt; $supports ); register_post_type('products', $args); </code></pre> <p>This code didn't enable revisions in the custom post type.</p> <p>Then I found another code which I added to my theme's function.php:</p> <pre><code>function add_revisions_custom_post() { add_post_type_support( 'products', 'revisions' ); } add_action('init','add_revisions_custom_post'); </code></pre> <p>This one is also not working.</p> <p>Can anyone suggest me how I can enable revisions?</p> <p>Thanks in advance.</p> <p><strong>EDIT:</strong> Here is my wp-config.php file.</p> <pre><code>&lt;?php /** * The base configurations of the WordPress. * * This file has the following configurations: MySQL settings, Table Prefix, * Secret Keys, WordPress Language, and ABSPATH. You can find more information * by visiting {@link http://codex.wordpress.org/Editing_wp-config.php Editing * wp-config.php} Codex page. You can get the MySQL settings from your web host. * * This file is used by the wp-config.php creation script during the * installation. You don't have to use the web site, you can just copy this file * to "wp-config.php" and fill in the values. * * @package WordPress */ // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define('WP_MEMORY_LIMIT', '64MB'); define('DB_NAME', 'MYDBNAME'); /** MySQL database username */ define('DB_USER', 'MYDBUSER'); /** MySQL database password */ define('DB_PASSWORD', 'MYDBPASSWORD'); /** MySQL hostname */ define('DB_HOST', 'localhost'); /** Database Charset to use in creating database tables. */ define('DB_CHARSET', 'utf8'); /** The Database Collate type. Don't change this if in doubt. */ define('DB_COLLATE', ''); define('WP_MEMORY_LIMIT', '64MB'); /**#@+ * Authentication Unique Keys and Salts. * * Change these to different unique phrases! * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service} * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again. * * @since 2.6.0 */ define('AUTH_KEY', 'c7ypbekexsfbt4wiucppwewene93cbtcfhf6xgpggepycabhildsoyqpre5iv3wi'); define('SECURE_AUTH_KEY', 'ujjxufvylpndsj0qeuwa90gxawj3cgaqnyusrdbmujmb08r37pnyreorpcyxqouu'); define('LOGGED_IN_KEY', 'vwlhlmenthgrq9g5jcocihz4ndldhrpegmcp6qyb3rfmjvxjejbacv1zharaexlp'); define('NONCE_KEY', 'qhnyqgmqckh3ylasveugagqlvifiuqajl6s9e7ulfrxepdxh2mewr8qhdinua8o2'); define('AUTH_SALT', 'rlb723gcatjvkfrd3jscmvdjio3kx9apm5yie9e4ibxktnnlukvgfpgbdsohrns9'); define('SECURE_AUTH_SALT', 'pllenyye8zbtml91hekptc2clqr7bhvhlriecz5qozexfhiqptmcvxrlehj44c16'); define('LOGGED_IN_SALT', '9lyqc6qod0zdgyh6esp7bsxmpmuyp3h64m62pcnwxyefejh6tjykm7tpxhecg3xy'); define('NONCE_SALT', 'ob0bq3fye46rubbgu5flycjuai4ygxqgxho8bb1k8t81mwhghcbkysrgxrjzx0fu'); /**#@-*/ /** * WordPress Database Table prefix. * * You can have multiple installations in one database if you give each a unique * prefix. Only numbers, letters, and underscores please! */ $table_prefix = 'wp_'; /** * WordPress Localized Language, defaults to English. * * Change this to localize WordPress. A corresponding MO file for the chosen * language must be installed to wp-content/languages. For example, install * de_DE.mo to wp-content/languages and set WPLANG to 'de_DE' to enable German * language support. */ define ('WPLANG', ''); /** * For developers: WordPress debugging mode. * * Change this to true to enable the display of notices during development. * It is strongly recommended that plugin and theme developers use WP_DEBUG * in their development environments. */ define('WP_DEBUG', false); /* That's all, stop editing! Happy blogging. */ /** Absolute path to the WordPress directory. */ if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); /** Sets up WordPress vars and included files. */ require_once(ABSPATH . 'wp-settings.php'); </code></pre>
[ { "answer_id": 315393, "author": "realloc", "author_id": 6972, "author_profile": "https://wordpress.stackexchange.com/users/6972", "pm_score": 0, "selected": false, "text": "<p>Yoast's SEO plugin has a <a href=\"https://yoast.com/wordpress/plugins/seo/api/\" rel=\"nofollow noreferrer\">n...
2018/09/29
[ "https://wordpress.stackexchange.com/questions/315485", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126701/" ]
I am trying to enable revisions for an existing custom post type. As the post type was already created about 2 years ago so where the post type was register I added `revisions` to the `supports` array. Earlier my code was like: ``` $labels = array( 'name' => 'Products', 'singular_name' => 'Product', 'all_items' => 'All Products', 'add_new' => 'Add New', 'add_new_item' => 'Add New Product', 'edit_item' => 'Edit Products', 'new_item' => 'New Product', 'view_item' => 'View Product', 'search_items' => 'Search Products', 'not_found' => 'No Prducsts Found', 'not_found_in_trash' => 'No Products in Trash', 'parent_item_colon' => '' ); $supports = array( 'title', 'custom-fields', 'editor', 'thumbnail' ); $args = array( 'labels' => $labels, 'public' => true, 'menu_position' => 5, 'rewrite' => array( 'slug' => 'products' ), 'has_archive' => true, 'supports' => $supports ); register_post_type('products', $args); ``` And now it looks like: ``` $labels = array( 'name' => 'Products', 'singular_name' => 'Product', 'all_items' => 'All Products', 'add_new' => 'Add New', 'add_new_item' => 'Add New Product', 'edit_item' => 'Edit Products', 'new_item' => 'New Product', 'view_item' => 'View Product', 'search_items' => 'Search Products', 'not_found' => 'No Prducsts Found', 'not_found_in_trash' => 'No Products in Trash', 'parent_item_colon' => '' ); $supports = array( 'title', 'custom-fields', 'editor', 'thumbnail', 'revisions' ); $args = array( 'labels' => $labels, 'public' => true, 'menu_position' => 5, 'rewrite' => array( 'slug' => 'products' ), 'has_archive' => true, 'supports' => $supports ); register_post_type('products', $args); ``` This code didn't enable revisions in the custom post type. Then I found another code which I added to my theme's function.php: ``` function add_revisions_custom_post() { add_post_type_support( 'products', 'revisions' ); } add_action('init','add_revisions_custom_post'); ``` This one is also not working. Can anyone suggest me how I can enable revisions? Thanks in advance. **EDIT:** Here is my wp-config.php file. ``` <?php /** * The base configurations of the WordPress. * * This file has the following configurations: MySQL settings, Table Prefix, * Secret Keys, WordPress Language, and ABSPATH. You can find more information * by visiting {@link http://codex.wordpress.org/Editing_wp-config.php Editing * wp-config.php} Codex page. You can get the MySQL settings from your web host. * * This file is used by the wp-config.php creation script during the * installation. You don't have to use the web site, you can just copy this file * to "wp-config.php" and fill in the values. * * @package WordPress */ // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define('WP_MEMORY_LIMIT', '64MB'); define('DB_NAME', 'MYDBNAME'); /** MySQL database username */ define('DB_USER', 'MYDBUSER'); /** MySQL database password */ define('DB_PASSWORD', 'MYDBPASSWORD'); /** MySQL hostname */ define('DB_HOST', 'localhost'); /** Database Charset to use in creating database tables. */ define('DB_CHARSET', 'utf8'); /** The Database Collate type. Don't change this if in doubt. */ define('DB_COLLATE', ''); define('WP_MEMORY_LIMIT', '64MB'); /**#@+ * Authentication Unique Keys and Salts. * * Change these to different unique phrases! * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service} * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again. * * @since 2.6.0 */ define('AUTH_KEY', 'c7ypbekexsfbt4wiucppwewene93cbtcfhf6xgpggepycabhildsoyqpre5iv3wi'); define('SECURE_AUTH_KEY', 'ujjxufvylpndsj0qeuwa90gxawj3cgaqnyusrdbmujmb08r37pnyreorpcyxqouu'); define('LOGGED_IN_KEY', 'vwlhlmenthgrq9g5jcocihz4ndldhrpegmcp6qyb3rfmjvxjejbacv1zharaexlp'); define('NONCE_KEY', 'qhnyqgmqckh3ylasveugagqlvifiuqajl6s9e7ulfrxepdxh2mewr8qhdinua8o2'); define('AUTH_SALT', 'rlb723gcatjvkfrd3jscmvdjio3kx9apm5yie9e4ibxktnnlukvgfpgbdsohrns9'); define('SECURE_AUTH_SALT', 'pllenyye8zbtml91hekptc2clqr7bhvhlriecz5qozexfhiqptmcvxrlehj44c16'); define('LOGGED_IN_SALT', '9lyqc6qod0zdgyh6esp7bsxmpmuyp3h64m62pcnwxyefejh6tjykm7tpxhecg3xy'); define('NONCE_SALT', 'ob0bq3fye46rubbgu5flycjuai4ygxqgxho8bb1k8t81mwhghcbkysrgxrjzx0fu'); /**#@-*/ /** * WordPress Database Table prefix. * * You can have multiple installations in one database if you give each a unique * prefix. Only numbers, letters, and underscores please! */ $table_prefix = 'wp_'; /** * WordPress Localized Language, defaults to English. * * Change this to localize WordPress. A corresponding MO file for the chosen * language must be installed to wp-content/languages. For example, install * de_DE.mo to wp-content/languages and set WPLANG to 'de_DE' to enable German * language support. */ define ('WPLANG', ''); /** * For developers: WordPress debugging mode. * * Change this to true to enable the display of notices during development. * It is strongly recommended that plugin and theme developers use WP_DEBUG * in their development environments. */ define('WP_DEBUG', false); /* That's all, stop editing! Happy blogging. */ /** Absolute path to the WordPress directory. */ if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); /** Sets up WordPress vars and included files. */ require_once(ABSPATH . 'wp-settings.php'); ```
Basically this is the answer I was looking for from this question: ``` function yoastVariableToTitle( $post_id ) { $yoast_title = get_post_meta( $post_id, '_yoast_wpseo_title', true ); $title = strstr( $yoast_title, '%%', true ); if ( empty( $title ) ) { $title = get_the_title( $post_id ); } $wpseo_titles = get_option( 'wpseo_titles' ); $sep_options = WPSEO_Option_Titles::get_instance()->get_separator_options(); if ( isset( $wpseo_titles['separator'] ) && isset( $sep_options[ $wpseo_titles['separator'] ] ) ) { $sep = $sep_options[ $wpseo_titles['separator'] ]; } else { $sep = '-'; //setting default separator if Admin didn't set it from backed } $site_title = get_bloginfo( 'name' ); $meta_title = $title . ' ' . $sep . ' ' . $site_title; return $meta_title; } ``` <https://stackoverflow.com/questions/41361510/is-there-any-way-to-get-yoast-title-inside-page-using-their-variable-i-e-ti>
315,490
<p>So I had previously tested a specific redirect where I knew the page exists. </p> <pre><code>function nepal_template_redirect() { if ( is_category( 'nepal' ) ) { $url = site_url( '/nepal' ); wp_safe_redirect( $url, 301 ); exit(); } } add_action( 'template_redirect', 'nepal_template_redirect' ); </code></pre> <p>However what I really want to do is include a generic function that redirects any category where a page name exists of the same name. So I thought along these lines.</p> <pre><code>function pagefromcat_template_redirect() { $category_id = get_cat_ID( 'Category Name' ); if (page_exists($category_id)) { $url = site_url( '/' . $category_id); wp_safe_redirect( $url, 301 ); } } add_action( 'template_redirect', 'pagefromcat_template_redirect' ); </code></pre> <p>However there does not seem to be a codex item for anything like page_exists()</p> <p>So how would I write a function to do this? Or is there an existing one that I have missed. Thanks</p>
[ { "answer_id": 315499, "author": "Hans", "author_id": 129367, "author_profile": "https://wordpress.stackexchange.com/users/129367", "pm_score": 1, "selected": false, "text": "<p><code>get_page_by_path</code> does something similar:</p>\n\n<pre><code>function pagefromcat_template_redirect...
2018/09/29
[ "https://wordpress.stackexchange.com/questions/315490", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69236/" ]
So I had previously tested a specific redirect where I knew the page exists. ``` function nepal_template_redirect() { if ( is_category( 'nepal' ) ) { $url = site_url( '/nepal' ); wp_safe_redirect( $url, 301 ); exit(); } } add_action( 'template_redirect', 'nepal_template_redirect' ); ``` However what I really want to do is include a generic function that redirects any category where a page name exists of the same name. So I thought along these lines. ``` function pagefromcat_template_redirect() { $category_id = get_cat_ID( 'Category Name' ); if (page_exists($category_id)) { $url = site_url( '/' . $category_id); wp_safe_redirect( $url, 301 ); } } add_action( 'template_redirect', 'pagefromcat_template_redirect' ); ``` However there does not seem to be a codex item for anything like page\_exists() So how would I write a function to do this? Or is there an existing one that I have missed. Thanks
Seems like I have it now. Largely due to @Michael - it requires of course that a category is exactly the same as a Page Title, but that is exactly what I want. function pagefromcat\_template\_redirect() { if ( ! is\_category() ) { return; } ``` $category = get_queried_object(); // $page = get_page_by_path( $category->slug ); -- doesnt work // $page = get_page_by_path( 'destinations/' . $category->slug); works but with deeper nested locations this will cause a problem, and we will have to have multiple prefixed locations // atcivities immediately for instance. $page = get_page_by_title($category->name); if ( $page instanceof WP_Post ) { $url = get_permalink( $page ); wp_safe_redirect( $url, 301 ); } ``` }
315,511
<p>As we know by the provided API from Gutenberg we can create a custom block as</p> <pre><code>const { registerBlockType } = wp.blocks; registerBlockType( 'my-namespace/my-block', { }) </code></pre> <p>but how do I create a wrapper(category like layout) around my custom blocks in gutenberg editor? Let's say I want to have a collector for my custom elements as slider, gallery ...</p>
[ { "answer_id": 315563, "author": "fefe", "author_id": 23759, "author_profile": "https://wordpress.stackexchange.com/users/23759", "pm_score": 5, "selected": true, "text": "<p>Digging myself deeper in documentation, I got the following result.</p>\n<p>There is a way to group your custom b...
2018/09/29
[ "https://wordpress.stackexchange.com/questions/315511", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/23759/" ]
As we know by the provided API from Gutenberg we can create a custom block as ``` const { registerBlockType } = wp.blocks; registerBlockType( 'my-namespace/my-block', { }) ``` but how do I create a wrapper(category like layout) around my custom blocks in gutenberg editor? Let's say I want to have a collector for my custom elements as slider, gallery ...
Digging myself deeper in documentation, I got the following result. There is a way to group your custom blocks around a given category in Gutenberg, and therefore we have the method [`block_categories_all`](https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#block_categories_all). So with a filter, you can extend the default categories with custom ones. Here is my example: ``` add_filter( 'block_categories_all', function( $categories, $post ) { return array_merge( $categories, array( array( 'slug' => 'my-slug', 'title' => 'my-title', ), ) ); }, 10, 2 ); ``` You can find more on this in [the provided API](https://wordpress.org/gutenberg/handbook/block-api).
315,576
<p>I am trying to copy an image uploaded using Contact Form 7 to the uploads directory but this only produces an empty jpeg file with 0644 permissions even though the dev directory and the uploads directory have 777 permissions while I try to solve the problem.</p> <p>I have had this particular set-up working, at least with the version of CF7 current in January 2017 but I cannot fathom why the copied images are always 0-byte files.</p> <p>The files are all correctly uploaded to Contact Form 7/Flamingo's wpcf7_uploads directory, which resides inside the standard uploads directory, so that's not the problem. It's copying them to another directory so I can rename them and display them that isn't happening.</p> <p>Just to re-iterate, since I can't seem to update via comments, as far as Contact Form 7 is concerned - and its sibling Flamingo plugin, which allows for saving of uploaded info/images as opposed to simply forwarding and then deleting them - both are playing their part excellently, uploading and saving the images, at least once the line </p> <pre><code>$this-&gt;remove_uploaded_files(); </code></pre> <p>is commented out (/plugins/contact_form-7/includes/submission.php, line 223, in the submit() function. The problem is simply that attempting to copy the files into a custom directory outside of wp-content fails, and produces 0-byte jpeg images. </p>
[ { "answer_id": 315588, "author": "Electron", "author_id": 148986, "author_profile": "https://wordpress.stackexchange.com/users/148986", "pm_score": 0, "selected": false, "text": "<h2>Use The WordPress UI to Upload Images</h2>\n\n<p>When images are copied into a WordPress directory outsid...
2018/09/30
[ "https://wordpress.stackexchange.com/questions/315576", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133963/" ]
I am trying to copy an image uploaded using Contact Form 7 to the uploads directory but this only produces an empty jpeg file with 0644 permissions even though the dev directory and the uploads directory have 777 permissions while I try to solve the problem. I have had this particular set-up working, at least with the version of CF7 current in January 2017 but I cannot fathom why the copied images are always 0-byte files. The files are all correctly uploaded to Contact Form 7/Flamingo's wpcf7\_uploads directory, which resides inside the standard uploads directory, so that's not the problem. It's copying them to another directory so I can rename them and display them that isn't happening. Just to re-iterate, since I can't seem to update via comments, as far as Contact Form 7 is concerned - and its sibling Flamingo plugin, which allows for saving of uploaded info/images as opposed to simply forwarding and then deleting them - both are playing their part excellently, uploading and saving the images, at least once the line ``` $this->remove_uploaded_files(); ``` is commented out (/plugins/contact\_form-7/includes/submission.php, line 223, in the submit() function. The problem is simply that attempting to copy the files into a custom directory outside of wp-content fails, and produces 0-byte jpeg images.
Since i was also looking for some sort of keeping submitted images, i found this simple plugin, which gave me a bit insight: <https://wordpress.org/plugins/store-file-uploads-for-contact-form-7/> Also if you read a bit on the mentioned "file-uploading-and-attachment" topic in cf7, you should get the point: > > For security reasons, specifying files outside of the wp-content > directory for email attachments is not allowed, so place the files in > the wp-content or its subdirectory. > > > I think if you stay within the wp-content dir, your copy-func may have its content.
315,582
<p>I'd like to know if I can remove the limit on the posts_per_page for a specific post type. </p> <p>In the archive.php page I'm displaying different post type, and for the specific "publications" post type I want to display all the posts. How can I achieve this without impacting the traditional "post" type? </p>
[ { "answer_id": 315585, "author": "FFrewin", "author_id": 43534, "author_profile": "https://wordpress.stackexchange.com/users/43534", "pm_score": 4, "selected": true, "text": "<p>You can hook into the <code>pre_get_posts</code> action, to access the <code>$query</code> object.</p>\n\n<p>Y...
2018/10/01
[ "https://wordpress.stackexchange.com/questions/315582", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151550/" ]
I'd like to know if I can remove the limit on the posts\_per\_page for a specific post type. In the archive.php page I'm displaying different post type, and for the specific "publications" post type I want to display all the posts. How can I achieve this without impacting the traditional "post" type?
You can hook into the `pre_get_posts` action, to access the `$query` object. You should use your action hook inside your functions.php. An example of what your function could look like: ``` add_action( 'pre_get_posts', 'publications_archive_query' ); function publications_archive_query( $query ) { if ( !is_admin() && $query->is_main_query()) { if ( $query->get('post_type') === 'publications' ) { $query->set( 'posts_per_page', 5 ); } } ``` Narrow down what is the query you are modifying by using conditional checks. `$query->get('post_type')` to get current's Query post\_type to check against. `is_main_query` to make sure you are only applying your query modification to the main query. Read further and find more examples: <https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts>
315,603
<p>I would like to add an extra row to the Cart Table in Woommerce, but I can't find the right action. </p> <p>From this file <a href="https://github.com/woocommerce/woocommerce/blob/master/templates/cart/cart.php" rel="nofollow noreferrer">https://github.com/woocommerce/woocommerce/blob/master/templates/cart/cart.php</a>, I would expect the 'woocommerce_after_cart_contents' action to be the right one (line 149), but it prints the content above the cart table. Am I missing anything?</p> <p>Here's the code (in <code>functions.php</code>):</p> <pre><code>function quality_certificates(){ echo '&lt;tr&gt;TEST&lt;/tr&gt;'; } add_action('woocommerce_cart_contents','quality_certificates'); </code></pre> <p>And this is the output:</p> <pre><code>&lt;form class="woocommerce-cart-form" action="..." method="post"&gt; TEST&lt;table class="shop_table ..."&gt; </code></pre> <p>etc.</p>
[ { "answer_id": 315610, "author": "VinothRaja", "author_id": 146008, "author_profile": "https://wordpress.stackexchange.com/users/146008", "pm_score": 0, "selected": false, "text": "<p>try this below hook</p>\n\n<pre><code>function custom_cart_function(){\n\n echo 'demo';\n}\n\nadd_ac...
2018/10/01
[ "https://wordpress.stackexchange.com/questions/315603", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50432/" ]
I would like to add an extra row to the Cart Table in Woommerce, but I can't find the right action. From this file <https://github.com/woocommerce/woocommerce/blob/master/templates/cart/cart.php>, I would expect the 'woocommerce\_after\_cart\_contents' action to be the right one (line 149), but it prints the content above the cart table. Am I missing anything? Here's the code (in `functions.php`): ``` function quality_certificates(){ echo '<tr>TEST</tr>'; } add_action('woocommerce_cart_contents','quality_certificates'); ``` And this is the output: ``` <form class="woocommerce-cart-form" action="..." method="post"> TEST<table class="shop_table ..."> ``` etc.
You already have the right "action", which is `woocommerce_after_cart_contents`. But when I tried the markup you used: ``` function quality_certificates(){ echo '<tr>TEST</tr>'; } ``` this was the visual output: *(I actually initially tested with the Twenty Seventeen theme; sorry about that. But this one is tested with Storefront)* ![](https://image.ibb.co/kJJN9K/image.png) Then I started thinking that the problem *might* be the markup, so I changed it to: ``` <tr><td colspan="6">TEST</td></tr> ``` and voila! I got the expected visual output: ![](https://image.ibb.co/haKjOe/image.png) So, **use the proper markup/HTML**. =) *PS: Those are **actual** screenshots. ;-)*
315,611
<p>I've integrated wordpress to my website with the help of godaddy. I can access my blog via a sub domain. The them of this blog however is completely different to the rest of the site.</p> <p>Am I right in saying that I need the html and css of that file to match the rest of the my site? What's the easiest way of going about this? Inside the blog directory there are hundreds of files, which ones do i need to edit? </p>
[ { "answer_id": 315610, "author": "VinothRaja", "author_id": 146008, "author_profile": "https://wordpress.stackexchange.com/users/146008", "pm_score": 0, "selected": false, "text": "<p>try this below hook</p>\n\n<pre><code>function custom_cart_function(){\n\n echo 'demo';\n}\n\nadd_ac...
2018/10/01
[ "https://wordpress.stackexchange.com/questions/315611", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151573/" ]
I've integrated wordpress to my website with the help of godaddy. I can access my blog via a sub domain. The them of this blog however is completely different to the rest of the site. Am I right in saying that I need the html and css of that file to match the rest of the my site? What's the easiest way of going about this? Inside the blog directory there are hundreds of files, which ones do i need to edit?
You already have the right "action", which is `woocommerce_after_cart_contents`. But when I tried the markup you used: ``` function quality_certificates(){ echo '<tr>TEST</tr>'; } ``` this was the visual output: *(I actually initially tested with the Twenty Seventeen theme; sorry about that. But this one is tested with Storefront)* ![](https://image.ibb.co/kJJN9K/image.png) Then I started thinking that the problem *might* be the markup, so I changed it to: ``` <tr><td colspan="6">TEST</td></tr> ``` and voila! I got the expected visual output: ![](https://image.ibb.co/haKjOe/image.png) So, **use the proper markup/HTML**. =) *PS: Those are **actual** screenshots. ;-)*
315,637
<p>I have an issue in my custom theme. </p> <p>Direct media library upload saving in wrong month date folder (2017/03) when current date is 2018/09. But when I upload images through post it goes to the correct folder.</p> <p>I have tested in default theme, Direct media library upload goes to the correct folder. So the issue is in my custom theme. But I am not sure where to look at. In which file of my theme has the issue? Help is much appreciated.</p> <p>Thanks in advance.</p>
[ { "answer_id": 315610, "author": "VinothRaja", "author_id": 146008, "author_profile": "https://wordpress.stackexchange.com/users/146008", "pm_score": 0, "selected": false, "text": "<p>try this below hook</p>\n\n<pre><code>function custom_cart_function(){\n\n echo 'demo';\n}\n\nadd_ac...
2018/10/01
[ "https://wordpress.stackexchange.com/questions/315637", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116707/" ]
I have an issue in my custom theme. Direct media library upload saving in wrong month date folder (2017/03) when current date is 2018/09. But when I upload images through post it goes to the correct folder. I have tested in default theme, Direct media library upload goes to the correct folder. So the issue is in my custom theme. But I am not sure where to look at. In which file of my theme has the issue? Help is much appreciated. Thanks in advance.
You already have the right "action", which is `woocommerce_after_cart_contents`. But when I tried the markup you used: ``` function quality_certificates(){ echo '<tr>TEST</tr>'; } ``` this was the visual output: *(I actually initially tested with the Twenty Seventeen theme; sorry about that. But this one is tested with Storefront)* ![](https://image.ibb.co/kJJN9K/image.png) Then I started thinking that the problem *might* be the markup, so I changed it to: ``` <tr><td colspan="6">TEST</td></tr> ``` and voila! I got the expected visual output: ![](https://image.ibb.co/haKjOe/image.png) So, **use the proper markup/HTML**. =) *PS: Those are **actual** screenshots. ;-)*
315,669
<p>I'm working on a WordPress site for my condo association. I would like to have two email aliases:</p> <p>residents@mycondoplace.net</p> <p>board@mycondoplace.net</p> <p>that alias to all residents, and the board members respectively. Is there a WordPress plugin that would enable this functionality? Or some other service? The domain name I'm hosting my WP site on is <code>mycondoplace.net</code>.</p>
[ { "answer_id": 315610, "author": "VinothRaja", "author_id": 146008, "author_profile": "https://wordpress.stackexchange.com/users/146008", "pm_score": 0, "selected": false, "text": "<p>try this below hook</p>\n\n<pre><code>function custom_cart_function(){\n\n echo 'demo';\n}\n\nadd_ac...
2018/10/01
[ "https://wordpress.stackexchange.com/questions/315669", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151609/" ]
I'm working on a WordPress site for my condo association. I would like to have two email aliases: residents@mycondoplace.net board@mycondoplace.net that alias to all residents, and the board members respectively. Is there a WordPress plugin that would enable this functionality? Or some other service? The domain name I'm hosting my WP site on is `mycondoplace.net`.
You already have the right "action", which is `woocommerce_after_cart_contents`. But when I tried the markup you used: ``` function quality_certificates(){ echo '<tr>TEST</tr>'; } ``` this was the visual output: *(I actually initially tested with the Twenty Seventeen theme; sorry about that. But this one is tested with Storefront)* ![](https://image.ibb.co/kJJN9K/image.png) Then I started thinking that the problem *might* be the markup, so I changed it to: ``` <tr><td colspan="6">TEST</td></tr> ``` and voila! I got the expected visual output: ![](https://image.ibb.co/haKjOe/image.png) So, **use the proper markup/HTML**. =) *PS: Those are **actual** screenshots. ;-)*
315,677
<p>I'm working on a custom Gutenberg block. I have used <code>&lt;PanelBody&gt;</code> <code>&lt;BaseControl&gt;</code> and <code>&lt;ColorPalette&gt;</code> to create some custom color pickers, however, it seems like it would be more efficient to use the built-in <code>&lt;PanelColorSettings&gt;</code> component. </p> <p>Has anyone used <code>&lt;PanelColorSettings&gt;</code> component in a custom block? The only discussion of this technique I could find was here: <a href="https://stackoverflow.com/questions/50480454/add-the-inbuilt-colour-palette-for-gutenberg-custom-block">https://stackoverflow.com/questions/50480454/add-the-inbuilt-colour-palette-for-gutenberg-custom-block</a></p>
[ { "answer_id": 315692, "author": "Ashiquzzaman Kiron", "author_id": 78505, "author_profile": "https://wordpress.stackexchange.com/users/78505", "pm_score": 5, "selected": true, "text": "<p>First you need to import the component - </p>\n\n<pre><code>const {\n PanelColorSettings,\n} = w...
2018/10/01
[ "https://wordpress.stackexchange.com/questions/315677", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66722/" ]
I'm working on a custom Gutenberg block. I have used `<PanelBody>` `<BaseControl>` and `<ColorPalette>` to create some custom color pickers, however, it seems like it would be more efficient to use the built-in `<PanelColorSettings>` component. Has anyone used `<PanelColorSettings>` component in a custom block? The only discussion of this technique I could find was here: <https://stackoverflow.com/questions/50480454/add-the-inbuilt-colour-palette-for-gutenberg-custom-block>
First you need to import the component - ``` const { PanelColorSettings, } = wp.editor; ``` then inside the **InspectorControls** you call the component ``` <PanelColorSettings title={ __( 'Color Settings' ) } colorSettings={ [ { value: color, onChange: ( colorValue ) => setAttributes( { color: colorValue } ), label: __( 'Background Color' ), }, { value: textColor, onChange: ( colorValue ) => setAttributes( { textColor: colorValue } ), label: __( 'Text Color' ), }, ] } > </PanelColorSettings> ```
315,685
<p>I am trying to crop a 1000 x 648 image to 400 x 400. I use this code in functions.php</p> <pre><code>add_theme_support( 'post-thumbnails' ); add_image_size('shop-size', 400, 400, array(center,center) ); add_image_size('shop-size2', 401, 400, true ); </code></pre> <p>then i go to the regenerate plugin and run it. While I run it I open up wp-content uploads to check out what's going on.</p> <p>I watch as it creates a 400x259 image that is scaled. The regenerate plugin even says it is going to do a 400x400 cropped to fit for shop-size, and then proceeds not to.</p> <p>I checked if gd is loaded with this and it returns 'gd loaded'</p> <pre><code>&lt;?php if (extension_loaded('gd')) { echo "gd loaded"; } else { echo "not loaded"; } ?&gt; </code></pre> <p>I also tried hooking it into after_theme_setup like this:</p> <pre><code>function add_custom_sizes() { add_image_size( 'map-size', 199, 199, array('center','center') ); add_image_size('shop-size', 599, 599, array('center','center') ); add_image_size('discover-size', 749, 620, array('center','center')); add_image_size( 'map-size1', 198, 199, true ); add_image_size('shop-size1', 598, 599, true ); add_image_size('discover-size1', 748, 620, true); } add_action('after_setup_theme','add_custom_sizes'); </code></pre> <p>however as i regenerate it still makes a 198x165 instead of 198x199 (from 768 x 641)</p> <p>The parent is called 'rise' by thrive themes. I contacted them but they said they don't have support for dev questions.</p> <p>The parent only uses add_image_size once, i tried removing this but I still had the scaling instead of cropping issue.</p> <p>I've included the rise files below. I have a hunch they do some kind of custom scaling thing? And i will have to over-ride this some how?</p> <p>thrive image optimization file - <a href="https://pastebin.com/1QEa6YJv" rel="nofollow noreferrer">https://pastebin.com/1QEa6YJv</a> thrive functions - <a href="https://pastebin.com/pAqBt285" rel="nofollow noreferrer">https://pastebin.com/pAqBt285</a></p> <p>Can anyone help me figure out what i'm doing wrong? Thanks for any help.</p>
[ { "answer_id": 315692, "author": "Ashiquzzaman Kiron", "author_id": 78505, "author_profile": "https://wordpress.stackexchange.com/users/78505", "pm_score": 5, "selected": true, "text": "<p>First you need to import the component - </p>\n\n<pre><code>const {\n PanelColorSettings,\n} = w...
2018/10/02
[ "https://wordpress.stackexchange.com/questions/315685", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145464/" ]
I am trying to crop a 1000 x 648 image to 400 x 400. I use this code in functions.php ``` add_theme_support( 'post-thumbnails' ); add_image_size('shop-size', 400, 400, array(center,center) ); add_image_size('shop-size2', 401, 400, true ); ``` then i go to the regenerate plugin and run it. While I run it I open up wp-content uploads to check out what's going on. I watch as it creates a 400x259 image that is scaled. The regenerate plugin even says it is going to do a 400x400 cropped to fit for shop-size, and then proceeds not to. I checked if gd is loaded with this and it returns 'gd loaded' ``` <?php if (extension_loaded('gd')) { echo "gd loaded"; } else { echo "not loaded"; } ?> ``` I also tried hooking it into after\_theme\_setup like this: ``` function add_custom_sizes() { add_image_size( 'map-size', 199, 199, array('center','center') ); add_image_size('shop-size', 599, 599, array('center','center') ); add_image_size('discover-size', 749, 620, array('center','center')); add_image_size( 'map-size1', 198, 199, true ); add_image_size('shop-size1', 598, 599, true ); add_image_size('discover-size1', 748, 620, true); } add_action('after_setup_theme','add_custom_sizes'); ``` however as i regenerate it still makes a 198x165 instead of 198x199 (from 768 x 641) The parent is called 'rise' by thrive themes. I contacted them but they said they don't have support for dev questions. The parent only uses add\_image\_size once, i tried removing this but I still had the scaling instead of cropping issue. I've included the rise files below. I have a hunch they do some kind of custom scaling thing? And i will have to over-ride this some how? thrive image optimization file - <https://pastebin.com/1QEa6YJv> thrive functions - <https://pastebin.com/pAqBt285> Can anyone help me figure out what i'm doing wrong? Thanks for any help.
First you need to import the component - ``` const { PanelColorSettings, } = wp.editor; ``` then inside the **InspectorControls** you call the component ``` <PanelColorSettings title={ __( 'Color Settings' ) } colorSettings={ [ { value: color, onChange: ( colorValue ) => setAttributes( { color: colorValue } ), label: __( 'Background Color' ), }, { value: textColor, onChange: ( colorValue ) => setAttributes( { textColor: colorValue } ), label: __( 'Text Color' ), }, ] } > </PanelColorSettings> ```
315,702
<p>I have Menu created by wp_nav_menu. Inside it, I want to set dynamic_sidebar but wp_nav_menu instead of displaying the content, throws 1. </p> <p>Have everyone some tips for display sidebar inside wp_nav_menu? I have to add dynamic_sidebar inside menu it's important.</p> <p>Inside walker I placed the code: </p> <pre><code>$item_output .= ' &lt;div class="recipes__dropdown"&gt; &lt;div class="container"&gt; &lt;div class="dropdown__content"&gt; &lt;div class="row"&gt;' . dynamic_sidebar( 'recipes-dropdown' ) . '&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;'; </code></pre> <p>Have you any suggestions how include dynamic sidebar inside wp_nav_menu?</p>
[ { "answer_id": 315703, "author": "Pratik Patel", "author_id": 143123, "author_profile": "https://wordpress.stackexchange.com/users/143123", "pm_score": -1, "selected": true, "text": "<p>You can add extra items in menu like</p>\n\n<pre><code>add_filter( 'wp_nav_menu_items', 'your_custom_m...
2018/10/02
[ "https://wordpress.stackexchange.com/questions/315702", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151639/" ]
I have Menu created by wp\_nav\_menu. Inside it, I want to set dynamic\_sidebar but wp\_nav\_menu instead of displaying the content, throws 1. Have everyone some tips for display sidebar inside wp\_nav\_menu? I have to add dynamic\_sidebar inside menu it's important. Inside walker I placed the code: ``` $item_output .= ' <div class="recipes__dropdown"> <div class="container"> <div class="dropdown__content"> <div class="row">' . dynamic_sidebar( 'recipes-dropdown' ) . '</div> </div> </div> </div>'; ``` Have you any suggestions how include dynamic sidebar inside wp\_nav\_menu?
You can add extra items in menu like ``` add_filter( 'wp_nav_menu_items', 'your_custom_menu_item', 10, 2 ); function your_custom_menu_item ( $items, $args ) { if ($args->theme_location == '[YOUR-MENU-LOCATION]') { $items .= '--YOUR EXTRA STUFF HERE--'; } return $items; } ``` Hope it will help!
315,721
<p>Because of a project I need help from you. I've searched a lot but I can't find a solution. I'm trying to edit a WooCommerce function named</p> <ul> <li><blockquote> <p>woocommerce_account_orders</p> </blockquote></li> </ul> <hr> <p>I've added the field</p> <ul> <li><blockquote> <p>mycustom_id</p> </blockquote></li> </ul> <p>to the the orders meta-data object because I need to get all orders which has the current logged in user in the field mycustom_id:</p> <ul> <li><blockquote> <p>(mycustom_id = current_user_id())</p> </blockquote></li> </ul> <hr> <p>The check for the <code>customer</code> should stay. I just need to add this other <code>current_user_id</code> check.</p> <p>This sould stay as it is:</p> <ul> <li><blockquote> <p>'customer' => get_current_user_id()</p> </blockquote></li> </ul> <hr> <p>. This is my not working code snippet:</p> <pre><code>function woocommerce_account_orders( $current_page ) { $current_page = empty( $current_page ) ? 1 : absint( $current_page ); $customer_orders = wc_get_orders( apply_filters( 'woocommerce_my_account_my_orders_query', array( 'customer' =&gt; get_current_user_id(), 'mycustom_id' =&gt; get_current_user_id(), 'page' =&gt; $current_page, 'paginate' =&gt; true, ) ) ); wc_get_template( 'myaccount/orders.php', array( 'current_page' =&gt; absint( $current_page ), 'customer_orders' =&gt; $customer_orders, 'has_orders' =&gt; 0 &lt; $customer_orders-&gt;total, ) ); } </code></pre> <p>The method is located in: <a href="https://docs.woocommerce.com/wc-apidocs/source-function-woocommerce_account_orders.html#2465-2486" rel="nofollow noreferrer">https://docs.woocommerce.com/wc-apidocs/source-function-woocommerce_account_orders.html#2465-2486</a></p> <hr> <p>How can I add this feature to the function a smart way like a filter and how can I pass my custom parameter the right way to the function? I've saved the parameter as an order_meta attribute:</p> <pre><code>[5] =&gt; WC_Meta_Data Object ( [current_data:protected] =&gt; Array ( [id] =&gt; 3477 [key] =&gt; mycustom_id [value] =&gt; 2 ) </code></pre> <p>Thank you for your help. I've tried so much but I'm new in PHP and must lurn a lot..</p>
[ { "answer_id": 336434, "author": "Scotty G", "author_id": 166793, "author_profile": "https://wordpress.stackexchange.com/users/166793", "pm_score": 0, "selected": false, "text": "<p>You would add the <code>meta_query</code> portion to your <code>wc_get_orders()</code> as the only filter ...
2018/10/02
[ "https://wordpress.stackexchange.com/questions/315721", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151233/" ]
Because of a project I need help from you. I've searched a lot but I can't find a solution. I'm trying to edit a WooCommerce function named * > > woocommerce\_account\_orders > > > --- I've added the field * > > mycustom\_id > > > to the the orders meta-data object because I need to get all orders which has the current logged in user in the field mycustom\_id: * > > (mycustom\_id = current\_user\_id()) > > > --- The check for the `customer` should stay. I just need to add this other `current_user_id` check. This sould stay as it is: * > > 'customer' => get\_current\_user\_id() > > > --- . This is my not working code snippet: ``` function woocommerce_account_orders( $current_page ) { $current_page = empty( $current_page ) ? 1 : absint( $current_page ); $customer_orders = wc_get_orders( apply_filters( 'woocommerce_my_account_my_orders_query', array( 'customer' => get_current_user_id(), 'mycustom_id' => get_current_user_id(), 'page' => $current_page, 'paginate' => true, ) ) ); wc_get_template( 'myaccount/orders.php', array( 'current_page' => absint( $current_page ), 'customer_orders' => $customer_orders, 'has_orders' => 0 < $customer_orders->total, ) ); } ``` The method is located in: <https://docs.woocommerce.com/wc-apidocs/source-function-woocommerce_account_orders.html#2465-2486> --- How can I add this feature to the function a smart way like a filter and how can I pass my custom parameter the right way to the function? I've saved the parameter as an order\_meta attribute: ``` [5] => WC_Meta_Data Object ( [current_data:protected] => Array ( [id] => 3477 [key] => mycustom_id [value] => 2 ) ``` Thank you for your help. I've tried so much but I'm new in PHP and must lurn a lot..
I know this is very old but I would just like to share the solution. Apparently, WooCommerce is ignoring the meta\_query parameter. What you should do is something like: ``` function woocommerce_account_orders( $current_page ) { $current_page = empty( $current_page ) ? 1 : absint( $current_page ); $customer_orders = wc_get_orders( apply_filters( 'woocommerce_my_account_my_orders_query', array( 'customer' => get_current_user_id(), 'mycustom_id' => get_current_user_id(), 'page' => $current_page, 'paginate' => true, 'meta_key' => 'mycustom_id', 'meta_compare' => '=', 'meta_value' => get_current_user_id(), ) ) ); wc_get_template( 'myaccount/orders.php', array( 'current_page' => absint( $current_page ), 'customer_orders' => $customer_orders, 'has_orders' => 0 < $customer_orders->total, ) ); } ```
315,728
<p>I am having trouble adding custom column to Woocommerce Subscription.</p> <p>My codes are as below:</p> <pre><code>add_filter( 'manage_shop_subscription_posts_columns', function ($columns) { $columns['my_field'] = __('My Field'); return $columns; }, 10); </code></pre> <p>What could be wrong with my code? I fail to understand why it is not working.</p>
[ { "answer_id": 336434, "author": "Scotty G", "author_id": 166793, "author_profile": "https://wordpress.stackexchange.com/users/166793", "pm_score": 0, "selected": false, "text": "<p>You would add the <code>meta_query</code> portion to your <code>wc_get_orders()</code> as the only filter ...
2018/10/02
[ "https://wordpress.stackexchange.com/questions/315728", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48410/" ]
I am having trouble adding custom column to Woocommerce Subscription. My codes are as below: ``` add_filter( 'manage_shop_subscription_posts_columns', function ($columns) { $columns['my_field'] = __('My Field'); return $columns; }, 10); ``` What could be wrong with my code? I fail to understand why it is not working.
I know this is very old but I would just like to share the solution. Apparently, WooCommerce is ignoring the meta\_query parameter. What you should do is something like: ``` function woocommerce_account_orders( $current_page ) { $current_page = empty( $current_page ) ? 1 : absint( $current_page ); $customer_orders = wc_get_orders( apply_filters( 'woocommerce_my_account_my_orders_query', array( 'customer' => get_current_user_id(), 'mycustom_id' => get_current_user_id(), 'page' => $current_page, 'paginate' => true, 'meta_key' => 'mycustom_id', 'meta_compare' => '=', 'meta_value' => get_current_user_id(), ) ) ); wc_get_template( 'myaccount/orders.php', array( 'current_page' => absint( $current_page ), 'customer_orders' => $customer_orders, 'has_orders' => 0 < $customer_orders->total, ) ); } ```
315,773
<p>I want to redirect all subcategories who belong to the category named symptoms to a same page.</p> <p>I did this:</p> <pre><code>RewriteRule ^category/symptoms/(.*)$ https://my-site/com/list/$1 [L,R=301] </code></pre> <p>Wordpress redirects but always add the subcategory at the end. For example: <code>my-site/com/category/symptoms/fever</code> is redirected to <code>my-site/com/list/fever</code>.</p> <p>How to stop it adding the subcategory?</p>
[ { "answer_id": 315762, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 4, "selected": true, "text": "<p>WordPress only looks for the default template files while loading the child theme. So does woocommerce.</p>\...
2018/10/03
[ "https://wordpress.stackexchange.com/questions/315773", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151695/" ]
I want to redirect all subcategories who belong to the category named symptoms to a same page. I did this: ``` RewriteRule ^category/symptoms/(.*)$ https://my-site/com/list/$1 [L,R=301] ``` Wordpress redirects but always add the subcategory at the end. For example: `my-site/com/category/symptoms/fever` is redirected to `my-site/com/list/fever`. How to stop it adding the subcategory?
WordPress only looks for the default template files while loading the child theme. So does woocommerce. Any extra folder or file that exists in your parent theme **can not** be overridden, unless the developer is using actions and filters that allows you to hook into them. Therefore, a simple `require()` or `include()` can't be overridden by a child theme. What you can do is to track the template file that is calling the files from the `inc` folder, and then override those in your theme's folder. You might need to go as back as `functions.php`. For a complete list of default template files, take a look at the [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/).
315,841
<p>I have a meta field called <code>postexpiry</code>, and I want to set the value to the publish date, + 2 weeks. So if today were October 3rd, I want the field to be set to October 17th.</p> <p>I was thinking about creating a hook to the <code>publish_post</code> filter, but I am not sure how to add 2 weeks on to <code>get_the_date()</code>. </p> <p>I know with php I can do something like this <code>$dateInTwoWeeks = strtotime('+2 weeks');</code> but I'm not sure how to use that with <code>get_the_date()</code></p> <p>Thanks!</p> <p><strong>UPDATE</strong></p> <p>I tried the following code, but it didn't do anything:</p> <pre><code>function dp_expiry() { $dp_new_expiry_date = strtotime( '+2 weeks', strtotime( $post-&gt;post_date ) ); update_post_meta( get_the_ID(), 'postexpiry', $dp_new_expiry_date ); } add_action( 'publish_post', 'dp_expiry' ); </code></pre> <p><strong>Also</strong>, my theme requires that the date be in <code>yyyy-mm-dd</code> format.</p> <p><strong>UPDATE 2</strong></p> <p>This code outputs "1209600" to the field. Any ideas? Thanks!</p> <pre><code>add_action('publish_post', 'dp_expiry'); function dp_expiry( $data ) { $dp_new_expiry_date = strtotime( '+2 weeks', strtotime( $post-&gt;post_date ) ); update_post_meta( $data['post_id'], 'postexpiry', $dp_new_expiry_date ); } </code></pre>
[ { "answer_id": 315798, "author": "Prem Gupta", "author_id": 151576, "author_profile": "https://wordpress.stackexchange.com/users/151576", "pm_score": -1, "selected": false, "text": "<p>Child theme is a WordPress theme that inherits its functionality from another WordPress theme, the pare...
2018/10/03
[ "https://wordpress.stackexchange.com/questions/315841", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151735/" ]
I have a meta field called `postexpiry`, and I want to set the value to the publish date, + 2 weeks. So if today were October 3rd, I want the field to be set to October 17th. I was thinking about creating a hook to the `publish_post` filter, but I am not sure how to add 2 weeks on to `get_the_date()`. I know with php I can do something like this `$dateInTwoWeeks = strtotime('+2 weeks');` but I'm not sure how to use that with `get_the_date()` Thanks! **UPDATE** I tried the following code, but it didn't do anything: ``` function dp_expiry() { $dp_new_expiry_date = strtotime( '+2 weeks', strtotime( $post->post_date ) ); update_post_meta( get_the_ID(), 'postexpiry', $dp_new_expiry_date ); } add_action( 'publish_post', 'dp_expiry' ); ``` **Also**, my theme requires that the date be in `yyyy-mm-dd` format. **UPDATE 2** This code outputs "1209600" to the field. Any ideas? Thanks! ``` add_action('publish_post', 'dp_expiry'); function dp_expiry( $data ) { $dp_new_expiry_date = strtotime( '+2 weeks', strtotime( $post->post_date ) ); update_post_meta( $data['post_id'], 'postexpiry', $dp_new_expiry_date ); } ```
hopefully I'm understanding correctly, if not, please explain. Usually, with a child theme, it's inheriting the functionality of the parent theme, so that means you should be able to use the parent theme's page builder. I would copy the extra lines of css you added into an external file for safekeeping, as, with some themes, they will sometimes be lost when you change to a child theme. The child theme would just be used to code additional styles or change page styles without touching the actual code files in the parent theme. If you're only going to use the admin interface, and not code anything, you probably don't need a child theme. If you want to change the layout via changing the html/php/js involved in the templates, then you'll want to add a child theme, copy the files you want to change into the child theme and edit them there, then the system will pull from them there. Make a little more sense?
315,843
<p>I want to get all products of category by category name (slug). Сategory has no parents or children. I wrote my code according to <a href="https://wordpress.stackexchange.com/a/67266/86327">this answer</a>. My code:</p> <pre><code>&lt;?php $args = [ 'post_type' =&gt; 'product', 'posts_per_page' =&gt; -1, 'product_cat' =&gt; 'pyvo-v-pliashkah' ]; $products = new WP_Query($args); wp_reset_query(); echo "&lt;pre&gt;"; print_r($products-&gt;posts); ?&gt; </code></pre> <p>But instead products of "pyvo-v-plyashkah" category I get all products of all categoryes. Where is my mistake?</p>
[ { "answer_id": 315798, "author": "Prem Gupta", "author_id": 151576, "author_profile": "https://wordpress.stackexchange.com/users/151576", "pm_score": -1, "selected": false, "text": "<p>Child theme is a WordPress theme that inherits its functionality from another WordPress theme, the pare...
2018/10/03
[ "https://wordpress.stackexchange.com/questions/315843", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86327/" ]
I want to get all products of category by category name (slug). Сategory has no parents or children. I wrote my code according to [this answer](https://wordpress.stackexchange.com/a/67266/86327). My code: ``` <?php $args = [ 'post_type' => 'product', 'posts_per_page' => -1, 'product_cat' => 'pyvo-v-pliashkah' ]; $products = new WP_Query($args); wp_reset_query(); echo "<pre>"; print_r($products->posts); ?> ``` But instead products of "pyvo-v-plyashkah" category I get all products of all categoryes. Where is my mistake?
hopefully I'm understanding correctly, if not, please explain. Usually, with a child theme, it's inheriting the functionality of the parent theme, so that means you should be able to use the parent theme's page builder. I would copy the extra lines of css you added into an external file for safekeeping, as, with some themes, they will sometimes be lost when you change to a child theme. The child theme would just be used to code additional styles or change page styles without touching the actual code files in the parent theme. If you're only going to use the admin interface, and not code anything, you probably don't need a child theme. If you want to change the layout via changing the html/php/js involved in the templates, then you'll want to add a child theme, copy the files you want to change into the child theme and edit them there, then the system will pull from them there. Make a little more sense?
315,850
<p>I'm trying to display the last 10 posts only on the home without wp creating /page/2, /page/3, archives.</p> <p>I've been testing and it seems if you disable pagination it will just grab everything crashing the server. (Don't do this at home).</p> <pre><code>if ( !is_admin() &amp;&amp; $query-&gt;is_home() &amp;&amp; $query-&gt;is_main_query() ) { $query-&gt;set( 'posts_per_page', 10 ); $query-&gt;set( 'nopaging' , true ); } </code></pre> <p>Someone suggested " no_found_rows=true" that doesn't do it either.</p> <p>Is this just impossible to do? It seems like it will either create the pages or show all, there's no way to "LIMIT" it?</p>
[ { "answer_id": 315851, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The <code>nopaging</code> parameter is used to show all posts or use pagination (<a href=\"https://codex.wordpres...
2018/10/03
[ "https://wordpress.stackexchange.com/questions/315850", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77283/" ]
I'm trying to display the last 10 posts only on the home without wp creating /page/2, /page/3, archives. I've been testing and it seems if you disable pagination it will just grab everything crashing the server. (Don't do this at home). ``` if ( !is_admin() && $query->is_home() && $query->is_main_query() ) { $query->set( 'posts_per_page', 10 ); $query->set( 'nopaging' , true ); } ``` Someone suggested " no\_found\_rows=true" that doesn't do it either. Is this just impossible to do? It seems like it will either create the pages or show all, there's no way to "LIMIT" it?
This is a mistake it will retrieve of posts: ``` $query->set( 'nopaging' , true ); ``` What you should do instead is: ``` if ( !is_admin() && $query->is_home() && $query->is_main_query() ) { $query->set( 'posts_per_page', 10 ); $query->set( 'paged', '1'); // Makes /page/2/, etc links redirect to home $query->set( 'no_found_rows', true ); // Avoid counting rows, faster processing. } ``` If your theme is still rendering the navigation buttons you'll have to add some logic to hide them on the pages you disabled pagination, for me it was the home page: ``` if (!is_home()) { // show pagination buttons } ```
315,881
<p>when tried to upload a theme,got this error.</p> <p>how can i solve this? Installing Theme from uploaded file: resume.zip Unpacking the package…</p> <p>Installing the theme…<br></p> <p>The package could not be installed. The theme is missing the style.css stylesheet.</p> <p>can i know why this issue happened?</p> <blockquote> <p>Theme installation failed.</p> </blockquote>
[ { "answer_id": 315882, "author": "Remzi Cavdar", "author_id": 149484, "author_profile": "https://wordpress.stackexchange.com/users/149484", "pm_score": 1, "selected": false, "text": "<p>The theme package is missing an important theme file (<strong>style.css</strong>), which is required.\...
2018/10/04
[ "https://wordpress.stackexchange.com/questions/315881", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148447/" ]
when tried to upload a theme,got this error. how can i solve this? Installing Theme from uploaded file: resume.zip Unpacking the package… Installing the theme… The package could not be installed. The theme is missing the style.css stylesheet. can i know why this issue happened? > > Theme installation failed. > > >
The key part from the error is: > > The theme is missing the style.css stylesheet. > > > WordPress docs on [Main Stylesheet](https://developer.wordpress.org/themes/basics/main-stylesheet-style-css/) says: > > In order for WordPress to recognize the set of theme template files as a valid theme, the style.css file needs to be located in the root directory of your theme, not a subdirectory. > > > I would suggest you to unzip the theme and look for `style.css`. If the file is there open it; there should be some commented lines that will look similar to these: ``` /* Theme Name: Twenty Seventeen Theme URI: https://wordpress.org/themes/twentyseventeen/ Author: the WordPress team Author URI: https://wordpress.org/ Description: Twenty Seventeen brings your site to life with immersive featured images and subtle animations. With a focus on business sites, it features multiple sections on the front page as well as widgets, navigation and social menus, a logo, and more. Personalize its asymmetrical grid with a custom color scheme and showcase your multimedia content with post formats. Our default theme for 2017 works great in many languages, for any abilities, and on any device. Version: 1.0 License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Text Domain: twentyseventeen Tags: one-column, two-columns, right-sidebar, flexible-header, accessibility-ready, custom-colors, custom-header, custom-menu, custom-logo, editor-style, featured-images, footer-widgets, post-formats, rtl-language-support, sticky-post, theme-options, threaded-comments, translation-ready This theme, like WordPress, is licensed under the GPL. Use it to make something cool, have fun, and share what you've learned with others. */ ``` The following fields should be in every main stylesheet: `Theme Name`, `Author`, `Description`, `Version`, `License`, `License URI` and `Text Domain`. If any of the mentioned fields are missing I strongly recommend contacting the theme provider. If you're the owner or the author of the theme make sure to include the mentioned lines and to include the `style.css` file in the root directory of the theme before uploading the archived theme to your WordPress installation. Also, make sure to read more on Main Stylesheets here: <https://developer.wordpress.org/themes/basics/main-stylesheet-style-css/>
315,947
<p>I'm trying to set up an SMTP gmail server to send emails from my WordPress site. This is what I've got in my <code>wp-config.php</code>: </p> <pre><code>define( 'SMTP_USER', 'myaddress@gmail.com' ); // Username to use for SMTP authentication define( 'SMTP_PASS', 'password' ); // Password to use for SMTP authentication define( 'SMTP_HOST', 'smtp.gmail.com' ); // The hostname of the mail server define( 'SMTP_FROM', 'myaddress@gmail.com' ); // SMTP From email address define( 'SMTP_NAME', 'My Site Name' ); // SMTP From name define( 'SMTP_PORT', '465' ); // SMTP port number - likely to be 25, 465 or 587 define( 'SMTP_SECURE', 'tls' ); // Encryption system to use - ssl or tls define( 'SMTP_AUTH', true ); // Use SMTP authentication (true|false) define( 'SMTP_DEBUG', 1 ); // for debugging purposes only set to 1 or 2 </code></pre> <p>I put this in my theme's <code>functions.php</code> file:</p> <pre><code>add_action( 'phpmailer_init', 'send_smtp_email' ); function send_smtp_email( $phpmailer ) { $phpmailer-&gt;isSMTP(); $phpmailer-&gt;Host = SMTP_HOST; $phpmailer-&gt;SMTPAuth = SMTP_AUTH; $phpmailer-&gt;Port = SMTP_PORT; $phpmailer-&gt;Username = SMTP_USER; $phpmailer-&gt;Password = SMTP_PASS; $phpmailer-&gt;SMTPSecure = SMTP_SECURE; $phpmailer-&gt;From = SMTP_FROM; $phpmailer-&gt;FromName = SMTP_NAME; } </code></pre> <p>I'm calling <code>wp_mail()</code> in a function like so:</p> <pre><code> function invite_others() { $team_name = $_GET['team_name']; $user_id = get_current_user_id(); $user = get_userdata($user_id); $site = get_site_url(); $message = "blah blah blah"; $subject = "blah"; $admin_email = get_option('admin_email'); foreach($_POST as $name =&gt; $email) { if($email != $_POST['invite_others']){ $headers = "From: ". $admin_email . "\r\n" . "Reply-To: " . $email . "\r\n"; $sent = wp_mail($email, $subject, strip_tags($message), $headers); } } } </code></pre> <p>I get the following error from <code>wp_mail()</code>: </p> <blockquote> <p>SMTP Error: Could not connect to SMTP host</p> </blockquote> <p>Any help would be appreciated! Thanks</p>
[ { "answer_id": 317636, "author": "Friss", "author_id": 62392, "author_profile": "https://wordpress.stackexchange.com/users/62392", "pm_score": 0, "selected": false, "text": "<p>Did you try to check in your Google account the option \"access for less secure app\"?\nAllow it and retry it, ...
2018/10/05
[ "https://wordpress.stackexchange.com/questions/315947", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147485/" ]
I'm trying to set up an SMTP gmail server to send emails from my WordPress site. This is what I've got in my `wp-config.php`: ``` define( 'SMTP_USER', 'myaddress@gmail.com' ); // Username to use for SMTP authentication define( 'SMTP_PASS', 'password' ); // Password to use for SMTP authentication define( 'SMTP_HOST', 'smtp.gmail.com' ); // The hostname of the mail server define( 'SMTP_FROM', 'myaddress@gmail.com' ); // SMTP From email address define( 'SMTP_NAME', 'My Site Name' ); // SMTP From name define( 'SMTP_PORT', '465' ); // SMTP port number - likely to be 25, 465 or 587 define( 'SMTP_SECURE', 'tls' ); // Encryption system to use - ssl or tls define( 'SMTP_AUTH', true ); // Use SMTP authentication (true|false) define( 'SMTP_DEBUG', 1 ); // for debugging purposes only set to 1 or 2 ``` I put this in my theme's `functions.php` file: ``` add_action( 'phpmailer_init', 'send_smtp_email' ); function send_smtp_email( $phpmailer ) { $phpmailer->isSMTP(); $phpmailer->Host = SMTP_HOST; $phpmailer->SMTPAuth = SMTP_AUTH; $phpmailer->Port = SMTP_PORT; $phpmailer->Username = SMTP_USER; $phpmailer->Password = SMTP_PASS; $phpmailer->SMTPSecure = SMTP_SECURE; $phpmailer->From = SMTP_FROM; $phpmailer->FromName = SMTP_NAME; } ``` I'm calling `wp_mail()` in a function like so: ``` function invite_others() { $team_name = $_GET['team_name']; $user_id = get_current_user_id(); $user = get_userdata($user_id); $site = get_site_url(); $message = "blah blah blah"; $subject = "blah"; $admin_email = get_option('admin_email'); foreach($_POST as $name => $email) { if($email != $_POST['invite_others']){ $headers = "From: ". $admin_email . "\r\n" . "Reply-To: " . $email . "\r\n"; $sent = wp_mail($email, $subject, strip_tags($message), $headers); } } } ``` I get the following error from `wp_mail()`: > > SMTP Error: Could not connect to SMTP host > > > Any help would be appreciated! Thanks
Quite likely you're using the wrong encryption/port combination. You are using port 465 for tls. Port 465 should be used for SSL Port 587 should be used for TLS
316,050
<p>I've overwritten WooCommerce's <code>review-order.php</code> to change the checkout a little bit. Now everytime I add something to the hook <code>woocommerce_review_order_after_order_total</code> the contents get displayed twice and before the whole block and NOT AFTER the order total:</p> <pre><code>function output_payment_button() { $order_button_text = apply_filters( 'woocommerce_order_button_text', __( 'Place order', 'woocommerce' ) ); echo '&lt;input type="submit" class="button alt" name="woocommerce_checkout_place_order" id="place_order" value="' . esc_attr( $order_button_text ) . '" data-value="' . esc_attr( $order_button_text ) . '" /&gt;'; } add_action( 'woocommerce_review_order_after_order_total', 'output_payment_button' ); </code></pre> <p>Also adding a simple <code>&lt;?php echo("Hello World"); ?&gt;</code> to the end of <code>review-order.php</code> makes it appear twice. Can someone explain to me what I am doing wrong?</p>
[ { "answer_id": 316062, "author": "Antonio", "author_id": 78763, "author_profile": "https://wordpress.stackexchange.com/users/78763", "pm_score": 0, "selected": false, "text": "<p>Probably if you check again the file <code>review-order.php</code> you will see that you replace the hook <co...
2018/10/06
[ "https://wordpress.stackexchange.com/questions/316050", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149002/" ]
I've overwritten WooCommerce's `review-order.php` to change the checkout a little bit. Now everytime I add something to the hook `woocommerce_review_order_after_order_total` the contents get displayed twice and before the whole block and NOT AFTER the order total: ``` function output_payment_button() { $order_button_text = apply_filters( 'woocommerce_order_button_text', __( 'Place order', 'woocommerce' ) ); echo '<input type="submit" class="button alt" name="woocommerce_checkout_place_order" id="place_order" value="' . esc_attr( $order_button_text ) . '" data-value="' . esc_attr( $order_button_text ) . '" />'; } add_action( 'woocommerce_review_order_after_order_total', 'output_payment_button' ); ``` Also adding a simple `<?php echo("Hello World"); ?>` to the end of `review-order.php` makes it appear twice. Can someone explain to me what I am doing wrong?
In case it helps anyone, the do\_action('woocommerce\_review\_order\_after\_order\_total') is called in the middle of a table in the template and expects a table row to be echoed by the add\_action hook. If you just echo text or, as in the question, an input, it falls outside the table, appears before not after the table and presumably gets left behind on ajax updates so appears more than once. So, something like the following will work in the add\_action hook (the table has 2 columns): ``` echo '<tr><td colspan="2">My after totals text</td></tr>'; ```
316,123
<p>I have a home/static page with login button. Currently I've set the button url as "<a href="http://example.com/login" rel="nofollow noreferrer">http://example.com/login</a>"</p> <p>How can I set the login button to redirect to a specific page IF/WHEN the user is logged in?</p> <p>I do not know much about coding. I found some solution about add_action or something and added to theme's function.php. But I can't get it work.</p> <p>Summary: if non-login user: login button url ---> login page if login user: login button url ---> specific page</p>
[ { "answer_id": 316125, "author": "Vinit Soni", "author_id": 151006, "author_profile": "https://wordpress.stackexchange.com/users/151006", "pm_score": 0, "selected": false, "text": "<p>Okay so you are asking if user logged in then redirect to other pages or something like this. It's WordP...
2018/10/08
[ "https://wordpress.stackexchange.com/questions/316123", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151961/" ]
I have a home/static page with login button. Currently I've set the button url as "<http://example.com/login>" How can I set the login button to redirect to a specific page IF/WHEN the user is logged in? I do not know much about coding. I found some solution about add\_action or something and added to theme's function.php. But I can't get it work. Summary: if non-login user: login button url ---> login page if login user: login button url ---> specific page
Add below code in your **functions.php** file of active theme directory in order to restrict the login page to logged-in users and redirect them to core user page (user profile). You can replace **"um\_get\_core\_page( 'user' )"** with any page URL where you want to redirect logged-in users. ``` /* Restrict Login page to logged-in users and redirect to core user page (user profile) */ add_action( 'template_redirect', 'um_restrict_login_page_logged_in' ); function um_restrict_login_page_logged_in() { if ( um_is_core_page('login') && is_user_logged_in() ) { wp_redirect( um_get_core_page( 'user' ) ); exit; } } ``` Hope this works!!
316,126
<p>i use the following code in my functions php to reach a download after contact form 7 submission. but it is not working</p> <pre><code>//contact form 7 Download white paper// add_action( 'wp_footer', 'redirect_cf7' ); function redirect_cf7() { ?&gt; &lt;script type="text/javascript"&gt; document.addEventListener( 'wpcf7mailsent', function( event ) { if ( '4265' == event.detail.contactFormId ) { // Sends sumissions on form 4265 to the first thank you page location = '/wp/wp- content/uploads/2018/06/file.pdf'; } else if ( '4266' == event.detail.contactFormId ) { // Sends submissions on form 1070 to the second thank you page location = '/wp/wp- content/uploads/2018/06/file2.pdf'; } else { //do nothing } }, false ); &lt;/script&gt; &lt;?php } </code></pre> <p>You have any ideas why it does not work?</p> <p>best regards</p>
[ { "answer_id": 316131, "author": "Karun", "author_id": 63470, "author_profile": "https://wordpress.stackexchange.com/users/63470", "pm_score": 1, "selected": false, "text": "<p>Try the following and replace [DOMAIN] by your own domain.</p>\n\n<pre><code>//contact form 7 Download white pa...
2018/10/08
[ "https://wordpress.stackexchange.com/questions/316126", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82174/" ]
i use the following code in my functions php to reach a download after contact form 7 submission. but it is not working ``` //contact form 7 Download white paper// add_action( 'wp_footer', 'redirect_cf7' ); function redirect_cf7() { ?> <script type="text/javascript"> document.addEventListener( 'wpcf7mailsent', function( event ) { if ( '4265' == event.detail.contactFormId ) { // Sends sumissions on form 4265 to the first thank you page location = '/wp/wp- content/uploads/2018/06/file.pdf'; } else if ( '4266' == event.detail.contactFormId ) { // Sends submissions on form 1070 to the second thank you page location = '/wp/wp- content/uploads/2018/06/file2.pdf'; } else { //do nothing } }, false ); </script> <?php } ``` You have any ideas why it does not work? best regards
Try the following and replace [DOMAIN] by your own domain. ``` //contact form 7 Download white paper// add_action( 'wp_footer', 'redirect_cf7' ); function redirect_cf7() { ?> <script type="text/javascript"> document.addEventListener( 'wpcf7mailsent', function( event ) { if ( '4265' == event.detail.contactFormId ) { // Sends sumissions on form 4265 to the first thank you page var pdfLink = '[DOMAIN]/wp/wp-content/uploads/2018/06/file.pdf'; } else if ( '4266' == event.detail.contactFormId ) { // Sends submissions on form 1070 to the second thank you page var pdfLink = '[DOMAIN]/wp/wp-content/uploads/2018/06/file2.pdf'; } else { //do nothing } jQuery.get(pdfLink, (data) -> window.location.href = jQuery(this).attr('href'); ) }, false ); </script> <?php } ```
316,187
<p>Having successfully uploaded an SVG image through WordPress's back-end media uploader with the help of a third party plugin such as Safe SVG by Daryll Doyle, how can one get the image's dimensions that are stored in the SVG file's <code>width</code>, <code>height</code>, or <code>viewBox</code> attributes to use in front-end with WordPress functions such as <code>wp_get_attachment_image_src()</code> ?</p> <p>Unlike other types of images such as PNG and JPEG, WordPress does not store SVG image's dimensions into its system.</p> <p>Here's a regular PNG: <a href="https://i.stack.imgur.com/xZARi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xZARi.jpg" alt="enter image description here"></a></p> <p>And here's an SVG image: <a href="https://i.stack.imgur.com/iwAwQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iwAwQ.jpg" alt="enter image description here"></a></p> <p>Maybe there's some kind of hook we could use in theme's <code>functions.php</code> that fires whenever you upload a file through WordPress's back-end in order to acquire those dimensions and write them directly into the database for that attachment?</p> <p>Thanks!</p>
[ { "answer_id": 316270, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": 2, "selected": false, "text": "<p>I agree with Tom J Nowell on the use of SVG, but if the upload is an actual image, you can tap into the attach...
2018/10/08
[ "https://wordpress.stackexchange.com/questions/316187", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/140129/" ]
Having successfully uploaded an SVG image through WordPress's back-end media uploader with the help of a third party plugin such as Safe SVG by Daryll Doyle, how can one get the image's dimensions that are stored in the SVG file's `width`, `height`, or `viewBox` attributes to use in front-end with WordPress functions such as `wp_get_attachment_image_src()` ? Unlike other types of images such as PNG and JPEG, WordPress does not store SVG image's dimensions into its system. Here's a regular PNG: [![enter image description here](https://i.stack.imgur.com/xZARi.jpg)](https://i.stack.imgur.com/xZARi.jpg) And here's an SVG image: [![enter image description here](https://i.stack.imgur.com/iwAwQ.jpg)](https://i.stack.imgur.com/iwAwQ.jpg) Maybe there's some kind of hook we could use in theme's `functions.php` that fires whenever you upload a file through WordPress's back-end in order to acquire those dimensions and write them directly into the database for that attachment? Thanks!
I agree with Tom J Nowell on the use of SVG, but if the upload is an actual image, you can tap into the attachment attributes using, as you suggested, wp\_get\_attachment\_image\_src. Those dimensions are actually already recorded and stored when using the WP media uploader, it's likely that the plugin you're using makes use of the WP media uploader. There are four attributes stored (0=URL,1=Width,2=Height,3=is\_intermediate) if the attachment is an image, false if it's not an image. So you can call and echo those attributes like in this example: ``` $img_atts = wp_get_attachment_image_src(get_post_thumbnail_id( $post->ID ), 'medium'); $img_src = $img_atts[0]; ``` I use this to echo an image's dimensions (atts 1 & 2) to create per-post OG tags for og:image:width and og:image:height (along with other OG tags). You can find more info here: <https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/>
316,195
<p>I've done a bunch of searching but can't seem to find a hack to do this, all I can find is how to remove the website field from the form. I want to leave it there, but if someone enters a url into the website field and tries to post a comment, it will automatically be rejected.</p>
[ { "answer_id": 316270, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": 2, "selected": false, "text": "<p>I agree with Tom J Nowell on the use of SVG, but if the upload is an actual image, you can tap into the attach...
2018/10/08
[ "https://wordpress.stackexchange.com/questions/316195", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152013/" ]
I've done a bunch of searching but can't seem to find a hack to do this, all I can find is how to remove the website field from the form. I want to leave it there, but if someone enters a url into the website field and tries to post a comment, it will automatically be rejected.
I agree with Tom J Nowell on the use of SVG, but if the upload is an actual image, you can tap into the attachment attributes using, as you suggested, wp\_get\_attachment\_image\_src. Those dimensions are actually already recorded and stored when using the WP media uploader, it's likely that the plugin you're using makes use of the WP media uploader. There are four attributes stored (0=URL,1=Width,2=Height,3=is\_intermediate) if the attachment is an image, false if it's not an image. So you can call and echo those attributes like in this example: ``` $img_atts = wp_get_attachment_image_src(get_post_thumbnail_id( $post->ID ), 'medium'); $img_src = $img_atts[0]; ``` I use this to echo an image's dimensions (atts 1 & 2) to create per-post OG tags for og:image:width and og:image:height (along with other OG tags). You can find more info here: <https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/>
316,282
<p>I am developing a new plugins, I added a new admin page menu with:</p> <pre><code>function ca_admin_link() { add_menu_page( 'Checklist Artistas', 'Checklist Artistas', 'checklist-artistas/includes/ca-checklist-acp-page.php' ); } add_action( 'admin_menu', 'ca_admin_link' ); </code></pre> <p>Everything ok, an item menu is shown and I can access to ca-checklist-acp-page.php but en this page I want to link to another page (ca-edit-checklist-acp-page.php) into same directory.</p> <p>Using</p> <pre><code>admin_url('admin.php?page=checklist-artistas/includes/ca_edit_checklist_acp-page.php') </code></pre> <p>but when I try to access to that new page I get "You do not have permission to access to this page"</p> <p>How to give admin permissions to ca_edit_checklist_acp-page.php?</p> <p>Thank you</p>
[ { "answer_id": 316270, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": 2, "selected": false, "text": "<p>I agree with Tom J Nowell on the use of SVG, but if the upload is an actual image, you can tap into the attach...
2018/10/09
[ "https://wordpress.stackexchange.com/questions/316282", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152047/" ]
I am developing a new plugins, I added a new admin page menu with: ``` function ca_admin_link() { add_menu_page( 'Checklist Artistas', 'Checklist Artistas', 'checklist-artistas/includes/ca-checklist-acp-page.php' ); } add_action( 'admin_menu', 'ca_admin_link' ); ``` Everything ok, an item menu is shown and I can access to ca-checklist-acp-page.php but en this page I want to link to another page (ca-edit-checklist-acp-page.php) into same directory. Using ``` admin_url('admin.php?page=checklist-artistas/includes/ca_edit_checklist_acp-page.php') ``` but when I try to access to that new page I get "You do not have permission to access to this page" How to give admin permissions to ca\_edit\_checklist\_acp-page.php? Thank you
I agree with Tom J Nowell on the use of SVG, but if the upload is an actual image, you can tap into the attachment attributes using, as you suggested, wp\_get\_attachment\_image\_src. Those dimensions are actually already recorded and stored when using the WP media uploader, it's likely that the plugin you're using makes use of the WP media uploader. There are four attributes stored (0=URL,1=Width,2=Height,3=is\_intermediate) if the attachment is an image, false if it's not an image. So you can call and echo those attributes like in this example: ``` $img_atts = wp_get_attachment_image_src(get_post_thumbnail_id( $post->ID ), 'medium'); $img_src = $img_atts[0]; ``` I use this to echo an image's dimensions (atts 1 & 2) to create per-post OG tags for og:image:width and og:image:height (along with other OG tags). You can find more info here: <https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/>
316,344
<p>I recently moved my new multisites network (which worked perfectly fine on an old domain) to my new domain. Now the website doesnt seem to work. The homepage doesnt load all images and even the menu isnt being loaded. Even after search and replacing my entire database and removing all the old url instances didnt work. I tried turning the wordpress debug-mode on. But no errors are displayed. When I check my console this is what I see:</p> <p><a href="https://i.stack.imgur.com/OGZn3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OGZn3.png" alt="enter image description here"></a></p> <p>Besides this there is another issue. My dashboard page isn't loading it's CSS. This is what it looks like at the moment : <a href="https://i.stack.imgur.com/wH9sa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wH9sa.png" alt="enter image description here"></a></p> <p>I tried to do the same and check if any errors were logged to the console, but in this case no errors are being logged. Has anyone ever had this situation ? I've moved many websites to new domains but I never had a situation like this before. I ran out of ideas, I hope someone has a solution. </p> <p>Thanks in advance. </p>
[ { "answer_id": 316270, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": 2, "selected": false, "text": "<p>I agree with Tom J Nowell on the use of SVG, but if the upload is an actual image, you can tap into the attach...
2018/10/10
[ "https://wordpress.stackexchange.com/questions/316344", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146426/" ]
I recently moved my new multisites network (which worked perfectly fine on an old domain) to my new domain. Now the website doesnt seem to work. The homepage doesnt load all images and even the menu isnt being loaded. Even after search and replacing my entire database and removing all the old url instances didnt work. I tried turning the wordpress debug-mode on. But no errors are displayed. When I check my console this is what I see: [![enter image description here](https://i.stack.imgur.com/OGZn3.png)](https://i.stack.imgur.com/OGZn3.png) Besides this there is another issue. My dashboard page isn't loading it's CSS. This is what it looks like at the moment : [![enter image description here](https://i.stack.imgur.com/wH9sa.png)](https://i.stack.imgur.com/wH9sa.png) I tried to do the same and check if any errors were logged to the console, but in this case no errors are being logged. Has anyone ever had this situation ? I've moved many websites to new domains but I never had a situation like this before. I ran out of ideas, I hope someone has a solution. Thanks in advance.
I agree with Tom J Nowell on the use of SVG, but if the upload is an actual image, you can tap into the attachment attributes using, as you suggested, wp\_get\_attachment\_image\_src. Those dimensions are actually already recorded and stored when using the WP media uploader, it's likely that the plugin you're using makes use of the WP media uploader. There are four attributes stored (0=URL,1=Width,2=Height,3=is\_intermediate) if the attachment is an image, false if it's not an image. So you can call and echo those attributes like in this example: ``` $img_atts = wp_get_attachment_image_src(get_post_thumbnail_id( $post->ID ), 'medium'); $img_src = $img_atts[0]; ``` I use this to echo an image's dimensions (atts 1 & 2) to create per-post OG tags for og:image:width and og:image:height (along with other OG tags). You can find more info here: <https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/>
316,372
<p>I'm using the X-Theme in Wordpress and I ran into an issue where I needed a CSS class in the <code>&lt;html&gt;</code> tag, but only on one page. This is the code I added into my child theme header file:</p> <pre><code>&lt;!-- If page#=103, add this class --&gt; &lt;?php if( is_page( 103 ) ) { ?&gt; &lt;html class="html-homepage"&gt; &lt;?php } ?&gt; </code></pre> <p>The code went into the _header.php file and appears to be working with no issues.</p> <p>My question is wondering if this method will break anything or if this is a super hacky way of doing this? I was unable to find a different solution that worked for me.</p> <p>It looks like since Wordpress is doing the processing, it should be fine, but I wanted to make sure that this won't interfere with other Wordpress functionality.</p> <p>Thanks!</p> <p><strong>Edit:</strong> The code I added is in the child theme files, not the Wordpress core files.</p>
[ { "answer_id": 316270, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": 2, "selected": false, "text": "<p>I agree with Tom J Nowell on the use of SVG, but if the upload is an actual image, you can tap into the attach...
2018/10/10
[ "https://wordpress.stackexchange.com/questions/316372", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152116/" ]
I'm using the X-Theme in Wordpress and I ran into an issue where I needed a CSS class in the `<html>` tag, but only on one page. This is the code I added into my child theme header file: ``` <!-- If page#=103, add this class --> <?php if( is_page( 103 ) ) { ?> <html class="html-homepage"> <?php } ?> ``` The code went into the \_header.php file and appears to be working with no issues. My question is wondering if this method will break anything or if this is a super hacky way of doing this? I was unable to find a different solution that worked for me. It looks like since Wordpress is doing the processing, it should be fine, but I wanted to make sure that this won't interfere with other Wordpress functionality. Thanks! **Edit:** The code I added is in the child theme files, not the Wordpress core files.
I agree with Tom J Nowell on the use of SVG, but if the upload is an actual image, you can tap into the attachment attributes using, as you suggested, wp\_get\_attachment\_image\_src. Those dimensions are actually already recorded and stored when using the WP media uploader, it's likely that the plugin you're using makes use of the WP media uploader. There are four attributes stored (0=URL,1=Width,2=Height,3=is\_intermediate) if the attachment is an image, false if it's not an image. So you can call and echo those attributes like in this example: ``` $img_atts = wp_get_attachment_image_src(get_post_thumbnail_id( $post->ID ), 'medium'); $img_src = $img_atts[0]; ``` I use this to echo an image's dimensions (atts 1 & 2) to create per-post OG tags for og:image:width and og:image:height (along with other OG tags). You can find more info here: <https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/>
316,382
<p>What is the correct process to make your jumbotron image dynamic (user changeable) via the WordPress customizer. Currently on my customers custom theme www.windupgram.co.uk I am using a static image, which I have to change when required. </p> <p>I would like to give the client an option to change the image whenever they want.</p> <p>Many thanks</p> <p>Andy</p>
[ { "answer_id": 316270, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": 2, "selected": false, "text": "<p>I agree with Tom J Nowell on the use of SVG, but if the upload is an actual image, you can tap into the attach...
2018/10/10
[ "https://wordpress.stackexchange.com/questions/316382", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125815/" ]
What is the correct process to make your jumbotron image dynamic (user changeable) via the WordPress customizer. Currently on my customers custom theme www.windupgram.co.uk I am using a static image, which I have to change when required. I would like to give the client an option to change the image whenever they want. Many thanks Andy
I agree with Tom J Nowell on the use of SVG, but if the upload is an actual image, you can tap into the attachment attributes using, as you suggested, wp\_get\_attachment\_image\_src. Those dimensions are actually already recorded and stored when using the WP media uploader, it's likely that the plugin you're using makes use of the WP media uploader. There are four attributes stored (0=URL,1=Width,2=Height,3=is\_intermediate) if the attachment is an image, false if it's not an image. So you can call and echo those attributes like in this example: ``` $img_atts = wp_get_attachment_image_src(get_post_thumbnail_id( $post->ID ), 'medium'); $img_src = $img_atts[0]; ``` I use this to echo an image's dimensions (atts 1 & 2) to create per-post OG tags for og:image:width and og:image:height (along with other OG tags). You can find more info here: <https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/>
316,387
<p>I want to upload an image and attach to it a category. This is my code:</p> <pre><code>function upload_cover(WP_REST_Request $request) { require_once( ABSPATH . 'wp-admin/includes/image.php' ); require_once( ABSPATH . 'wp-admin/includes/file.php' ); require_once( ABSPATH . 'wp-admin/includes/media.php' ); $attachment_id = media_handle_upload('poster', 0); $event = array( 'post_status' =&gt; 'publish', 'post_type' =&gt; 'poster', 'meta_input' =&gt; array(), 'post_category' =&gt; array('poster') ); $post_id = wp_insert_post( $event ); wp_set_post_terms($post_id, 'poster', 'category'); } </code></pre> <p>The uploader works fine, but no category is attached to the image. I have tried and with these:</p> <pre><code>$cat_id = get_cat_ID('cover'); add_term_meta( $cat_id, 'poster', $post_id, true ); wp_set_post_categories($post_id, array('poster'), true); wp_set_post_terms($post_id, array('poster'), 'category'); </code></pre> <p>For the categories for images, I am using this plugin <code>Media Library Categories</code>. </p>
[ { "answer_id": 316432, "author": "Rachid Chihabi", "author_id": 151631, "author_profile": "https://wordpress.stackexchange.com/users/151631", "pm_score": 1, "selected": false, "text": "<p>First of all, if you want to apply categories to Attachments, you have to enable categories for the ...
2018/10/10
[ "https://wordpress.stackexchange.com/questions/316387", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152132/" ]
I want to upload an image and attach to it a category. This is my code: ``` function upload_cover(WP_REST_Request $request) { require_once( ABSPATH . 'wp-admin/includes/image.php' ); require_once( ABSPATH . 'wp-admin/includes/file.php' ); require_once( ABSPATH . 'wp-admin/includes/media.php' ); $attachment_id = media_handle_upload('poster', 0); $event = array( 'post_status' => 'publish', 'post_type' => 'poster', 'meta_input' => array(), 'post_category' => array('poster') ); $post_id = wp_insert_post( $event ); wp_set_post_terms($post_id, 'poster', 'category'); } ``` The uploader works fine, but no category is attached to the image. I have tried and with these: ``` $cat_id = get_cat_ID('cover'); add_term_meta( $cat_id, 'poster', $post_id, true ); wp_set_post_categories($post_id, array('poster'), true); wp_set_post_terms($post_id, array('poster'), 'category'); ``` For the categories for images, I am using this plugin `Media Library Categories`.
First of all, if you want to apply categories to Attachments, you have to enable categories for the attachment. You can do this by using the [register\_taxonomy\_for\_object\_type()](http://codex.wordpress.org/Function_Reference/register_taxonomy_for_object_type) function. In your plugin file or theme functions file, add the following: ``` function wp_add_categories_to_attachments() { register_taxonomy_for_object_type( 'category', 'attachment' ); } add_action( 'init' , 'wp_add_categories_to_attachments' ); ```
316,419
<p>Ok, I'm at wit's end with Wordpress. This is the fifth time I've tried installing it and it flat out is not working. </p> <p>When I install it, it shows one of the themes, but the default welcome post doesn't show up and when I log in it won't let me with the username and password I set up. Am I doing something wrong? </p> <p>The wp-config file is edited to match the db settings.</p> <p>I'm getting very frustrated. I login with <strong>admin</strong> and my password and it says <em>"error: invalid username"</em>. </p> <p>How can it be invalid when I left it at the default which was the admin. What do I do now? I'm completely stumped.</p> <hr> <p>No, I don't have a dedicated host or domain so I'm trying locally with xampp. and the username - password is not case-sensitive even the first letter of the username is not capitalized.</p> <p>I have tried different test cases also like clear site cookies, cache, renaming plugin directory and theme directory one by one.</p> <h2>also, make changes in wp-config.php as follows:</h2> <pre><code>define('WP_DEBUG', true); define('WP_ALLOW_REPAIR', true); </code></pre> <h2>My MySQL settings are also correct, as per standard</h2> <pre><code>define('DB_NAME', 'WP'); /** MySQL database username */ define('DB_USER', 'root'); /** MySQL database password */ define('DB_PASSWORD', ''); /** MySQL hostname */ define('DB_HOST', 'localhost'); /** Database Charset to use in creating database tables. */ define('DB_CHARSET', 'utf8mb4'); /** The Database Collate type. Don't change this if in doubt. */ define('DB_COLLATE', ''); </code></pre> <p>suggest me something plese.</p>
[ { "answer_id": 316432, "author": "Rachid Chihabi", "author_id": 151631, "author_profile": "https://wordpress.stackexchange.com/users/151631", "pm_score": 1, "selected": false, "text": "<p>First of all, if you want to apply categories to Attachments, you have to enable categories for the ...
2018/10/11
[ "https://wordpress.stackexchange.com/questions/316419", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152155/" ]
Ok, I'm at wit's end with Wordpress. This is the fifth time I've tried installing it and it flat out is not working. When I install it, it shows one of the themes, but the default welcome post doesn't show up and when I log in it won't let me with the username and password I set up. Am I doing something wrong? The wp-config file is edited to match the db settings. I'm getting very frustrated. I login with **admin** and my password and it says *"error: invalid username"*. How can it be invalid when I left it at the default which was the admin. What do I do now? I'm completely stumped. --- No, I don't have a dedicated host or domain so I'm trying locally with xampp. and the username - password is not case-sensitive even the first letter of the username is not capitalized. I have tried different test cases also like clear site cookies, cache, renaming plugin directory and theme directory one by one. also, make changes in wp-config.php as follows: ----------------------------------------------- ``` define('WP_DEBUG', true); define('WP_ALLOW_REPAIR', true); ``` My MySQL settings are also correct, as per standard --------------------------------------------------- ``` define('DB_NAME', 'WP'); /** MySQL database username */ define('DB_USER', 'root'); /** MySQL database password */ define('DB_PASSWORD', ''); /** MySQL hostname */ define('DB_HOST', 'localhost'); /** Database Charset to use in creating database tables. */ define('DB_CHARSET', 'utf8mb4'); /** The Database Collate type. Don't change this if in doubt. */ define('DB_COLLATE', ''); ``` suggest me something plese.
First of all, if you want to apply categories to Attachments, you have to enable categories for the attachment. You can do this by using the [register\_taxonomy\_for\_object\_type()](http://codex.wordpress.org/Function_Reference/register_taxonomy_for_object_type) function. In your plugin file or theme functions file, add the following: ``` function wp_add_categories_to_attachments() { register_taxonomy_for_object_type( 'category', 'attachment' ); } add_action( 'init' , 'wp_add_categories_to_attachments' ); ```
316,422
<p>I have created 1 custom post and some custom fields. </p> <ul> <li>Custom post type: Tour <ul> <li>Custom field: tour_id</li> </ul></li> </ul> <p>Now I want to customize permalink link structure, want to append "tour_id" value in link. I'm using below code.</p> <pre><code>add_action('init', 'pub_rewrite_rules'); function pub_rewrite_rules() { global $wp_rewrite; $wp_rewrite-&gt;add_rewrite_tag( '%pstname%', '([^/]+)', 'post_type=tour&amp;name='); $wp_rewrite-&gt;add_rewrite_tag( '%tourid%', '([^/]{4})', 'tourid='); $wp_rewrite-&gt;add_permastruct('tour', '/tour/%pstname%/%tourid%', array( 'walk_dirs' =&gt; false )); } function pub_permalink($permalink, $post, $leavename) { if((false !==strpos( $permalink, '%tourid%') ) &amp;&amp; get_post_type($post)=='tour') { $publicationtype = get_post_meta($post-&gt;ID, 'tour_id',true); $rewritecode = array('%pstname%','%tourid%'); $rewritereplace = array($post-&gt;post_name,$publicationtype); $permalink = str_replace($rewritecode, $rewritereplace, $permalink); } return $permalink; } </code></pre> <p>I'm getting correct link "<a href="https://tourjourney/tour/tour-1/1000/" rel="nofollow noreferrer">https://tourjourney/tour/tour-1/1000/</a>" here, "tour" is custom post, "tour-1" is post title and "1000" is tour_id, but while viewing the post i'm getting "404 File Not Found error". <a href="https://i.stack.imgur.com/vcTyd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vcTyd.png" alt="tour1"></a> I have done above code in function.php file of theme. I have checked .htaccess, it's proper.</p> <p>I guess the problem is in add_permastruct or m'I missing anything in code.</p>
[ { "answer_id": 316436, "author": "Rachid Chihabi", "author_id": 151631, "author_profile": "https://wordpress.stackexchange.com/users/151631", "pm_score": 1, "selected": false, "text": "<p>I had the same technical need as you, and I have did this(code below) to get it work :</p>\n\n<pre><...
2018/10/11
[ "https://wordpress.stackexchange.com/questions/316422", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152163/" ]
I have created 1 custom post and some custom fields. * Custom post type: Tour + Custom field: tour\_id Now I want to customize permalink link structure, want to append "tour\_id" value in link. I'm using below code. ``` add_action('init', 'pub_rewrite_rules'); function pub_rewrite_rules() { global $wp_rewrite; $wp_rewrite->add_rewrite_tag( '%pstname%', '([^/]+)', 'post_type=tour&name='); $wp_rewrite->add_rewrite_tag( '%tourid%', '([^/]{4})', 'tourid='); $wp_rewrite->add_permastruct('tour', '/tour/%pstname%/%tourid%', array( 'walk_dirs' => false )); } function pub_permalink($permalink, $post, $leavename) { if((false !==strpos( $permalink, '%tourid%') ) && get_post_type($post)=='tour') { $publicationtype = get_post_meta($post->ID, 'tour_id',true); $rewritecode = array('%pstname%','%tourid%'); $rewritereplace = array($post->post_name,$publicationtype); $permalink = str_replace($rewritecode, $rewritereplace, $permalink); } return $permalink; } ``` I'm getting correct link "<https://tourjourney/tour/tour-1/1000/>" here, "tour" is custom post, "tour-1" is post title and "1000" is tour\_id, but while viewing the post i'm getting "404 File Not Found error". [![tour1](https://i.stack.imgur.com/vcTyd.png)](https://i.stack.imgur.com/vcTyd.png) I have done above code in function.php file of theme. I have checked .htaccess, it's proper. I guess the problem is in add\_permastruct or m'I missing anything in code.
I had the same technical need as you, and I have did this(code below) to get it work : ``` function my_custom_rewrite_tag() { add_rewrite_tag('%xxx%', '([^&]+)'); //change the regex to your needs add_rewrite_tag('%yyy%', '([^&]+)'); //change the regex to your needs } add_action('init', 'my_custom_rewrite_tag', 10, 0); function my_custom_rewrite_rule() { add_rewrite_rule('^tour/([^/]*)/([^/]*)/?','index.php?pagename=tour&xxx=$matches[1]&yyy=$matches[2]','top'); } add_action('init', 'my_custom_rewrite_rule', 10, 0); ``` Finally, do not forget to flash the permalinks structure from your dashboard.
316,438
<p><a href="https://i.stack.imgur.com/GBnga.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GBnga.png" alt="enter image description here"></a> </p> <p>So this is my code. This piece of code shows me the child page titles. But i'm providing the ID from the parent page. Is there a way to make this dynamic? I don't want to use the ID cuz then its static..</p> <pre><code> &lt;?php $childArgs = array( 'sort_order' =&gt; 'ASC', 'sort_column' =&gt; 'menu_order', 'child_of' =&gt; 127 ); $childList = get_pages($childArgs); foreach ($childList as $child) { ?&gt; &lt;ul class="menu-items menu-level-1 menu-count-5"&gt; &lt;li class="menu-item item-number-1 item-number-2 item-number-3 item-number-4 item-number-5 item-id-84283 item-odd item-page item-node item-alias-over-ons-de-winkel"&gt;&lt;a href=""&gt;&lt;?php echo $child-&gt;post_title; ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php } ?&gt; </code></pre>
[ { "answer_id": 316444, "author": "Pim", "author_id": 50432, "author_profile": "https://wordpress.stackexchange.com/users/50432", "pm_score": -1, "selected": false, "text": "<p>Try the following:</p>\n\n<pre><code>&lt;?php\n\n global $post;\n\n $page_id = get_the_id();\n\n $childArgs =...
2018/10/11
[ "https://wordpress.stackexchange.com/questions/316438", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152168/" ]
[![enter image description here](https://i.stack.imgur.com/GBnga.png)](https://i.stack.imgur.com/GBnga.png) So this is my code. This piece of code shows me the child page titles. But i'm providing the ID from the parent page. Is there a way to make this dynamic? I don't want to use the ID cuz then its static.. ``` <?php $childArgs = array( 'sort_order' => 'ASC', 'sort_column' => 'menu_order', 'child_of' => 127 ); $childList = get_pages($childArgs); foreach ($childList as $child) { ?> <ul class="menu-items menu-level-1 menu-count-5"> <li class="menu-item item-number-1 item-number-2 item-number-3 item-number-4 item-number-5 item-id-84283 item-odd item-page item-node item-alias-over-ons-de-winkel"><a href=""><?php echo $child->post_title; ?></a></li> <?php } ?> ```
//The correct code functions.php ``` function get_page_parent_id( $id ) { $args = array( 'sort_order' => 'ASC', 'sort_column' => 'menu_order', 'child_of' => $id ); $args = get_pages($args); if(is_array($pages)) $pageID = $id; else { $pageID = wp_get_post_parent_id( $id ); } return $pageID; } ?> ``` page.php ``` <?php $parentID = get_page_parent_id(get_the_ID()); $childArgs = array( 'sort_order' => 'ASC', 'sort_column' => 'menu_order', 'child_of' => $parentID ); ?> <div class="subnav"> <h3 class="subnav-headline"><a href="/over-ons" class="c-dark"><?php echo get_the_title($parentID); ?></a></h3> <ul class="menu-items menu-level-1 menu-count-5"> <?php $pages = get_pages($childArgs); foreach($pages as $page ) { ?> <li class="menu-item item-number-2 item-id-84286 item-even item-page item-node item-alias-over-ons-geschiedenis-leonidas"><a href="<?php echo get_the_permalink($page);?>"><?php echo $page->post_title;?></a></li> <?php } ?> </ul> </div> ```
316,469
<p>The problem I've run into is the WordPress for my website yesterday randomly stopped allowing us to edit any of the pages. Every time you click to edit a page it comes up with a 404 error. </p> <p>Things I have tried so far:</p> <ul> <li>Deactivated every plugin thinking that was the problem, but that didn't solve the issue</li> <li>I have restarted the permalinks</li> <li>Changed the theme</li> <li>Even checked the code in the htacess file</li> </ul> <p>The website is fully functioning and viewable to our visitors. We just can't edit any of the pages now for some reason.</p>
[ { "answer_id": 316444, "author": "Pim", "author_id": 50432, "author_profile": "https://wordpress.stackexchange.com/users/50432", "pm_score": -1, "selected": false, "text": "<p>Try the following:</p>\n\n<pre><code>&lt;?php\n\n global $post;\n\n $page_id = get_the_id();\n\n $childArgs =...
2018/10/11
[ "https://wordpress.stackexchange.com/questions/316469", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152182/" ]
The problem I've run into is the WordPress for my website yesterday randomly stopped allowing us to edit any of the pages. Every time you click to edit a page it comes up with a 404 error. Things I have tried so far: * Deactivated every plugin thinking that was the problem, but that didn't solve the issue * I have restarted the permalinks * Changed the theme * Even checked the code in the htacess file The website is fully functioning and viewable to our visitors. We just can't edit any of the pages now for some reason.
//The correct code functions.php ``` function get_page_parent_id( $id ) { $args = array( 'sort_order' => 'ASC', 'sort_column' => 'menu_order', 'child_of' => $id ); $args = get_pages($args); if(is_array($pages)) $pageID = $id; else { $pageID = wp_get_post_parent_id( $id ); } return $pageID; } ?> ``` page.php ``` <?php $parentID = get_page_parent_id(get_the_ID()); $childArgs = array( 'sort_order' => 'ASC', 'sort_column' => 'menu_order', 'child_of' => $parentID ); ?> <div class="subnav"> <h3 class="subnav-headline"><a href="/over-ons" class="c-dark"><?php echo get_the_title($parentID); ?></a></h3> <ul class="menu-items menu-level-1 menu-count-5"> <?php $pages = get_pages($childArgs); foreach($pages as $page ) { ?> <li class="menu-item item-number-2 item-id-84286 item-even item-page item-node item-alias-over-ons-geschiedenis-leonidas"><a href="<?php echo get_the_permalink($page);?>"><?php echo $page->post_title;?></a></li> <?php } ?> </ul> </div> ```
316,472
<p>I am trying to run js function when customizer section is expended and cant seem to find any event to do so. </p> <p>Something like this </p> <pre><code>wp.customize.bind( 'ready', function() { wp.customize.section.bind( 'expand', function() { console.log('hello'); }); } ); </code></pre> <p>or </p> <pre><code>wp.customize.bind( 'ready', function() { wp.customize.section.on( 'opened', function() { console.log('hello'); }); } ); </code></pre> <p>or anything that triggers when section is active/activated/expanded/opened. </p> <p>Any help is appreciated!</p>
[ { "answer_id": 316558, "author": "Benn", "author_id": 67176, "author_profile": "https://wordpress.stackexchange.com/users/67176", "pm_score": 2, "selected": false, "text": "<p>Here it is </p>\n\n<pre><code>wp.customize.bind( 'ready', function() {\n\n wp.customize.section.each( functio...
2018/10/11
[ "https://wordpress.stackexchange.com/questions/316472", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67176/" ]
I am trying to run js function when customizer section is expended and cant seem to find any event to do so. Something like this ``` wp.customize.bind( 'ready', function() { wp.customize.section.bind( 'expand', function() { console.log('hello'); }); } ); ``` or ``` wp.customize.bind( 'ready', function() { wp.customize.section.on( 'opened', function() { console.log('hello'); }); } ); ``` or anything that triggers when section is active/activated/expanded/opened. Any help is appreciated!
Here it is ``` wp.customize.bind( 'ready', function() { wp.customize.section.each( function ( section ) { section.expanded.bind( function( isExpanding ) { if(isExpanding){ console.log(section); } }); }); }); ```
316,508
<p>I want my site to have logo like when i go to google.com it shows the google logo with google at the tabs on top of browser. How can I achieve this for my wordpress site ?</p>
[ { "answer_id": 316558, "author": "Benn", "author_id": 67176, "author_profile": "https://wordpress.stackexchange.com/users/67176", "pm_score": 2, "selected": false, "text": "<p>Here it is </p>\n\n<pre><code>wp.customize.bind( 'ready', function() {\n\n wp.customize.section.each( functio...
2018/10/12
[ "https://wordpress.stackexchange.com/questions/316508", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152109/" ]
I want my site to have logo like when i go to google.com it shows the google logo with google at the tabs on top of browser. How can I achieve this for my wordpress site ?
Here it is ``` wp.customize.bind( 'ready', function() { wp.customize.section.each( function ( section ) { section.expanded.bind( function( isExpanding ) { if(isExpanding){ console.log(section); } }); }); }); ```
316,530
<p>I've a problem with some functions on function.php. I want to use get_tems_by("slug", $slug, "category"); but it doesn't work inside a function on function.php. When i changed slug by ID and give a random ID it's work. I'm sure that the slug exist. I've also try that : </p> <pre><code>add_action( 'init', 'wpse27111_tester', 999 ); function wpse27111_tester() { $term = get_term_by('slug', 'some-term', 'some-taxonomy'); var_dump($term); } </code></pre> <p>And it's work but i need to put $slug</p> <p>If you have a solution please tell me.</p>
[ { "answer_id": 316574, "author": "Remzi Cavdar", "author_id": 149484, "author_profile": "https://wordpress.stackexchange.com/users/149484", "pm_score": 1, "selected": false, "text": "<p>Did you try to use add_action without priority? On the last line, you specify the priority. Lower numb...
2018/10/12
[ "https://wordpress.stackexchange.com/questions/316530", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152232/" ]
I've a problem with some functions on function.php. I want to use get\_tems\_by("slug", $slug, "category"); but it doesn't work inside a function on function.php. When i changed slug by ID and give a random ID it's work. I'm sure that the slug exist. I've also try that : ``` add_action( 'init', 'wpse27111_tester', 999 ); function wpse27111_tester() { $term = get_term_by('slug', 'some-term', 'some-taxonomy'); var_dump($term); } ``` And it's work but i need to put $slug If you have a solution please tell me.
Did you try to use add\_action without priority? On the last line, you specify the priority. Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action. ``` function test_1234567() { // Get term by name ''news'' in Categories taxonomy. $category = get_term_by('name', 'news', 'category'); // Get term by name ''news'' in Tags taxonomy. $tag = get_term_by('name', 'news', 'post_tag'); // Get term by name ''news'' in Custom taxonomy. $term = get_term_by('name', 'news', 'my_custom_taxonomy'); // Get term by name ''Default Menu'' from theme's nav menus. // (Alternative to using wp_get_nav_menu_items) $menu = get_term_by('name', 'Default Menu', 'nav_menu'); var_dump($category); } add_action( 'init', 'test_1234567' ); ``` Also, you do not need to specify the priority, the default is 10.
316,541
<p>I want to show avatar from the post author. I use Ultimate Members and want to show the avatars that are defined via UM.</p> <pre><code>&lt;?php global $post; $url = get_avatar_url( $post, array( 'size' =&gt; 48 )); $img = '&lt;img alt="" src="'. $url .'"&gt;'; echo $img; ?&gt; </code></pre> <p>But this code shows the gravatars or default avatar. How can I get the avatars from Ultimate Member?</p>
[ { "answer_id": 316574, "author": "Remzi Cavdar", "author_id": 149484, "author_profile": "https://wordpress.stackexchange.com/users/149484", "pm_score": 1, "selected": false, "text": "<p>Did you try to use add_action without priority? On the last line, you specify the priority. Lower numb...
2018/10/12
[ "https://wordpress.stackexchange.com/questions/316541", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152174/" ]
I want to show avatar from the post author. I use Ultimate Members and want to show the avatars that are defined via UM. ``` <?php global $post; $url = get_avatar_url( $post, array( 'size' => 48 )); $img = '<img alt="" src="'. $url .'">'; echo $img; ?> ``` But this code shows the gravatars or default avatar. How can I get the avatars from Ultimate Member?
Did you try to use add\_action without priority? On the last line, you specify the priority. Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action. ``` function test_1234567() { // Get term by name ''news'' in Categories taxonomy. $category = get_term_by('name', 'news', 'category'); // Get term by name ''news'' in Tags taxonomy. $tag = get_term_by('name', 'news', 'post_tag'); // Get term by name ''news'' in Custom taxonomy. $term = get_term_by('name', 'news', 'my_custom_taxonomy'); // Get term by name ''Default Menu'' from theme's nav menus. // (Alternative to using wp_get_nav_menu_items) $menu = get_term_by('name', 'Default Menu', 'nav_menu'); var_dump($category); } add_action( 'init', 'test_1234567' ); ``` Also, you do not need to specify the priority, the default is 10.
316,546
<p>The shortcode for the MailChimp subscribe form in my theme's custom homepage is not working. But when I put the same shortcode in a blog page and other pages, then it is working</p> <p>I put the shortcode <code>[mc4wp_form id=&quot;id&quot;]</code> in theme pages and it's working.</p> <p>But when I put <code>&lt;?php echo do_shortcode ([mc4wp_form id=&quot;id&quot;]); ?&gt;</code> in my custom homepage, then it's not working.</p> <p>thanks</p>
[ { "answer_id": 316548, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>You're missing quotes around the shortcode in the <code>do_shortcode()</code> function:</p>\n\n<pre><co...
2018/10/12
[ "https://wordpress.stackexchange.com/questions/316546", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149030/" ]
The shortcode for the MailChimp subscribe form in my theme's custom homepage is not working. But when I put the same shortcode in a blog page and other pages, then it is working I put the shortcode `[mc4wp_form id="id"]` in theme pages and it's working. But when I put `<?php echo do_shortcode ([mc4wp_form id="id"]); ?>` in my custom homepage, then it's not working. thanks
The common way to approach this is to use `do_shortcode()`. But that's not an efficient way to do it because it has to run a pretty extensive regex (regular expression) to parse through every single shortcode in your WP install to get to the one you are asking for. [See this post for a more thorough explanation](https://konstantin.blog/2013/dont-do_shortcode/). A better approach is to run the callback function needed directly. But that can sometimes be a challenge - either you have to dig through a lot of code to find it, or it may possibly be in an object class and how do you call that? [J.D. Grimes has provided a good utility function](https://codesymphony.co/dont-do_shortcode/) for calling shortcodes this way so that you can get to the direct callback function without having to use do\_shortcode(). Add the following function, which you can use for any shortcode instance: ``` /** * Call a shortcode function by tag name. * * @author J.D. Grimes * @link https://codesymphony.co/dont-do_shortcode/ * * @param string $tag The shortcode whose function to call. * @param array $atts The attributes to pass to the shortcode function. Optional. * @param array $content The shortcode's content. Default is null (none). * * @return string|bool False on failure, the result of the shortcode on success. */ function do_shortcode_func( $tag, array $atts = array(), $content = null ) { global $shortcode_tags; if ( ! isset( $shortcode_tags[ $tag ] ) ) return false; return call_user_func( $shortcode_tags[ $tag ], $atts, $content, $tag ); } ``` Then you can call your shortcode this way: ``` echo do_shortcode_func( 'mc4wp_form', array( 'id' => 'id' ) ); ```
316,550
<p>I registered a new footer widget with this code.</p> <pre><code>register_sidebar(array( 'name' =&gt; esc_html__( 'Footer Sidebarprestige', 'realtor' ), 'id' =&gt; 'footer-sidebarprestige', 'description' =&gt; esc_html__( 'Widgets in this area will be shown in Footer Area.', 'realtor' ), 'class'=&gt;'', 'before_widget'=&gt;'&lt;li id="%1$s" class="col-md-3 col-sm-6 widget %2$s"&gt;', 'after_widget'=&gt;'&lt;/li&gt;', 'before_title' =&gt; '&lt;h5&gt;', 'after_title' =&gt; '&lt;/h5&gt;' )); </code></pre> <p>I called it in my footer.php file like this:</p> <pre><code>&lt;ul class="row"&gt; &lt;?php dynamic_sidebar('footer-sidebar'); ?&gt; &lt;/ul&gt; &lt;ul class="row"&gt; &lt;?php dynamic_sidebar('footer-sidebarprestige'); ?&gt; &lt;/ul&gt; </code></pre> <p>The 'footer-sidebar' is original widget and the 'footer-sidebarprestige' is the one I added. The way it is now if I add a widget to the widget area I added it shows up under the original one and I understand why.</p> <p>What I am trying to do. Call the widget area that I added only for certain page ID's. Basically, only on called page ID's show newly created footer widget and not show the original widget area.</p>
[ { "answer_id": 316552, "author": "Pim", "author_id": 50432, "author_profile": "https://wordpress.stackexchange.com/users/50432", "pm_score": 3, "selected": true, "text": "<p>There are several ways you can achieve this:</p>\n\n<p>A. Use CSS to hide and show widgets based on which page you...
2018/10/12
[ "https://wordpress.stackexchange.com/questions/316550", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146043/" ]
I registered a new footer widget with this code. ``` register_sidebar(array( 'name' => esc_html__( 'Footer Sidebarprestige', 'realtor' ), 'id' => 'footer-sidebarprestige', 'description' => esc_html__( 'Widgets in this area will be shown in Footer Area.', 'realtor' ), 'class'=>'', 'before_widget'=>'<li id="%1$s" class="col-md-3 col-sm-6 widget %2$s">', 'after_widget'=>'</li>', 'before_title' => '<h5>', 'after_title' => '</h5>' )); ``` I called it in my footer.php file like this: ``` <ul class="row"> <?php dynamic_sidebar('footer-sidebar'); ?> </ul> <ul class="row"> <?php dynamic_sidebar('footer-sidebarprestige'); ?> </ul> ``` The 'footer-sidebar' is original widget and the 'footer-sidebarprestige' is the one I added. The way it is now if I add a widget to the widget area I added it shows up under the original one and I understand why. What I am trying to do. Call the widget area that I added only for certain page ID's. Basically, only on called page ID's show newly created footer widget and not show the original widget area.
There are several ways you can achieve this: A. Use CSS to hide and show widgets based on which page you are on. This is fine as a workaround, but it isn't really solving your problem, especially if you have lots of pages/widgets. B. Call a different widget area in your template file with conditional logic ``` <ul class="row"> <?php if(is_page('my-page')){ dynamic_sidebar('footer-sidebarprestige'); } ?> </ul> ``` C. Use a plugin like [Widget Logic](https://wordpress.org/plugins/widget-logic/) to use conditional logic on the widgets themselves. You can then add a condition like `is_page('my-page')` for displaying the widget, on a widget-per-widget basis.
316,576
<p>I have a ton of posts that we created, but unfortunately there are a lot of blank spaces. This is an example of what I see on the backend, in the actual post:</p> <pre><code>&lt;h1&gt;This is a post title&lt;/h1&gt; &amp;nbsp; &amp;nbsp; Words here. More words. &amp;nbsp; &amp;nbsp; Words down here. </code></pre> <p>So, when that is rendered on the page on the Front end, there are extra line breaks that I'd like to get rid of.</p> <p>Is there a way to loop through the actual posts on the backend? Then I can (somehow) check for 2+ empty lines and/or <code>&amp;nbsp;</code>, and remove them.</p> <p>Or - a solution to the symptom, not the problem - would I be better off somehow using CSS to remove such lines?</p>
[ { "answer_id": 316584, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 2, "selected": true, "text": "<p>Since there are no tags around the space <code>&amp;nbsp;</code> characters, they will be compressed on...
2018/10/12
[ "https://wordpress.stackexchange.com/questions/316576", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147631/" ]
I have a ton of posts that we created, but unfortunately there are a lot of blank spaces. This is an example of what I see on the backend, in the actual post: ``` <h1>This is a post title</h1> &nbsp; &nbsp; Words here. More words. &nbsp; &nbsp; Words down here. ``` So, when that is rendered on the page on the Front end, there are extra line breaks that I'd like to get rid of. Is there a way to loop through the actual posts on the backend? Then I can (somehow) check for 2+ empty lines and/or `&nbsp;`, and remove them. Or - a solution to the symptom, not the problem - would I be better off somehow using CSS to remove such lines?
Since there are no tags around the space `&nbsp;` characters, they will be compressed on the page output. So the visual output will not be affected. And a very minor effect on the database or processing of the post content. If you are really concerned about the extra stuff, then you could use `the_content` filter to remove extra `&nbsp;` in the content. But you would have to be careful that your filter didn't remove `&nbsp;` that really needed to be in the content. Which is why I don't think that the effort to remove is worth it, and may cause unexpected problems. **Added** If you really want to get rid of the extra spaces in the posts, then see the answer [here](https://wordpress.stackexchange.com/questions/35931/how-can-i-edit-post-data-before-it-is-saved), where the [wp\_insert\_post\_data](http://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data) filter is used. That filter fires when the post is saved via the editor. You'll just need to adjust the regex for the text you are looking to replace. Look at a example post in text editing mode to get the actual string to look for in the regex. (Regex is hard for the amatuer - and maybe the experts - but you might look at this Regex testing site to tweak your regex so it works: <https://regex101.com/> . I like that site, because it explains things and also creates the PHP code needed to do the Regex.)
316,579
<p>I inherited a WordPress site that has a lot of custom coding that appears to be Bootstrap. A contact form is coded in a PHP file and the client would like to add a couple more email addresses for submissions to be sent to.</p> <p>I've found the code for sending the email, but I want to make sure that I update it correctly and not break it. Here is the line of code:</p> <p><code>$emails = array( $email, 'myemail@me.com' );</code></p> <p>I'm assuming that I will either need to update it to</p> <p><code>$emails = array( $email, 'myemail@me.com, anotheremail@me.com' );</code></p> <p>or</p> <p><code>$emails = array( $email, 'myemail@me.com','anotheremail@me.com' );</code></p> <p>Any insight on which would be correct?</p>
[ { "answer_id": 316580, "author": "Liam Stewart", "author_id": 121955, "author_profile": "https://wordpress.stackexchange.com/users/121955", "pm_score": 1, "selected": false, "text": "<p>Looking at the snippet you provided the solution seems to be your last solution.</p>\n\n<pre><code>$em...
2018/10/12
[ "https://wordpress.stackexchange.com/questions/316579", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127744/" ]
I inherited a WordPress site that has a lot of custom coding that appears to be Bootstrap. A contact form is coded in a PHP file and the client would like to add a couple more email addresses for submissions to be sent to. I've found the code for sending the email, but I want to make sure that I update it correctly and not break it. Here is the line of code: `$emails = array( $email, 'myemail@me.com' );` I'm assuming that I will either need to update it to `$emails = array( $email, 'myemail@me.com, anotheremail@me.com' );` or `$emails = array( $email, 'myemail@me.com','anotheremail@me.com' );` Any insight on which would be correct?
Looking at the snippet you provided the solution seems to be your last solution. ``` $emails = array( $email, 'myemail@me.com','anotheremail@me.com' ); ``` Sending an array of emails, the first one (`$email`) being the dynamic email. The second and third would be hard coded values. This is assuming the email handler is ready to accept an array of emails to mail to. **EDIT** I see some comments regarding your first attempt: ``` $emails = array( $email, 'myemail@me.com, anotheremail@me.com' ); ``` This is a valid array - however will pass the value of `myemail@me.com, anotheremail@me.com` instead of `myemail@me.com` and `anotheremail@me.com` as separate values - which by first glance is how the code is expecting additional email addresses.
316,590
<p>For the contact form of my own theme I have created a Custom Post Type in which the messages of the users are automatically stored. In the administration area the messages can be read similar to comments.</p> <p>By doing this, you can create, change and delete messages in the administration area. All these functionalities should be prevented, so that only the reading of the messages remains possible. </p> <p>I tried to achieve this by giving the custom post type its own capability and assigning read rights to all user roles only. Unfortunately, by doing so, the Custom Post Type is no longer displayed at all. As it turned out, this is probably because the read rights are meant for the frontend. So how is it possible to restrict access to the custom post type to reading only?</p> <hr> <p>Here are my CPT args:</p> <pre><code>$args = array( 'labels' =&gt; $labels, 'public' =&gt; false, 'publicly_queryable' =&gt; false, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'show_in_admin_bar' =&gt; false, 'menu_icon' =&gt; 'dashicons-email-alt', 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'contact-form' ), 'capability_type' =&gt; array( 'contactFormMessage', 'contactFormMessages' ), 'capabilities' =&gt; array( 'edit_post' =&gt; 'edit_contactFormMessage', 'edit_posts' =&gt; 'edit_contactFormMessages', 'edit_others_posts' =&gt; 'edit_other_contactFormMessages', 'publish_posts' =&gt; 'publish_contactFormMessages', 'read_post' =&gt; 'read_contactFormMessage', 'read_private_posts' =&gt; 'read_private_contactFormMessages', 'delete_post' =&gt; 'delete_contactFormMessage' ), 'map_meta_cap' =&gt; true, 'has_archive' =&gt; true, 'hierarchical' =&gt; false, 'menu_position' =&gt; null, 'supports' =&gt; array( 'title', 'editor', 'author' ) ); </code></pre> <p>And using the following loop, I gave the read rights to all the user roles.</p> <pre><code>global $wp_roles; foreach ( $wp_roles-&gt;roles as $key =&gt; $value ) { $currentRole = get_role( $key ); $currentRole-&gt;add_cap( 'read_contactFormMessages' ); $currentRole-&gt;add_cap( 'read_private_contactFormMessages' ); } </code></pre> <hr> <p>For the sake of security, I'm searching for a plugin-free solution to this issue. However, should it be a huge effort to achieve this, the use of a plugin is still an option.</p>
[ { "answer_id": 316594, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 0, "selected": false, "text": "<p>You are correct that the <code>read</code> capability is intended for the frontend. <strong>The capability y...
2018/10/12
[ "https://wordpress.stackexchange.com/questions/316590", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93282/" ]
For the contact form of my own theme I have created a Custom Post Type in which the messages of the users are automatically stored. In the administration area the messages can be read similar to comments. By doing this, you can create, change and delete messages in the administration area. All these functionalities should be prevented, so that only the reading of the messages remains possible. I tried to achieve this by giving the custom post type its own capability and assigning read rights to all user roles only. Unfortunately, by doing so, the Custom Post Type is no longer displayed at all. As it turned out, this is probably because the read rights are meant for the frontend. So how is it possible to restrict access to the custom post type to reading only? --- Here are my CPT args: ``` $args = array( 'labels' => $labels, 'public' => false, 'publicly_queryable' => false, 'show_ui' => true, 'show_in_menu' => true, 'show_in_admin_bar' => false, 'menu_icon' => 'dashicons-email-alt', 'query_var' => true, 'rewrite' => array( 'slug' => 'contact-form' ), 'capability_type' => array( 'contactFormMessage', 'contactFormMessages' ), 'capabilities' => array( 'edit_post' => 'edit_contactFormMessage', 'edit_posts' => 'edit_contactFormMessages', 'edit_others_posts' => 'edit_other_contactFormMessages', 'publish_posts' => 'publish_contactFormMessages', 'read_post' => 'read_contactFormMessage', 'read_private_posts' => 'read_private_contactFormMessages', 'delete_post' => 'delete_contactFormMessage' ), 'map_meta_cap' => true, 'has_archive' => true, 'hierarchical' => false, 'menu_position' => null, 'supports' => array( 'title', 'editor', 'author' ) ); ``` And using the following loop, I gave the read rights to all the user roles. ``` global $wp_roles; foreach ( $wp_roles->roles as $key => $value ) { $currentRole = get_role( $key ); $currentRole->add_cap( 'read_contactFormMessages' ); $currentRole->add_cap( 'read_private_contactFormMessages' ); } ``` --- For the sake of security, I'm searching for a plugin-free solution to this issue. However, should it be a huge effort to achieve this, the use of a plugin is still an option.
You are correct that the `read` capability is intended for the frontend. **The capability you're looking for does not exist**. Additionally, if it did exist ( which it does not ), the WP Admin user interface does not provide a UI for viewing/reading posts, only addition and editing. If you want it, I'm afraid you have to take the following steps: * Add a new capability, and add it to the relevant roles * Remove the standard WP access to those custom post types for those roles * Implement a UI from scratch, including a listing screen, and an option page for viewing the items
316,615
<p>So in this quest to build a custom pseudo web chat service with Telegram, I'm trying to get the messages Telegram sends to the server and redirect them to frontend. SSE with <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource" rel="nofollow noreferrer">HTML5 EventSource</a> seems the best and easy solution to do that.</p> <p>The thing is that EventSource needs <code>'Content-Type: text/event-stream'</code> and <code>'Cache-Control: no-cache'</code> headers set in server's response.</p> <p>If a <code>WP_REST_REQUEST</code> is returned on the function that sets the response ("set_telegram_response", below), nothing will arrive at EventSource. But if the response is echoed, EventSource will close the connection claiming that the server is sending a JSON response instead of a <code>text/event-stream</code> one.</p> <p>Following is the barebones of the class I wrote for this. If I pull a GET request on that endpoint, it will return the "Some text" string. But the EventSource script prints nothing, as if the response were empty.</p> <pre><code>class Chat { private static $token, $telegram, $chat_id; public $telegram_message; public function __construct() { self::$chat_id = "&lt;TELEGRAM-CHAT-ID&gt;"; self::$token = "&lt;TELEGRAM-TOKEN&gt;"; self::$telegram = "https://api.telegram.org:443/bot" . self::$token; add_action('rest_api_init', array( $this, 'set_telegram_message_endpoint' )); add_action('admin_post_chat_form', array( $this, 'chat_telegram' )); add_action('admin_post_nopriv_chat_form', array( $this, 'chat_telegram' )); } public function set_telegram_message_endpoint() { register_rest_route('mybot/v2', 'bot', array( array( 'methods' =&gt; WP_REST_SERVER::CREATABLE, 'callback' =&gt; array( $this, 'get_telegram_message' ), ), array( 'methods' =&gt; WP_REST_SERVER::READABLE, 'callback' =&gt; array( $this, 'set_telegram_message' ), ), )); } public function set_telegram_message( WP_REST_REQUEST $request ) { $new_response = new WP_REST_Response( "Some text" . PHP_EOL . PHP_EOL, 200 ); $new_response-&gt;header( 'Content-Type', 'text/event-stream' ); $new_response-&gt;header( 'Cache-Control', 'no-cache' ); ob_flush(); return $new_response; } public function get_telegram_message( WP_REST_REQUEST $request ) { $this-&gt;telegram_message = $request; //return rest_ensure_response( $request['message']['text'] ); } public function chat_telegram( $input = null ) { $mensaje = $input === '' ? $_POST['texto'] : $input; echo $mensaje; $query = http_build_query([ 'chat_id' =&gt; self::$chat_id, 'text' =&gt; $mensaje, 'parse_mode' =&gt; "Markdown", ]); $response = file_get_contents( self::$telegram . '/sendMessage?' . $query ); return $response; } } </code></pre> <p>I spent all the afternoon and part of this morning reading the documentation on REST API, but couldn't find any clue on what could be wrong or how to do this.</p> <p>BTW, the server I'm deploying this can handle EventSource requests - I just tried it on a test PHP script and it worked well. So I really don't know what is going on here. Any help would be hugely appreciated.</p>
[ { "answer_id": 316753, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>This is because the rest API internally uses <code>json_encode()</code> to output the data. There are 2 way...
2018/10/13
[ "https://wordpress.stackexchange.com/questions/316615", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145926/" ]
So in this quest to build a custom pseudo web chat service with Telegram, I'm trying to get the messages Telegram sends to the server and redirect them to frontend. SSE with [HTML5 EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) seems the best and easy solution to do that. The thing is that EventSource needs `'Content-Type: text/event-stream'` and `'Cache-Control: no-cache'` headers set in server's response. If a `WP_REST_REQUEST` is returned on the function that sets the response ("set\_telegram\_response", below), nothing will arrive at EventSource. But if the response is echoed, EventSource will close the connection claiming that the server is sending a JSON response instead of a `text/event-stream` one. Following is the barebones of the class I wrote for this. If I pull a GET request on that endpoint, it will return the "Some text" string. But the EventSource script prints nothing, as if the response were empty. ``` class Chat { private static $token, $telegram, $chat_id; public $telegram_message; public function __construct() { self::$chat_id = "<TELEGRAM-CHAT-ID>"; self::$token = "<TELEGRAM-TOKEN>"; self::$telegram = "https://api.telegram.org:443/bot" . self::$token; add_action('rest_api_init', array( $this, 'set_telegram_message_endpoint' )); add_action('admin_post_chat_form', array( $this, 'chat_telegram' )); add_action('admin_post_nopriv_chat_form', array( $this, 'chat_telegram' )); } public function set_telegram_message_endpoint() { register_rest_route('mybot/v2', 'bot', array( array( 'methods' => WP_REST_SERVER::CREATABLE, 'callback' => array( $this, 'get_telegram_message' ), ), array( 'methods' => WP_REST_SERVER::READABLE, 'callback' => array( $this, 'set_telegram_message' ), ), )); } public function set_telegram_message( WP_REST_REQUEST $request ) { $new_response = new WP_REST_Response( "Some text" . PHP_EOL . PHP_EOL, 200 ); $new_response->header( 'Content-Type', 'text/event-stream' ); $new_response->header( 'Cache-Control', 'no-cache' ); ob_flush(); return $new_response; } public function get_telegram_message( WP_REST_REQUEST $request ) { $this->telegram_message = $request; //return rest_ensure_response( $request['message']['text'] ); } public function chat_telegram( $input = null ) { $mensaje = $input === '' ? $_POST['texto'] : $input; echo $mensaje; $query = http_build_query([ 'chat_id' => self::$chat_id, 'text' => $mensaje, 'parse_mode' => "Markdown", ]); $response = file_get_contents( self::$telegram . '/sendMessage?' . $query ); return $response; } } ``` I spent all the afternoon and part of this morning reading the documentation on REST API, but couldn't find any clue on what could be wrong or how to do this. BTW, the server I'm deploying this can handle EventSource requests - I just tried it on a test PHP script and it worked well. So I really don't know what is going on here. Any help would be hugely appreciated.
This is because the rest API internally uses `json_encode()` to output the data. There are 2 ways that you can resolve this. 1. Prevent the API from sending the data ---------------------------------------- This might be a bit odd and raise some issues, but you can set the header type and echo the content before returning the data: ``` header( 'Content-Type: text/event-stream' ); header( 'Cache-Control: no-cache' ); // Echo whatever data you got here // Prevent the API from continuing exit(); ``` Since this is not the standard way to use the API, it might cause some issues. I haven't tried this myself. 2. Use `admin-ajax.php` ----------------------- Instead of the rest API, use the admin AJAX. The implementation is the same. Basically if you use `json_encode()` alongside with `die();` you'll get the same results as rest API. The [codex page](https://codex.wordpress.org/AJAX_in_Plugins) on this topic covers almost everything. By using admin AJAX, you can fully control the headers and output type.
316,624
<p>When created a new page or post or columns blocks we get the "Write your story" placeholder. Can this be removed or replaced, in custom blocks? How?</p> <p><a href="https://i.stack.imgur.com/XY26Z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XY26Z.png" alt="enter image description here"></a></p>
[ { "answer_id": 316677, "author": "admcfajn", "author_id": 123674, "author_profile": "https://wordpress.stackexchange.com/users/123674", "pm_score": 0, "selected": false, "text": "<p>Here's an example block taken from <a href=\"https://github.com/WordPress/gutenberg-examples\" rel=\"nofol...
2018/10/13
[ "https://wordpress.stackexchange.com/questions/316624", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/111085/" ]
When created a new page or post or columns blocks we get the "Write your story" placeholder. Can this be removed or replaced, in custom blocks? How? [![enter image description here](https://i.stack.imgur.com/XY26Z.png)](https://i.stack.imgur.com/XY26Z.png)
There does seem to be a filter to modify the default: <https://github.com/WordPress/gutenberg/blob/master/lib/client-assets.php#L1574> ``` 'bodyPlaceholder' => apply_filters( 'write_your_story', __( 'Write your story', 'gutenberg' ), $post ), ``` So you should be able to use the WordPress [add\_filter()](https://developer.wordpress.org/reference/functions/add_filter/) function.
316,646
<p>What does this .htaccess do?</p> <p>Am I correct in thinking that all it does is prevent automatic brute force attacks?</p> <p>So, to access the wp-login.php you have to manually type in the URL of the domain so that negates all the bots seeking out wp-login.php</p> <p>Am I correct?</p> <p>Here's the .htaccess rule:</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine on RewriteCond %{REQUEST_METHOD} POST RewriteCond %{HTTP_REFERER} !^https://(.*)?my-domain.com [NC] RewriteCond %{REQUEST_URI} ^(.*)?wp-login\.php(.*)$ [OR] RewriteCond %{REQUEST_URI} ^(.*)?wp-admin$ RewriteRule ^(.*)$ - [F] &lt;/IfModule&gt; </code></pre>
[ { "answer_id": 316648, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": false, "text": "<p>It appears to prevent any POST requests to wp-login.php that aren't made from a page on my-domain.com. ...
2018/10/14
[ "https://wordpress.stackexchange.com/questions/316646", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93691/" ]
What does this .htaccess do? Am I correct in thinking that all it does is prevent automatic brute force attacks? So, to access the wp-login.php you have to manually type in the URL of the domain so that negates all the bots seeking out wp-login.php Am I correct? Here's the .htaccess rule: ``` <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{REQUEST_METHOD} POST RewriteCond %{HTTP_REFERER} !^https://(.*)?my-domain.com [NC] RewriteCond %{REQUEST_URI} ^(.*)?wp-login\.php(.*)$ [OR] RewriteCond %{REQUEST_URI} ^(.*)?wp-admin$ RewriteRule ^(.*)$ - [F] </IfModule> ```
It appears to prevent any POST requests to wp-login.php that aren't made from a page on my-domain.com. When the browser sends a POST request, say after submitting a form, it will include a HTTP Referrer header telling the server where the request came from. This theoretically prevents bots submitting POST requests directly to wp-login.php as part of a brute force attack, but the HTTP referrer is trivial to fake, so it's not actually all that helpful.
316,686
<p>wordpress's default Recent Comments widget is showing the user's email address instead of their display/first name.. </p> <p>get_comment_author() just changes the email address to 'anonymous'....</p> <p>What do I change exactly to make it show the commenter's name instead?</p> <pre><code>$output .= sprintf( _x( '%1$s on %2$s', 'widgets' ), '' . get_comment_author_link( $comment ) . '', '&lt;a href="' . esc_url( get_comment_link( $comment ) ) . '"&gt;' . get_the_title( $comment-&gt;comment_post_ID ) . '&lt;/a&gt;' ); </code></pre>
[ { "answer_id": 316648, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": false, "text": "<p>It appears to prevent any POST requests to wp-login.php that aren't made from a page on my-domain.com. ...
2018/10/15
[ "https://wordpress.stackexchange.com/questions/316686", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134482/" ]
wordpress's default Recent Comments widget is showing the user's email address instead of their display/first name.. get\_comment\_author() just changes the email address to 'anonymous'.... What do I change exactly to make it show the commenter's name instead? ``` $output .= sprintf( _x( '%1$s on %2$s', 'widgets' ), '' . get_comment_author_link( $comment ) . '', '<a href="' . esc_url( get_comment_link( $comment ) ) . '">' . get_the_title( $comment->comment_post_ID ) . '</a>' ); ```
It appears to prevent any POST requests to wp-login.php that aren't made from a page on my-domain.com. When the browser sends a POST request, say after submitting a form, it will include a HTTP Referrer header telling the server where the request came from. This theoretically prevents bots submitting POST requests directly to wp-login.php as part of a brute force attack, but the HTTP referrer is trivial to fake, so it's not actually all that helpful.
316,698
<p>I'm using this code to try and check the last post on each page loop is even so i can add different classes.</p> <p>This works to check if its the last post :</p> <pre><code>( ( 1 == $wp_query-&gt;current_post + 1 ) == $wp_query-&gt;post_count ) </code></pre> <p>This works to check if its a even post</p> <pre><code>( $wp_query-&gt;current_post % 2 == 0 ) </code></pre> <p>But this doesn't check if its the last post and even.</p> <pre><code> ( ( 1 == $wp_query-&gt;current_post + 1 ) == $wp_query-&gt;post_count ) &amp;&amp; ( $wp_query-&gt;current_post % 2 == 0 ); </code></pre> <p>The problem i have is i want to display posts in columns and avoid the last post displaying in a column with a gap when there's a even amount of posts.</p>
[ { "answer_id": 316648, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": false, "text": "<p>It appears to prevent any POST requests to wp-login.php that aren't made from a page on my-domain.com. ...
2018/10/15
[ "https://wordpress.stackexchange.com/questions/316698", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/110232/" ]
I'm using this code to try and check the last post on each page loop is even so i can add different classes. This works to check if its the last post : ``` ( ( 1 == $wp_query->current_post + 1 ) == $wp_query->post_count ) ``` This works to check if its a even post ``` ( $wp_query->current_post % 2 == 0 ) ``` But this doesn't check if its the last post and even. ``` ( ( 1 == $wp_query->current_post + 1 ) == $wp_query->post_count ) && ( $wp_query->current_post % 2 == 0 ); ``` The problem i have is i want to display posts in columns and avoid the last post displaying in a column with a gap when there's a even amount of posts.
It appears to prevent any POST requests to wp-login.php that aren't made from a page on my-domain.com. When the browser sends a POST request, say after submitting a form, it will include a HTTP Referrer header telling the server where the request came from. This theoretically prevents bots submitting POST requests directly to wp-login.php as part of a brute force attack, but the HTTP referrer is trivial to fake, so it's not actually all that helpful.
316,705
<p>I want to use different logo for my home page and another logo for others page in wordpress.what will be the changes in header file and css.Currently i am using terminus theme.</p>
[ { "answer_id": 316712, "author": "Pratik Patel", "author_id": 143123, "author_profile": "https://wordpress.stackexchange.com/users/143123", "pm_score": 2, "selected": false, "text": "<p>You can do that using condition in your header file like</p>\n\n<pre><code>if(is_front_page() || is_ho...
2018/10/15
[ "https://wordpress.stackexchange.com/questions/316705", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152343/" ]
I want to use different logo for my home page and another logo for others page in wordpress.what will be the changes in header file and css.Currently i am using terminus theme.
You can do that using condition in your header file like ``` if(is_front_page() || is_home()) { // PUT YOUR HOME PAGE LOGO HERE }else{ // PUT LOGO FOR INNER PAGES } ``` Hope it will help you!
316,719
<p>I am developing a custom Gutenberg block with the PanelColorSettings component to set up the background color, here is my code</p> <pre><code>&lt;PanelColorSettings title={ __( 'Color Settings' ) } colorSettings={ [ { value: backgroundColor, onChange: ( colorValue ) =&gt; setAttributes( { backgroundColor: colorValue } ), label: __( 'Background Color' ), }, ] } &gt; &lt;/PanelColorSettings&gt; </code></pre> <p>How do I the color name instead of the color code for the backgroundColor attribute? It seems the default returned value is the color code which is useless in future color code updates as the content would need to be re-saved.</p>
[ { "answer_id": 319664, "author": "Till", "author_id": 154359, "author_profile": "https://wordpress.stackexchange.com/users/154359", "pm_score": 2, "selected": false, "text": "<p>I could solve it with the function getColorObjectByColorValue (<a href=\"https://github.com/WordPress/gutenber...
2018/10/15
[ "https://wordpress.stackexchange.com/questions/316719", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152355/" ]
I am developing a custom Gutenberg block with the PanelColorSettings component to set up the background color, here is my code ``` <PanelColorSettings title={ __( 'Color Settings' ) } colorSettings={ [ { value: backgroundColor, onChange: ( colorValue ) => setAttributes( { backgroundColor: colorValue } ), label: __( 'Background Color' ), }, ] } > </PanelColorSettings> ``` How do I the color name instead of the color code for the backgroundColor attribute? It seems the default returned value is the color code which is useless in future color code updates as the content would need to be re-saved.
I could solve it with the function getColorObjectByColorValue ([take a look at the gutenberg files](https://github.com/WordPress/gutenberg/blob/9297fc93a2c7b47575007127ffe038d22101de81/packages/editor/src/components/colors/utils.js)). If you have something like ``` const backgroundColors = [ { name: 'Light Green', slug: 'light-green', color: '#E6F0F0' }, { name: 'Light Gray', slug: 'light-gray', color: '#F7F7F7' } ]; ``` then you can get the color name by ``` const test = getColorObjectByColorValue(backgroundColors, backgroundColor); console.log(test.name); ``` Should also work with the default palette.
316,777
<p>I have imported a large amount of content using WPAllImport, all to a custom post type called "article" ("Articles") and all organised by a custom taxonomy type called "source" ("Sources").</p> <p>However, on the edit-tags.php page for the Sources taxonomy listing, the Articles post counts are all inaccurate.</p> <p>There is one term which shows as only having three Articles against it but, on the post index for Articles with that Source, it clearly has 1,997.</p> <p>How can I fix all the counts?</p> <p>I have tried to use <code>wp_update_term_count_now</code></p> <p>I tried ...</p> <pre><code>$update_taxonomy = 'source'; $get_terms_args = array( 'taxonomy' =&gt; $update_taxonomy, 'fields' =&gt; 'ids', 'hide_empty' =&gt; false, ); $update_terms = get_terms($get_terms_args); wp_update_term_count_now($update_terms, $update_taxonomy); </code></pre> <p>(<a href="https://wordpress.stackexchange.com/questions/10953/fixing-category-count">via</a>)</p> <p>and the kitchen sink ...</p> <pre><code>$taxonomies = get_taxonomies(); foreach( $taxonomies as $taxonomy ) { $args = array( 'hide_empty' =&gt; 0, 'fields' =&gt; 'ids' ); $terms = get_terms( $taxonomy, $args ); if( is_array( $terms ) &amp;&amp; !empty( $terms ) ) wp_update_term_count_now( $terms, $taxonomy ); } </code></pre> <p>(<a href="https://alley.co/news/large-custom-wordpress-content-migrations/" rel="nofollow noreferrer">via</a>)</p> <p>But neither seems to do anything.</p> <p>I put the code in a header.php theme file just to execute.</p>
[ { "answer_id": 317517, "author": "Robert Andrews", "author_id": 39300, "author_profile": "https://wordpress.stackexchange.com/users/39300", "pm_score": 2, "selected": false, "text": "<p>The question arose out of misinterpretation...</p>\n\n<p>On the taxonomy list in question, the Count n...
2018/10/15
[ "https://wordpress.stackexchange.com/questions/316777", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/39300/" ]
I have imported a large amount of content using WPAllImport, all to a custom post type called "article" ("Articles") and all organised by a custom taxonomy type called "source" ("Sources"). However, on the edit-tags.php page for the Sources taxonomy listing, the Articles post counts are all inaccurate. There is one term which shows as only having three Articles against it but, on the post index for Articles with that Source, it clearly has 1,997. How can I fix all the counts? I have tried to use `wp_update_term_count_now` I tried ... ``` $update_taxonomy = 'source'; $get_terms_args = array( 'taxonomy' => $update_taxonomy, 'fields' => 'ids', 'hide_empty' => false, ); $update_terms = get_terms($get_terms_args); wp_update_term_count_now($update_terms, $update_taxonomy); ``` ([via](https://wordpress.stackexchange.com/questions/10953/fixing-category-count)) and the kitchen sink ... ``` $taxonomies = get_taxonomies(); foreach( $taxonomies as $taxonomy ) { $args = array( 'hide_empty' => 0, 'fields' => 'ids' ); $terms = get_terms( $taxonomy, $args ); if( is_array( $terms ) && !empty( $terms ) ) wp_update_term_count_now( $terms, $taxonomy ); } ``` ([via](https://alley.co/news/large-custom-wordpress-content-migrations/)) But neither seems to do anything. I put the code in a header.php theme file just to execute.
It only took 3.5-years for someone to be put into the position of @robert-andrews to chase down the post count problem. While having the same problem (and misinterpretation), I ran across your post yesterday in my search for answers. Nothing good really turned up. So, I was forced to trace the code and take the long way home in figuring out what's going on. (Though there are other related posts [here](https://wordpress.stackexchange.com/questions/10953/fixing-category-count) and [here](https://wordpress.stackexchange.com/questions/126691/count-number-of-post-in-taxonomy) that touch on this subject, there is no "good" answer on the [StackExchange family of sites](https://stackexchange.com/search?q=update_post_term_count_statuses) or [StackOverflow](https://stackoverflow.com/search?q=update_post_term_count_statuses).) You'll notice taxonomies generally appear under the admin menu of the post type to which they have been registered. That's important to note because `wp-admin/edit-tags.php` only shows post counts of the type under which the page is nested. (Hint: look in the URL, and you'll see the slug of that post type.) Next, my tracing took me a private function [`_update_post_term_count()`](https://core.trac.wordpress.org/browser/tags/5.9/src/wp-includes/taxonomy.php#L4018). What I found is that the count is [stored in the database](https://core.trac.wordpress.org/browser/tags/5.9/src/wp-includes/taxonomy.php#L4067), not calculated dynamically. In other words, no results will be seen simply by doing a bit of coding and refreshing the page: a post associated with the taxonomy must be saved in order to manifest any results. (What a silly thing to do considering the limited number of times the count is accessed and the fact that post counts are dynamic in the admin table view counts.) Anyway, back to `_update_post_term_count()`: it will only save posts of the specific post type *that have published status*. This was particularly distressing to me because I have a custom post status for a custom post type that is categorized by a custom taxonomy. Well, the [`update_post_term_count_statuses` hook](https://core.trac.wordpress.org/browser/tags/5.9/src/wp-includes/taxonomy.php#L4041) is what solves that problem. Here's a bit of shorthand of how I solved my problem of counting posts appearing in my CPT admin table "All" view: ``` add_filter('update_post_term_count_statuses', function($post_statuses, $taxonomy) { // Intercept if($taxonomy->name === 'mort-custom-taxonomy') { foreach(array( // Some post statuses to be included in the count ... 'mort-custom-post-status', 'draft', 'pending', 'private' ) as $v) { // Check to ensure another call hasn't already added the status. if(!in_array($v, $post_statuses)) { $post_statuses[] = $v; } } } // Return return $post_statuses; }, 10, 2); ``` Here's how the filter above would be called: `_update_post_term_count()` is executed by `wp_update_term_count_now()` when `wp_update_term_count()` is put into effect by `wp_set_object_terms()` and `_update_term_count_on_transition_post_status()` at the time a post is created/updated/published. One final important note so you don't drive yourself crazy. After implementing the filter, the count of a term will not be updated until (as you might have guessed) a post related to that term is created/updated/published.
316,782
<p>Please help me to figure this out that I want to show <strong>thumbnails along with recent post from a wordpress blog on static website's homepage</strong>. </p> <p>Following code are working fine but I need to show one single image from post as thumbnail:</p> <blockquote> <pre><code>&lt;?php define('WP_USE_THEMES', false); require('blog/wp-blog-header.php'); ?&gt; &lt;?php $args = array( 'numberposts' =&gt; 3, 'post_status'=&gt;"publish",'post_type'=&gt;"post",'orderby'=&gt;"post_date"); $postslist = get_posts( $args ); foreach ($postslist as $post) : setup_postdata($post);?&gt; // Here I want to show post's thumbnail &lt;h4 class="post-modern-title"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;/h4&gt; &lt;p class="post-short-info"&gt; // Here I want to show post's short info &lt;/p&gt; &lt;?php endforeach; ?&gt; </code></pre> </blockquote> <p><strong>Right now it is showing like this :-</strong> </p> <blockquote> <p><a href="https://i.stack.imgur.com/jS3k1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jS3k1.png" alt="enter image description here"></a></p> </blockquote> <p><strong>But I want to show like this :-</strong></p> <p><a href="https://i.stack.imgur.com/DAVyI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DAVyI.png" alt="enter image description here"></a></p> <p><strong>Here are the updated code :-</strong></p> <pre><code>&lt;?php define('WP_USE_THEMES', false); require('blog/wp-blog-header.php'); ?&gt; &lt;div class="row row-60 row-sm"&gt; &lt;?php $args = array( 'numberposts' =&gt; 3, 'post_status'=&gt;"publish",'post_type'=&gt;"post",'orderby'=&gt;"post_date"); $postslist = get_posts( $args ); foreach ($postslist as $post) : setup_postdata($post);?&gt; &lt;div class="col-sm-6 col-lg-4 wow fadeInLeft"&gt; &lt;!-- Post Modern--&gt; &lt;article class="post post-modern"&gt;&lt;a class="post-modern-figure" href="&lt;?php the_permalink( $post-&gt;ID ); ?&gt;" target="_top"&gt; &lt;?php echo get_the_post_thumbnail( $post-&gt;ID ); ?&gt; &lt;div class="post-modern-time"&gt; &lt;!-- &lt;time datetime=""&gt;&lt;span class="post-modern-time-month"&gt;07&lt;/span&gt;&lt;span class="post-modern-time-number"&gt;04&lt;/span&gt;&lt;/time&gt; --&gt; &lt;time datetime=""&gt;&lt;span class="post-modern-time-number"&gt;&lt;?php echo the_date( 'd/m' ); ?&gt;&lt;/span&gt;&lt;/time&gt; &lt;/div&gt;&lt;/a&gt; &lt;h4 class="post-modern-title"&gt;&lt;a href="&lt;?php the_permalink( $post-&gt;ID ); ?&gt;" target="_top"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h4&gt; &lt;p class="post-modern-text"&gt;&lt;?php the_excerpt(); ?&gt;&lt;/p&gt; &lt;/article&gt; &lt;/div&gt; &lt;?php endforeach; ?&gt; &lt;/div&gt; </code></pre> <p><strong>I'm getting following output where I'm unable to see date in a single post:-</strong></p> <p><a href="https://i.stack.imgur.com/TnUpN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TnUpN.png" alt="enter image description here"></a></p>
[ { "answer_id": 317517, "author": "Robert Andrews", "author_id": 39300, "author_profile": "https://wordpress.stackexchange.com/users/39300", "pm_score": 2, "selected": false, "text": "<p>The question arose out of misinterpretation...</p>\n\n<p>On the taxonomy list in question, the Count n...
2018/10/15
[ "https://wordpress.stackexchange.com/questions/316782", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152395/" ]
Please help me to figure this out that I want to show **thumbnails along with recent post from a wordpress blog on static website's homepage**. Following code are working fine but I need to show one single image from post as thumbnail: > > > ``` > <?php > define('WP_USE_THEMES', false); > require('blog/wp-blog-header.php'); > ?> > > <?php > $args = array( 'numberposts' => 3, 'post_status'=>"publish",'post_type'=>"post",'orderby'=>"post_date"); > $postslist = get_posts( $args ); > foreach ($postslist as $post) : setup_postdata($post);?> > > // Here I want to show post's thumbnail > > <h4 class="post-modern-title"> > <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> > </h4> > <p class="post-short-info"> > > // Here I want to show post's short info > > </p> > <?php endforeach; ?> > > ``` > > **Right now it is showing like this :-** > > [![enter image description here](https://i.stack.imgur.com/jS3k1.png)](https://i.stack.imgur.com/jS3k1.png) > > > **But I want to show like this :-** [![enter image description here](https://i.stack.imgur.com/DAVyI.png)](https://i.stack.imgur.com/DAVyI.png) **Here are the updated code :-** ``` <?php define('WP_USE_THEMES', false); require('blog/wp-blog-header.php'); ?> <div class="row row-60 row-sm"> <?php $args = array( 'numberposts' => 3, 'post_status'=>"publish",'post_type'=>"post",'orderby'=>"post_date"); $postslist = get_posts( $args ); foreach ($postslist as $post) : setup_postdata($post);?> <div class="col-sm-6 col-lg-4 wow fadeInLeft"> <!-- Post Modern--> <article class="post post-modern"><a class="post-modern-figure" href="<?php the_permalink( $post->ID ); ?>" target="_top"> <?php echo get_the_post_thumbnail( $post->ID ); ?> <div class="post-modern-time"> <!-- <time datetime=""><span class="post-modern-time-month">07</span><span class="post-modern-time-number">04</span></time> --> <time datetime=""><span class="post-modern-time-number"><?php echo the_date( 'd/m' ); ?></span></time> </div></a> <h4 class="post-modern-title"><a href="<?php the_permalink( $post->ID ); ?>" target="_top"><?php the_title(); ?></a></h4> <p class="post-modern-text"><?php the_excerpt(); ?></p> </article> </div> <?php endforeach; ?> </div> ``` **I'm getting following output where I'm unable to see date in a single post:-** [![enter image description here](https://i.stack.imgur.com/TnUpN.png)](https://i.stack.imgur.com/TnUpN.png)
It only took 3.5-years for someone to be put into the position of @robert-andrews to chase down the post count problem. While having the same problem (and misinterpretation), I ran across your post yesterday in my search for answers. Nothing good really turned up. So, I was forced to trace the code and take the long way home in figuring out what's going on. (Though there are other related posts [here](https://wordpress.stackexchange.com/questions/10953/fixing-category-count) and [here](https://wordpress.stackexchange.com/questions/126691/count-number-of-post-in-taxonomy) that touch on this subject, there is no "good" answer on the [StackExchange family of sites](https://stackexchange.com/search?q=update_post_term_count_statuses) or [StackOverflow](https://stackoverflow.com/search?q=update_post_term_count_statuses).) You'll notice taxonomies generally appear under the admin menu of the post type to which they have been registered. That's important to note because `wp-admin/edit-tags.php` only shows post counts of the type under which the page is nested. (Hint: look in the URL, and you'll see the slug of that post type.) Next, my tracing took me a private function [`_update_post_term_count()`](https://core.trac.wordpress.org/browser/tags/5.9/src/wp-includes/taxonomy.php#L4018). What I found is that the count is [stored in the database](https://core.trac.wordpress.org/browser/tags/5.9/src/wp-includes/taxonomy.php#L4067), not calculated dynamically. In other words, no results will be seen simply by doing a bit of coding and refreshing the page: a post associated with the taxonomy must be saved in order to manifest any results. (What a silly thing to do considering the limited number of times the count is accessed and the fact that post counts are dynamic in the admin table view counts.) Anyway, back to `_update_post_term_count()`: it will only save posts of the specific post type *that have published status*. This was particularly distressing to me because I have a custom post status for a custom post type that is categorized by a custom taxonomy. Well, the [`update_post_term_count_statuses` hook](https://core.trac.wordpress.org/browser/tags/5.9/src/wp-includes/taxonomy.php#L4041) is what solves that problem. Here's a bit of shorthand of how I solved my problem of counting posts appearing in my CPT admin table "All" view: ``` add_filter('update_post_term_count_statuses', function($post_statuses, $taxonomy) { // Intercept if($taxonomy->name === 'mort-custom-taxonomy') { foreach(array( // Some post statuses to be included in the count ... 'mort-custom-post-status', 'draft', 'pending', 'private' ) as $v) { // Check to ensure another call hasn't already added the status. if(!in_array($v, $post_statuses)) { $post_statuses[] = $v; } } } // Return return $post_statuses; }, 10, 2); ``` Here's how the filter above would be called: `_update_post_term_count()` is executed by `wp_update_term_count_now()` when `wp_update_term_count()` is put into effect by `wp_set_object_terms()` and `_update_term_count_on_transition_post_status()` at the time a post is created/updated/published. One final important note so you don't drive yourself crazy. After implementing the filter, the count of a term will not be updated until (as you might have guessed) a post related to that term is created/updated/published.
316,853
<p>I'd like to be have more control on the srcset on certain important images of my website if not all.</p> <p>By default the srcset includes all the sizes created by wordpress for all the images. I'd like to be able to choose which sizes will be taken among all the different sizes created by wordpress.</p> <p>To be very clear here is an example : - I have lots of thumbnails images in a page listing all my articles. - maximum width of this thumbnail : 250px taking count of all the different screens and resolutions - I upload my thumbnail at a resolution much higher than needed lets say 2000px wide. In my case 10 images are generated at these sizes :</p> <pre><code>thumbnail (150x150) medium (600x600) medium_large (700x700) large (800x800) featured-blog (719x1020) featured-blog-mobile-3x (1350x1915) pleine-largeur (910x910) colonne (460x460) encart (340x240) mini-size (300x300) thumbnail-blog (246x180) thumbnail-blog-mobile-3x (500x365) In mobile 3x (pixel density) The image used is much too heavy : </code></pre> <p>250px X 3 = 750px. Consequently it loads this one "large (800x800)" I want to avoid such a big image to be used as I have 70 images of that kind on the page. The page weight 30MO. Much too much !</p> <p>So what I'd need is to define among the different sizes served in the srcset which one I want to include and exclude the one I don't want.</p> <p>Thanks already, I would be so thankful if you could help me on this one</p> <p>François</p>
[ { "answer_id": 316881, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>There is a filter <code>max_srcset_image_width</code> that lets you limit the sizes used in a <code>src...
2018/10/16
[ "https://wordpress.stackexchange.com/questions/316853", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152357/" ]
I'd like to be have more control on the srcset on certain important images of my website if not all. By default the srcset includes all the sizes created by wordpress for all the images. I'd like to be able to choose which sizes will be taken among all the different sizes created by wordpress. To be very clear here is an example : - I have lots of thumbnails images in a page listing all my articles. - maximum width of this thumbnail : 250px taking count of all the different screens and resolutions - I upload my thumbnail at a resolution much higher than needed lets say 2000px wide. In my case 10 images are generated at these sizes : ``` thumbnail (150x150) medium (600x600) medium_large (700x700) large (800x800) featured-blog (719x1020) featured-blog-mobile-3x (1350x1915) pleine-largeur (910x910) colonne (460x460) encart (340x240) mini-size (300x300) thumbnail-blog (246x180) thumbnail-blog-mobile-3x (500x365) In mobile 3x (pixel density) The image used is much too heavy : ``` 250px X 3 = 750px. Consequently it loads this one "large (800x800)" I want to avoid such a big image to be used as I have 70 images of that kind on the page. The page weight 30MO. Much too much ! So what I'd need is to define among the different sizes served in the srcset which one I want to include and exclude the one I don't want. Thanks already, I would be so thankful if you could help me on this one François
There is a filter `max_srcset_image_width` that lets you limit the sizes used in a `srcset` attribute to those that are less than a given maximum width. This code will make it so that only sizes < 500 pixels wide will be used in the `srcset`: ``` /** * @param int $max_width The maximum image width to be included in the 'srcset'. Default '1600'. * @param array $size_array Array of width and height values in pixels (in that order). */ function wpse_316853_srcset_maximum_width( $max_srcset_image_width, $sizes_array ) { return 500; } add_filter( 'max_srcset_image_width', 'wpse_316853_srcset_maximum_width', 10, 2 ); ``` In your case though, you might only want to apply this limit when the original image is your 250px wide thumbnail. `$sizes_array` contains the sizes of the current image, so you can use that to check: ``` /** * @param int $max_width The maximum image width to be included in the 'srcset'. Default '1600'. * @param array $size_array Array of width and height values in pixels (in that order). */ function wpse_316853_srcset_maximum_width( $max_srcset_image_width, $sizes_array ) { if ( $sizes_array[0] === 250 ) { $max_srcset_image_width = 500; } return $max_srcset_image_width; } add_filter( 'max_srcset_image_width', 'wpse_316853_srcset_maximum_width' ); ``` Or you could do it dynamically, so that the `srcset` will only include images up to 2x the width of the original image: ``` /** * @param int $max_width The maximum image width to be included in the 'srcset'. Default '1600'. * @param array $size_array Array of width and height values in pixels (in that order). */ function wpse_316853_srcset_maximum_width( $max_srcset_image_width, $sizes_array ) { return $sizes_array[0] * 2; } add_filter( 'max_srcset_image_width', 'wpse_316853_srcset_maximum_width' ); ```
316,890
<p>Forcing www to non-www is simple at the primary domain level.</p> <p>What about at the subdomain level?</p> <p>If I am correct the "issue" is that it is at two levels of depth so you can't force a subdomain to be non-www</p> <p>This is what I mean:</p> <pre><code>https://my.domain.com &lt; correct https://www.my.domain.com &lt; incorrect and trying to force to non-www </code></pre>
[ { "answer_id": 316892, "author": "Coomie", "author_id": 152479, "author_profile": "https://wordpress.stackexchange.com/users/152479", "pm_score": 0, "selected": false, "text": "<p>This would probably only happen if you are erroneously redirecting to www.my.domain.com in your htaccess. So...
2018/10/17
[ "https://wordpress.stackexchange.com/questions/316890", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93691/" ]
Forcing www to non-www is simple at the primary domain level. What about at the subdomain level? If I am correct the "issue" is that it is at two levels of depth so you can't force a subdomain to be non-www This is what I mean: ``` https://my.domain.com < correct https://www.my.domain.com < incorrect and trying to force to non-www ```
> > Forcing www to non-www is simple at the primary domain level. > > > It's actually the same for the subdomain (depending on how you've written the directives in the first place). If the hostname (main domain or subdmomain) starts with `www.` then remove it. (Forcing non-www to www for subdomains *and* main domains is a little more tricky if you want a generic single directive solution.) The following removes the `www` subdomain from *any* hostname. ``` RewriteEngine On RewriteCond %{HTTP_HOST} ^www\.(.+) [NC] RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L] ``` In addition... If your subdomains are pointing to subdirectories off the main domain (eg. `example.com/subdomain`) then these subdirectories are probably also accessible and would need to be redirected. (Although search engines shouldn't discover these subdirectories, or the www subdomain for that matter, unless it was *leaked* in some way.)
316,897
<p>I have tried several things but unfortunately do not manage to do it in a good way.</p> <p>I use a while loop to pick up dealers (custom post type) from different countries and provinces. In this loop of dealers I want to categorize them in countries and provinces.</p> <p>The main category of a dealer is a country and then there is the possibility for some countries to select a subcategory, the province.</p> <p>In this way I want to categorize them: <a href="https://imgur.com/D5yEwSw" rel="nofollow noreferrer">Categorized dealers</a></p> <p>As I said, I have tried several things but it does not work exactly as I want. In addition, it is also too much code in my opinion.</p> <p>Code:</p> <pre><code>&lt;?php $titel_categorie_nederland = false; $titel_categorie_belgie = false; $titel_categorie_italie = false; $titel_categorie_polen = false; $titel_categorie_noord_brabant = false; while ( have_posts() ): the_post(); $categories = get_the_category(); $cat_name = $categories[0]-&gt;cat_name; if($cat_name == "Nederland" &amp;&amp; !$titel_categorie_nederland) { ?&gt; &lt;div class="col-lg-12"&gt;&lt;h3&gt;Nederland&lt;/h3&gt;&lt;/div&gt; &lt;?php $titel_categorie_nederland = true; } if($cat_name == "Polen" &amp;&amp; !$titel_categorie_polen) { ?&gt; &lt;div class="col-lg-12"&gt;&lt;h3&gt;Polen&lt;/h3&gt;&lt;/div&gt; &lt;?php $titel_categorie_polen = true; } if($cat_name == "Belgie" &amp;&amp; !$titel_categorie_belgie) { ?&gt; &lt;div class="col-lg-12"&gt;&lt;h3&gt;Belgie&lt;/h3&gt;&lt;/div&gt; &lt;?php $titel_categorie_belgie = true; } if($cat_name == "Italie" &amp;&amp; !$titel_categorie_italie) { ?&gt; &lt;div class="col-lg-12"&gt;&lt;h3&gt;Italie&lt;/h3&gt;&lt;/div&gt; &lt;?php $titel_categorie_italie = true; } ?&gt; &lt;div class="col-lg-4"&gt; &lt;span class="dealer-title"&gt;&lt;?php the_title(); ?&gt;&lt;/span&gt; &lt;span class="dealer-plaats"&gt;&lt;?php the_field('plaats'); ?&gt;&lt;/span&gt; &lt;span class="dealer-plaats"&gt;&lt;?php the_field('telefoonnummer'); ?&gt;&lt;/span&gt; &lt;span class="dealer-plaats"&gt;&lt;?php the_field('website'); ?&gt;&lt;/span&gt; &lt;span class="dealer-plaats"&gt;&lt;?php the_field('e-mailadres'); ?&gt;&lt;/span&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; </code></pre> <p>This code only does the main category (countries) but not the subcategory if there is one. That said it does not work well either.</p> <p>I know that there must be an easier way to realize this. Someone who can steer me in the right direction?</p>
[ { "answer_id": 316892, "author": "Coomie", "author_id": 152479, "author_profile": "https://wordpress.stackexchange.com/users/152479", "pm_score": 0, "selected": false, "text": "<p>This would probably only happen if you are erroneously redirecting to www.my.domain.com in your htaccess. So...
2018/10/17
[ "https://wordpress.stackexchange.com/questions/316897", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/49429/" ]
I have tried several things but unfortunately do not manage to do it in a good way. I use a while loop to pick up dealers (custom post type) from different countries and provinces. In this loop of dealers I want to categorize them in countries and provinces. The main category of a dealer is a country and then there is the possibility for some countries to select a subcategory, the province. In this way I want to categorize them: [Categorized dealers](https://imgur.com/D5yEwSw) As I said, I have tried several things but it does not work exactly as I want. In addition, it is also too much code in my opinion. Code: ``` <?php $titel_categorie_nederland = false; $titel_categorie_belgie = false; $titel_categorie_italie = false; $titel_categorie_polen = false; $titel_categorie_noord_brabant = false; while ( have_posts() ): the_post(); $categories = get_the_category(); $cat_name = $categories[0]->cat_name; if($cat_name == "Nederland" && !$titel_categorie_nederland) { ?> <div class="col-lg-12"><h3>Nederland</h3></div> <?php $titel_categorie_nederland = true; } if($cat_name == "Polen" && !$titel_categorie_polen) { ?> <div class="col-lg-12"><h3>Polen</h3></div> <?php $titel_categorie_polen = true; } if($cat_name == "Belgie" && !$titel_categorie_belgie) { ?> <div class="col-lg-12"><h3>Belgie</h3></div> <?php $titel_categorie_belgie = true; } if($cat_name == "Italie" && !$titel_categorie_italie) { ?> <div class="col-lg-12"><h3>Italie</h3></div> <?php $titel_categorie_italie = true; } ?> <div class="col-lg-4"> <span class="dealer-title"><?php the_title(); ?></span> <span class="dealer-plaats"><?php the_field('plaats'); ?></span> <span class="dealer-plaats"><?php the_field('telefoonnummer'); ?></span> <span class="dealer-plaats"><?php the_field('website'); ?></span> <span class="dealer-plaats"><?php the_field('e-mailadres'); ?></span> </div> <?php endwhile; ?> ``` This code only does the main category (countries) but not the subcategory if there is one. That said it does not work well either. I know that there must be an easier way to realize this. Someone who can steer me in the right direction?
> > Forcing www to non-www is simple at the primary domain level. > > > It's actually the same for the subdomain (depending on how you've written the directives in the first place). If the hostname (main domain or subdmomain) starts with `www.` then remove it. (Forcing non-www to www for subdomains *and* main domains is a little more tricky if you want a generic single directive solution.) The following removes the `www` subdomain from *any* hostname. ``` RewriteEngine On RewriteCond %{HTTP_HOST} ^www\.(.+) [NC] RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L] ``` In addition... If your subdomains are pointing to subdirectories off the main domain (eg. `example.com/subdomain`) then these subdirectories are probably also accessible and would need to be redirected. (Although search engines shouldn't discover these subdirectories, or the www subdomain for that matter, unless it was *leaked* in some way.)
316,927
<p>I am trying to get the post thumbnail image for each accordion or show accordion post thumbnail outside of the loop.</p> <p>Currently, it's setup with image empty but I need each thumb to represent the currently on click accordion. </p> <p>can you add jquery when each accordion click function should add a class on the <code>&lt;div class=" image active"&gt;</code> according to post id on the accordion?</p> <p>Problem Now is that <code>jquery</code> function is not <code>add active class</code> to the <code>&lt;div class="image"&gt;</code> after cick on each accordion?</p> <p><strong>Jquery</strong></p> <pre><code> $('.heading-accordion .top').on('click', function () { var $question = $(this).closest('.heading-accordion '); $('.heading-accordion.open').not($question).each(function () { var $this = $(this); $this.removeClass('open'); $this.find('.bottom').slideUp(); }); if ($question.hasClass('open')) { $question.removeClass('open'); $question.find('.bottom').slideUp(); } else { $question.find('.bottom').slideDown(function () { $question.addClass('open'); }); } }); $('.change-image').on('click', function () { var targetImage = parseInt($(this).attr('data-image')); $('.image-wrapper .image.active').removeClass('active'); $($('.image-wrapper .image').get(targetImage)).addClass('active'); }); $('.accordion-steps .change-image').on('click', function () { var targetImage = parseInt($(this).attr('data-image')); $('.accordion-steps .image-wrapper .image.active').removeClass('active'); $($('.accordion-steps .image-wrapper .image').get(targetImage)).addClass('active'); }); </code></pre> <p><strong>Html and Wordpress Code</strong></p> <pre><code> &lt;section class="steps accordion-steps"&gt; &lt;div class="row"&gt; &lt;?php $posts_counter = 0; $dataimg = ''; $open = 0; $args = array( 'post_type' =&gt; 'servicesaccordion', 'orderby' =&gt; 'id', 'order' =&gt; 'DESC', 'post_status' =&gt; 'publish' ); $myposts = new WP_Query( $args ); ?&gt; &lt;?php if ($myposts-&gt;have_posts() ) { echo ' &lt;div class="small-12 medium-7 large-5 column steps-wrapper e-in"&gt;'; $i = 0; // Always start the list with a div.row /* Start the Loop */ while ($myposts -&gt;have_posts() ) { $myposts -&gt;the_post(); $i++; $dataimg++; $open++; ?&gt; &lt;div&gt; &lt;div class="heading-accordion &lt;?php if($open == 1){echo 'open';} ?&gt; delay-&lt;?php echo $i ?&gt; change-image" data-image="&lt;?php echo $dataimg ?&gt;" data-id="&lt;?php echo get_the_ID();?&gt;"&gt; &lt;div class="top"&gt; &lt;div class="deco-wrapper"&gt; &lt;div class="inner-wrapper"&gt;&lt;/div&gt; &lt;/div&gt; &lt;?php the_title();?&gt; &lt;/div&gt; &lt;div class="bottom" &lt;?php if($open == 1){echo 'style="display: block;"';} ?&gt; &lt;div class="inner-wrapper"&gt; &lt;p&gt;&lt;?php the_content();?&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php $images_html_array[] = get_the_ID(); } // end of the while() loop wp_reset_postdata(); echo ' &lt;/div&gt; '; echo ' &lt;div class="small-12 medium-5 column"&gt; &lt;div class="image-wrapper e-in"&gt; &lt;div class="image active"&gt; &lt;!--Post Iamge Will Show Herre According To The Posts--&gt; &lt;img class="lazy" data-src="https://via.placeholder.com/639x504" alt="" /&gt; &lt;/div&gt; &lt;div class="image"&gt; &lt;!--Post Iamge Will Show Herre According To The Posts--&gt; &lt;img class="lazy" data-src="https://via.placeholder.com/639x510" alt="" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; '; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; </code></pre>
[ { "answer_id": 316929, "author": "ManzoorWani", "author_id": 113465, "author_profile": "https://wordpress.stackexchange.com/users/113465", "pm_score": -1, "selected": false, "text": "<p>You can use this if you have the <code>$post_id</code></p>\n\n<pre><code>$thumbnail_id = get_post_thum...
2018/10/17
[ "https://wordpress.stackexchange.com/questions/316927", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24510/" ]
I am trying to get the post thumbnail image for each accordion or show accordion post thumbnail outside of the loop. Currently, it's setup with image empty but I need each thumb to represent the currently on click accordion. can you add jquery when each accordion click function should add a class on the `<div class=" image active">` according to post id on the accordion? Problem Now is that `jquery` function is not `add active class` to the `<div class="image">` after cick on each accordion? **Jquery** ``` $('.heading-accordion .top').on('click', function () { var $question = $(this).closest('.heading-accordion '); $('.heading-accordion.open').not($question).each(function () { var $this = $(this); $this.removeClass('open'); $this.find('.bottom').slideUp(); }); if ($question.hasClass('open')) { $question.removeClass('open'); $question.find('.bottom').slideUp(); } else { $question.find('.bottom').slideDown(function () { $question.addClass('open'); }); } }); $('.change-image').on('click', function () { var targetImage = parseInt($(this).attr('data-image')); $('.image-wrapper .image.active').removeClass('active'); $($('.image-wrapper .image').get(targetImage)).addClass('active'); }); $('.accordion-steps .change-image').on('click', function () { var targetImage = parseInt($(this).attr('data-image')); $('.accordion-steps .image-wrapper .image.active').removeClass('active'); $($('.accordion-steps .image-wrapper .image').get(targetImage)).addClass('active'); }); ``` **Html and Wordpress Code** ``` <section class="steps accordion-steps"> <div class="row"> <?php $posts_counter = 0; $dataimg = ''; $open = 0; $args = array( 'post_type' => 'servicesaccordion', 'orderby' => 'id', 'order' => 'DESC', 'post_status' => 'publish' ); $myposts = new WP_Query( $args ); ?> <?php if ($myposts->have_posts() ) { echo ' <div class="small-12 medium-7 large-5 column steps-wrapper e-in">'; $i = 0; // Always start the list with a div.row /* Start the Loop */ while ($myposts ->have_posts() ) { $myposts ->the_post(); $i++; $dataimg++; $open++; ?> <div> <div class="heading-accordion <?php if($open == 1){echo 'open';} ?> delay-<?php echo $i ?> change-image" data-image="<?php echo $dataimg ?>" data-id="<?php echo get_the_ID();?>"> <div class="top"> <div class="deco-wrapper"> <div class="inner-wrapper"></div> </div> <?php the_title();?> </div> <div class="bottom" <?php if($open == 1){echo 'style="display: block;"';} ?> <div class="inner-wrapper"> <p><?php the_content();?></p> </div> </div> </div> <?php $images_html_array[] = get_the_ID(); } // end of the while() loop wp_reset_postdata(); echo ' </div> '; echo ' <div class="small-12 medium-5 column"> <div class="image-wrapper e-in"> <div class="image active"> <!--Post Iamge Will Show Herre According To The Posts--> <img class="lazy" data-src="https://via.placeholder.com/639x504" alt="" /> </div> <div class="image"> <!--Post Iamge Will Show Herre According To The Posts--> <img class="lazy" data-src="https://via.placeholder.com/639x510" alt="" /> </div> </div> </div> '; </div> </div> </section> ```
Off top of my head here's two possible solution concepts. 1) Just run the custom loop (I meant to type, query) again and this time use it with only `the_post_thumbnail`. ``` <?php if ($myposts->have_posts() ) : ?> <div class="image-wrapper e-in"> <?php while ($myposts ->have_posts() ) : $myposts ->the_post(); ?> <div class="image "> <!--Post Iamge Will Show Herre According To The Posts--> <img class="lazy" data-src="<?php the_post_thumbnail_url(); ?>" alt="" /> </div> <?php endwhile; wp_reset_postdata(); ?> </div> <?php endif; ?> ``` 2) Push `get_the_post_thumbnail`'s to a helper array while doing the custom loop. After the custom loop is done, do a `foreach` for the helper array to echo thumbnail html outside the loop. First ``` $myposts = new WP_Query( $args ); images_html_array = array(); ``` Then inside the loop ``` images_html_array[] = get_the_post_thumbnail_url(); ``` Then ``` <div class="image-wrapper e-in"> <?php foreach( $images_html_array as $img_url ) : ?> <div class="image "> <!--Post Iamge Will Show Herre According To The Posts--> <img class="lazy" data-src="<?php echo esc_url( $img_url ); ?>" alt="" /> </div> <?php endforeach; ?> </div> ``` Maybe? These are just rough code examples and I didn't test these yet.
316,932
<p>On the website I'm developing, I need all login-related forms to be on custom, branded pages. I have pretty much covered them all, but I have just one case I can't manage correctly.</p> <p>I have set a custom page for the <em>Lost password?</em> page, by adding the filter below, then creating a new page with a custom template that renders the <em>Insert email to get the link</em> form.</p> <pre><code>function custom_lost_password_page( $lostpassword_url, $redirect ) { return home_url( '/lost-password/' ); } add_filter( 'lostpassword_url', 'custom_lost_password_page', 10, 2 ); </code></pre> <p>On the page template I set a custom <code>redirect_to</code> input field so that the successful request redirects to my custom login page with a specific message.</p> <pre><code>&lt;input type="hidden" name="redirect_to" value="&lt;?= site_url('/login?resetlink=sent') ?&gt;"&gt; </code></pre> <p>So far so good. What I can't seem to intercept, is when the user enter a non-existent email. In that case, no matter what, I get redirected to <code>/wp-login.php?action=lostpassword</code>, which is a native WP page we don't want, with the corresponding error message.</p> <p><a href="https://i.stack.imgur.com/AeBFu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AeBFu.png" alt="Invalid email screen"></a></p> <p>I can't seem to find an action or filter to latch onto in this particular case. Google unfortunately wasn't of help and all similar questions here don't seem to handle this very specific case.</p> <p>Any ideas? Thanks in advance and have a nice day!</p>
[ { "answer_id": 316936, "author": "djboris", "author_id": 152412, "author_profile": "https://wordpress.stackexchange.com/users/152412", "pm_score": 3, "selected": true, "text": "<p>Try this:</p>\n\n<pre><code>add_action( 'lost_password', 'wpse316932_redirect_wrong_email' );\nfunction wpse...
2018/10/17
[ "https://wordpress.stackexchange.com/questions/316932", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107437/" ]
On the website I'm developing, I need all login-related forms to be on custom, branded pages. I have pretty much covered them all, but I have just one case I can't manage correctly. I have set a custom page for the *Lost password?* page, by adding the filter below, then creating a new page with a custom template that renders the *Insert email to get the link* form. ``` function custom_lost_password_page( $lostpassword_url, $redirect ) { return home_url( '/lost-password/' ); } add_filter( 'lostpassword_url', 'custom_lost_password_page', 10, 2 ); ``` On the page template I set a custom `redirect_to` input field so that the successful request redirects to my custom login page with a specific message. ``` <input type="hidden" name="redirect_to" value="<?= site_url('/login?resetlink=sent') ?>"> ``` So far so good. What I can't seem to intercept, is when the user enter a non-existent email. In that case, no matter what, I get redirected to `/wp-login.php?action=lostpassword`, which is a native WP page we don't want, with the corresponding error message. [![Invalid email screen](https://i.stack.imgur.com/AeBFu.png)](https://i.stack.imgur.com/AeBFu.png) I can't seem to find an action or filter to latch onto in this particular case. Google unfortunately wasn't of help and all similar questions here don't seem to handle this very specific case. Any ideas? Thanks in advance and have a nice day!
Try this: ``` add_action( 'lost_password', 'wpse316932_redirect_wrong_email' ); function wpse316932_redirect_wrong_email() { global $errors; if ( $error = $errors->get_error_code() ) { wp_safe_redirect( 'lost-password/?error=' . $error ); } else { wp_safe_redirect( 'lost-password/' ); } } ``` This is utilizing the [`lost_password` action hook](https://developer.wordpress.org/reference/hooks/lost_password/) that fires right before the lost password form. You were experiencing this because WP will only redirect you to the url you specified in `redirect_to` input field when there is no errors. If it finds errors in processing the form (which is the obvious case here), it simply continues with rendering the form on the `wp-login.php` page. By using this action you can hook into this procedure right before that.
316,952
<p>Instead of bogging down my child theme's <code>functions.php</code> file, I would like to have a separate .php file that has various functions, that I can call within <code>functions.php</code> (and in other files).</p> <p>I have created <code>my-custom-functions.php</code> within my child theme, where the <code>functions.php</code> lives. </p> <p>Here's the folder structure:</p> <pre><code>wp-content themes grow-minimal-child functions.php my-custom-functions.php </code></pre> <p>Code for <code>my-custom-functions.php</code>:</p> <pre><code>&lt;?php function js_log($msg){ return "&lt;script type='text/javascript'&gt;alert('$msg');&lt;/script&gt;"; } echo js_log("Hello!"); </code></pre> <p>And the first few lines of <code>functions.php</code>:</p> <pre><code>&lt;?php include_once(get_theme_roots() . '/grow-minimal-child/rs-custom-functions.php'); </code></pre> <p>But, when I load any page, I get this error:</p> <blockquote> <p>Warning: include_once(/themes/grow-minimal-child/my-custom-functions.php): failed to open stream: No such file or directory in /opt/bitnami/apps/wordpress/htdocs/wp-content/themes/grow-minimal-child/functions.php on line 2</p> </blockquote> <p>What do I need to fix, it looks like the <code>include_once</code> is looking for <code>functions.php</code>?</p>
[ { "answer_id": 316955, "author": "BruceWayne", "author_id": 147631, "author_profile": "https://wordpress.stackexchange.com/users/147631", "pm_score": 0, "selected": false, "text": "<p>The error was using <code>get_theme_roots()</code>. This returns a relative path.</p>\n\n<p><code>get_t...
2018/10/17
[ "https://wordpress.stackexchange.com/questions/316952", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147631/" ]
Instead of bogging down my child theme's `functions.php` file, I would like to have a separate .php file that has various functions, that I can call within `functions.php` (and in other files). I have created `my-custom-functions.php` within my child theme, where the `functions.php` lives. Here's the folder structure: ``` wp-content themes grow-minimal-child functions.php my-custom-functions.php ``` Code for `my-custom-functions.php`: ``` <?php function js_log($msg){ return "<script type='text/javascript'>alert('$msg');</script>"; } echo js_log("Hello!"); ``` And the first few lines of `functions.php`: ``` <?php include_once(get_theme_roots() . '/grow-minimal-child/rs-custom-functions.php'); ``` But, when I load any page, I get this error: > > Warning: include\_once(/themes/grow-minimal-child/my-custom-functions.php): failed to open stream: No such file or directory in /opt/bitnami/apps/wordpress/htdocs/wp-content/themes/grow-minimal-child/functions.php on line 2 > > > What do I need to fix, it looks like the `include_once` is looking for `functions.php`?
`get_theme_roots()` and `get_theme_root()` aren't really appropriate functions for getting the path to a file from a theme. I recommend you use [`get_theme_file_path()`](https://developer.wordpress.org/reference/functions/get_theme_file_path/) instead: ``` include_once get_theme_file_path( 'grow-minimal-child/rs-custom-functions.php' ); ```
316,994
<p>I am actually building a custom theme for my blog and I use single quotes for HTML everywhere like:</p> <pre><code>&lt;div class='div'&gt;&lt;/div&gt; </code></pre> <p>Does this cause me redirection to index.php??</p> <p>My site correctly redirects at 301, mod_rewrite is enabled and responses to links but open index.php. Is this because I used single quote??</p>
[ { "answer_id": 316955, "author": "BruceWayne", "author_id": 147631, "author_profile": "https://wordpress.stackexchange.com/users/147631", "pm_score": 0, "selected": false, "text": "<p>The error was using <code>get_theme_roots()</code>. This returns a relative path.</p>\n\n<p><code>get_t...
2018/10/18
[ "https://wordpress.stackexchange.com/questions/316994", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152554/" ]
I am actually building a custom theme for my blog and I use single quotes for HTML everywhere like: ``` <div class='div'></div> ``` Does this cause me redirection to index.php?? My site correctly redirects at 301, mod\_rewrite is enabled and responses to links but open index.php. Is this because I used single quote??
`get_theme_roots()` and `get_theme_root()` aren't really appropriate functions for getting the path to a file from a theme. I recommend you use [`get_theme_file_path()`](https://developer.wordpress.org/reference/functions/get_theme_file_path/) instead: ``` include_once get_theme_file_path( 'grow-minimal-child/rs-custom-functions.php' ); ```
317,003
<p>So I am using nested blocks in Wordpress Gutenberg. I am applying a wrapper on my elements that apply a bootstrap container class. Obviously I'd only want that on the outermost blocks, not on the ones inside a nested block.</p> <p>Is there a way to know if the current block is inside a <code>InnerBlocks</code> Definiton of a parent block? I am currently applying the wrapper inside the <code>blocks.getSaveElement</code> Filter.</p> <p>Is there a better way to do this?</p> <p>For context: In previous gutenberg versions there used to be the layout attribute to achieve that, but it has since been removed. I am using Version 3.9.0.</p> <p>This is a shortened version of my wrapper function:</p> <pre><code> namespace.saveElement = ( element, blockType, attributes ) =&gt; { const hasBootstrapWrapper = hasBlockSupport( blockType.name, 'bootstrapWrapper' ); if (hasBlockSupport( blockType.name, 'anchor' )) { element.props.id = attributes.anchor; } if (hasBootstrapWrapper) { // HERE I NEED TO CHECK IF THE CURRENT ELEMENT IS INSIDE A INNERBLOCKS ELEMENT AND THEN APPLY DIFFERENT WRAPPER var setWrapperInnerClass = wrapperInnerClass; var setWrapperClass = wrapperClass; if (attributes.containerSize) { setWrapperInnerClass = wrapperInnerClass + ' ' + attributes.containerSize; } if (attributes.wrapperType) { setWrapperClass = wrapperClass + ' ' + attributes.wrapperType; } const setWrapperAnchor = (attributes.wrapperAnchor) ? attributes.wrapperAnchor : false; return ( newEl('div', { key: wrapperClass, className: setWrapperClass, id: setWrapperAnchor}, newEl('div', { key: wrapperInnerClass, className: setWrapperInnerClass}, element ) ) ); } else { return element; } }; wp.hooks.addFilter('blocks.getSaveElement', 'namespace/gutenberg', namespace.saveElement); </code></pre>
[ { "answer_id": 346863, "author": "N. Seghir", "author_id": 154459, "author_profile": "https://wordpress.stackexchange.com/users/154459", "pm_score": 3, "selected": false, "text": "<p>you can call <code>getBlockHierarchyRootClientId</code> with the clientId of the block, <code>getBlockHie...
2018/10/18
[ "https://wordpress.stackexchange.com/questions/317003", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/42572/" ]
So I am using nested blocks in Wordpress Gutenberg. I am applying a wrapper on my elements that apply a bootstrap container class. Obviously I'd only want that on the outermost blocks, not on the ones inside a nested block. Is there a way to know if the current block is inside a `InnerBlocks` Definiton of a parent block? I am currently applying the wrapper inside the `blocks.getSaveElement` Filter. Is there a better way to do this? For context: In previous gutenberg versions there used to be the layout attribute to achieve that, but it has since been removed. I am using Version 3.9.0. This is a shortened version of my wrapper function: ``` namespace.saveElement = ( element, blockType, attributes ) => { const hasBootstrapWrapper = hasBlockSupport( blockType.name, 'bootstrapWrapper' ); if (hasBlockSupport( blockType.name, 'anchor' )) { element.props.id = attributes.anchor; } if (hasBootstrapWrapper) { // HERE I NEED TO CHECK IF THE CURRENT ELEMENT IS INSIDE A INNERBLOCKS ELEMENT AND THEN APPLY DIFFERENT WRAPPER var setWrapperInnerClass = wrapperInnerClass; var setWrapperClass = wrapperClass; if (attributes.containerSize) { setWrapperInnerClass = wrapperInnerClass + ' ' + attributes.containerSize; } if (attributes.wrapperType) { setWrapperClass = wrapperClass + ' ' + attributes.wrapperType; } const setWrapperAnchor = (attributes.wrapperAnchor) ? attributes.wrapperAnchor : false; return ( newEl('div', { key: wrapperClass, className: setWrapperClass, id: setWrapperAnchor}, newEl('div', { key: wrapperInnerClass, className: setWrapperInnerClass}, element ) ) ); } else { return element; } }; wp.hooks.addFilter('blocks.getSaveElement', 'namespace/gutenberg', namespace.saveElement); ```
you can call `getBlockHierarchyRootClientId` with the clientId of the block, `getBlockHierarchyRootClientId` will return the parent block id if the current block is inside innerBlocks and will return the same id if it's root you can call it like this ``` wp.data.select( 'core/editor' ).getBlockHierarchyRootClientId( clientId ); ``` additionally, you can define a helper function that you can use in your code ``` const blockHasParent = ( clientId ) => clientId !== wp.data.select( 'core/editor' ).getBlockHierarchyRootClientId( clientId ); if ( blockHasParent( yourClientId ) { .... } ```
317,005
<p>I have like 5 parent pages and would like to echo all their title's on the front page.php. Maybe with get_the_id(); but don't know how.</p>
[ { "answer_id": 317006, "author": "Michael", "author_id": 133863, "author_profile": "https://wordpress.stackexchange.com/users/133863", "pm_score": 1, "selected": false, "text": "<p>Check <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters\" rel=\"nofol...
2018/10/18
[ "https://wordpress.stackexchange.com/questions/317005", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152168/" ]
I have like 5 parent pages and would like to echo all their title's on the front page.php. Maybe with get\_the\_id(); but don't know how.
Check [Post & Page Parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters) or [get\_page\_children()](https://codex.wordpress.org/Function_Reference/get_page_children). ``` <?php global $post; $args = array( 'post_type' => 'page', 'posts_per_page' => -1, 'post_parent' => $post->ID, 'order' => 'ASC', 'orderby' => 'menu_order' ); $parent = new WP_Query( $args ); if ( $parent->have_posts() ) : ?> <?php while ( $parent->have_posts() ) : $parent->the_post(); ?> <div id="parent-<?php the_ID(); ?>" class="parent-page"> <h1><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h1> </div> <?php endwhile; ?> <?php endif; wp_reset_postdata(); ?> ```
317,012
<p>I have tried to update a gallery field and the images shows up in frontend but not the backend.</p> <pre><code>// I have also tried to use the ACF field name like $field = 'field_xxxxxxxxxxxxx'; $field = 'images'; $post_id = 12345; $attachments_ids = [ 0 =&gt; 22222, 1 =&gt; 33333, 2 =&gt; 44444, 3 =&gt; 55555 ]; update_field($field, $attachment_ids, $post_id); </code></pre>
[ { "answer_id": 317006, "author": "Michael", "author_id": 133863, "author_profile": "https://wordpress.stackexchange.com/users/133863", "pm_score": 1, "selected": false, "text": "<p>Check <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters\" rel=\"nofol...
2018/10/18
[ "https://wordpress.stackexchange.com/questions/317012", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9564/" ]
I have tried to update a gallery field and the images shows up in frontend but not the backend. ``` // I have also tried to use the ACF field name like $field = 'field_xxxxxxxxxxxxx'; $field = 'images'; $post_id = 12345; $attachments_ids = [ 0 => 22222, 1 => 33333, 2 => 44444, 3 => 55555 ]; update_field($field, $attachment_ids, $post_id); ```
Check [Post & Page Parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters) or [get\_page\_children()](https://codex.wordpress.org/Function_Reference/get_page_children). ``` <?php global $post; $args = array( 'post_type' => 'page', 'posts_per_page' => -1, 'post_parent' => $post->ID, 'order' => 'ASC', 'orderby' => 'menu_order' ); $parent = new WP_Query( $args ); if ( $parent->have_posts() ) : ?> <?php while ( $parent->have_posts() ) : $parent->the_post(); ?> <div id="parent-<?php the_ID(); ?>" class="parent-page"> <h1><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h1> </div> <?php endwhile; ?> <?php endif; wp_reset_postdata(); ?> ```
317,019
<p>How can I show the title when a checkbox is checked. I use Advanced custom fields</p> <p>my field name is nav</p> <p>This is what i currently have.</p> <pre><code>&lt;?php if(get_field('nav')) { ?&gt; &lt;li&gt; &lt;a href="&lt;?php the_permalink()?&gt;" class="active"&gt;&lt;?php the_title();?&gt;&lt;/a&gt; &lt;/li&gt; &lt;?php } ?&gt; </code></pre>
[ { "answer_id": 317020, "author": "djboris", "author_id": 152412, "author_profile": "https://wordpress.stackexchange.com/users/152412", "pm_score": 0, "selected": false, "text": "<p>You would like to use ACF true/false field > <a href=\"https://www.advancedcustomfields.com/resources/true-...
2018/10/18
[ "https://wordpress.stackexchange.com/questions/317019", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152168/" ]
How can I show the title when a checkbox is checked. I use Advanced custom fields my field name is nav This is what i currently have. ``` <?php if(get_field('nav')) { ?> <li> <a href="<?php the_permalink()?>" class="active"><?php the_title();?></a> </li> <?php } ?> ```
You would like to use ACF true/false field > [link](https://www.advancedcustomfields.com/resources/true-false/) Then basically in your template wrap the title element in conditional, like this: ``` if( get_field( 'title_show_or_whatever' ) ) { // The title element } ```
317,035
<p>I am upgrading Font Awesome 4 to version 5 which introduces both integrity and crossorigin attributes to the <code>&lt;link rel="stylesheet"&gt;</code> markup. </p> <p><em>Currently, I am using:</em></p> <pre><code>wp_register_style('FontAwesome', 'https://example.com/font-awesome.min.css', array(), null, 'all' ); wp_enqueue_style('FontAwesome'); </code></pre> <p><em>Which outputs as:</em></p> <pre><code>&lt;link rel="stylesheet" id="FontAwesome-css" href="https://example.com/font-awesome.min.css" type="text/css" media="all" /&gt; </code></pre> <p><em>With Font Awesome 5 it introduces two new attributes and values (<code>integrity</code> and <code>crossorigin</code>) e.g:</em></p> <pre><code>&lt;link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous"&gt; </code></pre> <p>So I need to find out how I can add both the integrity and crossorigin to wp_register_style, I have tried but my attempts to use <code>wp_style_add_data</code> have failed, it would seem that this method only supports <code>conditional</code>, <code>rtl</code> and <code>suffix</code>, <code>alt</code> and <code>title</code>.</p>
[ { "answer_id": 319773, "author": "Remzi Cavdar", "author_id": 149484, "author_profile": "https://wordpress.stackexchange.com/users/149484", "pm_score": 6, "selected": true, "text": "<p><strong>style_loader_tag</strong><br>\nstyle_loader_tag is an official WordPress API, see the documenta...
2018/10/18
[ "https://wordpress.stackexchange.com/questions/317035", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54879/" ]
I am upgrading Font Awesome 4 to version 5 which introduces both integrity and crossorigin attributes to the `<link rel="stylesheet">` markup. *Currently, I am using:* ``` wp_register_style('FontAwesome', 'https://example.com/font-awesome.min.css', array(), null, 'all' ); wp_enqueue_style('FontAwesome'); ``` *Which outputs as:* ``` <link rel="stylesheet" id="FontAwesome-css" href="https://example.com/font-awesome.min.css" type="text/css" media="all" /> ``` *With Font Awesome 5 it introduces two new attributes and values (`integrity` and `crossorigin`) e.g:* ``` <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous"> ``` So I need to find out how I can add both the integrity and crossorigin to wp\_register\_style, I have tried but my attempts to use `wp_style_add_data` have failed, it would seem that this method only supports `conditional`, `rtl` and `suffix`, `alt` and `title`.
**style\_loader\_tag** style\_loader\_tag is an official WordPress API, see the documentation: <https://developer.wordpress.org/reference/hooks/style_loader_tag/> > > `apply_filters( 'style_loader_tag', $html, $handle, $href, $media )` > Filters the HTML link tag of an enqueued > style. > > > First enqueue your stylesheet, see documentation: <https://developer.wordpress.org/reference/functions/wp_enqueue_style/> ``` wp_enqueue_style( 'font-awesome-5', 'https://use.fontawesome.com/releases/v5.5.0/css/all.css', array(), null ); ``` The `$handle` is `'font-awesome-5'` I do `null` so that there is no version number. This way it will be cached. **Simple str\_replace** A simple str\_replace is enough to achieve what you want, see example below ``` function add_font_awesome_5_cdn_attributes( $html, $handle ) { if ( 'font-awesome-5' === $handle ) { return str_replace( "media='all'", "media='all' integrity='sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU' crossorigin='anonymous'", $html ); } return $html; } add_filter( 'style_loader_tag', 'add_font_awesome_5_cdn_attributes', 10, 2 ); ``` **Add different atributes** Below an example to add different atributes to (multiple) different stylesheets ``` function add_style_attributes( $html, $handle ) { if ( 'font-awesome-5' === $handle ) { return str_replace( "media='all'", "media='all' integrity='sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU' crossorigin='anonymous'", $html ); } if ( 'another-style' === $handle ) { return str_replace( "media='all'", "media='all' integrity='blajbsf' example", $html ); } if ( 'bootstrap-css' === $handle ) { return str_replace( "media='all'", "media='all' integrity='something-different' crossorigin='anonymous'", $html ); } return $html; } add_filter( 'style_loader_tag', 'add_style_attributes', 10, 2 ); ``` **Add attributes to all styles** Below an example to add the same atributes to more than one stylesheet ``` function add_attributes_to_all_styles( $html, $handle ) { // add style handles to the array below $styles = array( 'font-awesome-5', 'another-style', 'bootstrap-css' ); foreach ( $styles as $style ) { if ( $style === $handle ) { return str_replace( "media='all'", "media='all' integrity='sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU' crossorigin='anonymous'", $html ); } } return $html; } add_filter( 'style_loader_tag', 'add_attributes_to_all_styles', 10, 2 ); ``` **script\_loader\_tag** I also would like to explain the script\_loader\_tag, because this is also handy, but this API works in combination with [wp\_enqueue\_script](https://developer.wordpress.org/reference/functions/wp_enqueue_script/). The script\_loader\_tag API is almost the same, only some small differences, see documentation: <https://developer.wordpress.org/reference/hooks/script_loader_tag/> > > `apply_filters( 'script_loader_tag', $tag, $handle, $src )` > Filters the > HTML script tag of an enqueued script. > > > Below an example to defer a single script ``` function add_defer_jquery( $tag, $handle ) { if ( 'jquery' === $handle ) { return str_replace( "src", "defer src", $tag ); } return $tag; } add_filter( 'script_loader_tag', 'add_defer_jquery', 10, 2 ); ``` Below an example to defer more than one script ``` function add_defer_attribute( $tag, $handle ) { // add script handles to the array below $scripts_to_defer = array( 'jquery', 'jquery-migrate', 'bootstrap-bundle-js' ); foreach ( $scripts_to_defer as $defer_script ) { if ( $defer_script === $handle ) { return str_replace( "src", "defer src", $tag ); } } return $tag; } add_filter( 'script_loader_tag', 'add_defer_attribute', 10, 2 ); ``` So I have explained both API's `style_loader_tag` and `script_loader_tag`. And I gave some examples for both API's I hope that this is useful for a lot of people out there. I have experience with both API's. **UPDATE** @CKMacLeod Thank you for your update, this clarifies things. We're mostly on the same page. As I said, I'm a WordPress developer and if you want to publish a theme and/or plugin on <https://wordpress.org> you're essentially forced to abide by the "[WordPress Coding Standards](https://make.wordpress.org/core/handbook/best-practices/coding-standards/)" or they will simply reject your theme and/or plugin. That's why I encourage developers out there to use "the WordPress way". I understand that sometimes there are no differences whatsoever, but it's also convenience. As you said yourself you could download Font Awesome and include it in your theme and/or plugin, this way you would only need to remove the style\_loader\_tag function and modify your wp\_enqueue\_style function. And one last thing, in the past (5 years ago) some caching, combining and minifying plugins didn't work and most of the times I would find out why those developers who made the theme simply put things in the head in the theme and/or echoed them. Most caching plugins, who also (most of the time) provide options to combine, minify and delay execution of scripts became smarter and better at detecting bad code and working around them. But this is not preferred. That's why I encourage people to code with standards/conventions in mind. As a developer, you always need to take into consideration what people could do with your code and taking compatibility in mind. So not taking the easy solution but the best optimal solution. I hope I have clarified my viewpoint. **EDIT** @CKMacLeod Thank you for the (technical) debate, I hope that you realize how important this is (using WordPress API's in your own development). Again, I have been looking around and even now if I look at the FAQ's of most popular minify plugins I usually see this one way or the other, for example: > > **Question:** Why are some of the CSS and JS files not being merged? > > **Answer:** The plugin only processes JS and CSS files enqueued using the > official WordPress API method – > <https://developer.wordpress.org/themes/basics/including-css-javascript/> > -as well as files from the same domain (unless specified on the settings). > > > See FAQ: <https://wordpress.org/plugins/fast-velocity-minify/>
317,056
<p>I'm trying to insert a dropdown (via HTML string) in to every <code>post</code> I have.</p> <p>I'd like to add it before the post information, but below the website nav. bar and header.</p> <p>In the screenshot, you'll notice it's added to the <em>very top</em>. I want it to be moved in the designated area. </p> <p><a href="https://i.stack.imgur.com/o4Vwj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o4Vwj.jpg" alt="enter image description here"></a></p> <p>So, you can see the "Choose an Article" and dropdown are at the top-top. I would like them inserted just before the Content (where <code>&lt;div id="content"&gt;</code>).</p> <p>Current code:</p> <pre><code>add_action('wp_head', 'append_header'); function append_header(){ //Close PHP tags ?&gt; &lt;script type="text/javascript" src="/wp-content/themes/grow-minimal-child/customjs.js"&gt;&lt;/script&gt; &lt;?php //Open PHP tags $args = ['post_type' =&gt; 'post', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1]; $titles = get_post_titles($args); $dropdown = create_dropdown_html($titles); echo $dropdown; } </code></pre> <p>I've tried also using <code>the_content</code> and appending the <code>$dropdown</code> html to that, but this just inserts the drop down after the "Test Post Please Ignore" and post info line. <a href="https://i.stack.imgur.com/9Fevr.jpg" rel="nofollow noreferrer">See this screenshot</a></p> <p>How do I place the code to hook <em>after</em> the header and nav bar, but <em>before</em> the content itself?</p>
[ { "answer_id": 317058, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 2, "selected": false, "text": "<p>Edit your single.php or single-post.php template, depending on which one is present and in use with your them...
2018/10/18
[ "https://wordpress.stackexchange.com/questions/317056", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147631/" ]
I'm trying to insert a dropdown (via HTML string) in to every `post` I have. I'd like to add it before the post information, but below the website nav. bar and header. In the screenshot, you'll notice it's added to the *very top*. I want it to be moved in the designated area. [![enter image description here](https://i.stack.imgur.com/o4Vwj.jpg)](https://i.stack.imgur.com/o4Vwj.jpg) So, you can see the "Choose an Article" and dropdown are at the top-top. I would like them inserted just before the Content (where `<div id="content">`). Current code: ``` add_action('wp_head', 'append_header'); function append_header(){ //Close PHP tags ?> <script type="text/javascript" src="/wp-content/themes/grow-minimal-child/customjs.js"></script> <?php //Open PHP tags $args = ['post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => -1]; $titles = get_post_titles($args); $dropdown = create_dropdown_html($titles); echo $dropdown; } ``` I've tried also using `the_content` and appending the `$dropdown` html to that, but this just inserts the drop down after the "Test Post Please Ignore" and post info line. [See this screenshot](https://i.stack.imgur.com/9Fevr.jpg) How do I place the code to hook *after* the header and nav bar, but *before* the content itself?
Edit your single.php or single-post.php template, depending on which one is present and in use with your theme. The JS file should be registered and conditionally enqueued when the template is loaded. This allows for dependency management and lots of other easy management actions. Another way to consider is make your menu an actual WordPress menu or a widget and register a sidebar in your single.php template. Either way, you have the benefit of managing the content via the CMS as intended. EDIT: your theme is likely making use of body classes which makes it very easy to know which template you need to edit. Look at the body tag and inspect the classes there.
317,061
<p><a href="https://i.stack.imgur.com/ol9wx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ol9wx.png" alt="enter image description here"></a>The client will be entering information for the year a report was produced (eg. 2010). I want to take that information and calculate if it was made in the last 3 years so I can display it in a 'recent documents' section. Any other report that doesn't match the result will be sent to an archives section. Am I thinking through this correctly?</p> <pre><code>&lt;?php if( have_rows('recent_documents') ): ?&gt; &lt;ul class="list-unstyled"&gt; &lt;?php while( have_rows('recent_documents') ): the_row(); ?&gt; &lt;?php if ( have_rows('new_document') ): ?&gt; &lt;?php while ( have_rows('new_document') ): the_row(); ?&gt; &lt;?php $year = the_sub_field('year'); ?&gt; &lt;?php if ( $year &gt; date("Y",strtotime("-1 year"))) : ?&gt; &lt;li&gt; &lt;a href="&lt;?php the_sub_field('file'); ?&gt;" target="blank"&gt;&lt;?php the_sub_field('year'); ?&gt; &lt;?php the_sub_field('report_type'); ?&gt;&lt;span&gt;&lt;i class="fas fa-download"&gt;&lt;/i&gt;&lt;/span&gt;&lt;/a&gt; &lt;/li&gt; &lt;?php endif; ?&gt; &lt;?php endwhile; ?&gt; &lt;?php endif; endwhile; ?&gt; &lt;/ul&gt; &lt;?php endif; ?&gt; </code></pre>
[ { "answer_id": 317058, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 2, "selected": false, "text": "<p>Edit your single.php or single-post.php template, depending on which one is present and in use with your them...
2018/10/18
[ "https://wordpress.stackexchange.com/questions/317061", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152408/" ]
[![enter image description here](https://i.stack.imgur.com/ol9wx.png)](https://i.stack.imgur.com/ol9wx.png)The client will be entering information for the year a report was produced (eg. 2010). I want to take that information and calculate if it was made in the last 3 years so I can display it in a 'recent documents' section. Any other report that doesn't match the result will be sent to an archives section. Am I thinking through this correctly? ``` <?php if( have_rows('recent_documents') ): ?> <ul class="list-unstyled"> <?php while( have_rows('recent_documents') ): the_row(); ?> <?php if ( have_rows('new_document') ): ?> <?php while ( have_rows('new_document') ): the_row(); ?> <?php $year = the_sub_field('year'); ?> <?php if ( $year > date("Y",strtotime("-1 year"))) : ?> <li> <a href="<?php the_sub_field('file'); ?>" target="blank"><?php the_sub_field('year'); ?> <?php the_sub_field('report_type'); ?><span><i class="fas fa-download"></i></span></a> </li> <?php endif; ?> <?php endwhile; ?> <?php endif; endwhile; ?> </ul> <?php endif; ?> ```
Edit your single.php or single-post.php template, depending on which one is present and in use with your theme. The JS file should be registered and conditionally enqueued when the template is loaded. This allows for dependency management and lots of other easy management actions. Another way to consider is make your menu an actual WordPress menu or a widget and register a sidebar in your single.php template. Either way, you have the benefit of managing the content via the CMS as intended. EDIT: your theme is likely making use of body classes which makes it very easy to know which template you need to edit. Look at the body tag and inspect the classes there.
317,073
<p>I checked the HTML validator. But, the message is the following.</p> <blockquote> <p>Quote " in attribute name. Probable cause: Matching quote missing somewhere earlier.</p> </blockquote> <p>The meta description is automatic from the content. So, if the content includes the quotation, it is also included in meta descrption. I would like to strip the quotation.</p> <p>Currently, I inserted the code in header.php as below.</p> <pre><code>$description = strip_shortcodes($description); $description = wp_strip_all_tags($description); </code></pre> <p>What should I add?</p>
[ { "answer_id": 317114, "author": "Heres2u", "author_id": 140036, "author_profile": "https://wordpress.stackexchange.com/users/140036", "pm_score": 1, "selected": false, "text": "<p>Without knowing further details of your specific installation:</p>\n\n<ol>\n<li>Make sure you are actually ...
2018/10/19
[ "https://wordpress.stackexchange.com/questions/317073", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151822/" ]
I checked the HTML validator. But, the message is the following. > > Quote " in attribute name. Probable cause: Matching quote missing > somewhere earlier. > > > The meta description is automatic from the content. So, if the content includes the quotation, it is also included in meta descrption. I would like to strip the quotation. Currently, I inserted the code in header.php as below. ``` $description = strip_shortcodes($description); $description = wp_strip_all_tags($description); ``` What should I add?
Without knowing further details of your specific installation: 1. Make sure you are actually previewing live on the web in a browser to see if the short-code actually is working. 2. Make sure you have spelled the short-code correctly, and have the correct syntax. (See theme's documentation.) 3. If the short-code requires some special JavaScript library, often other plugins that also use JavaScript, can interfere. I've had 3rd party plugins break the default theme functionality on my site. When I deactivate the offending plugin, the theme features work again. 4. Contact the theme developer's support forum or directly for answers. Likely others have the same issue or question. If #1 or #2 or #3 above are not the issue, then the developer or other user in a forum may be able to shed some light on the subject.
317,084
<p>My question is close to other questions, but I dont' have enough reputation to comment.</p> <p>I'm working for a restaurant and I 'd like, for my menu page, to organise my posts "meal" under terms "cat_meal".</p> <p>This terms should respect an order (dessert after starter for example). And that's my probleme : I tried so many snippets, that I don't know which one I should write here... Here are some picture to explain, I hope. <a href="https://i.stack.imgur.com/ARAGT.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ARAGT.jpg" alt="Page menu"></a> <a href="https://i.stack.imgur.com/sgJUl.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sgJUl.jpg" alt="Page menu with comments"></a> But, there is always something wrong : either I can display my term in a right order and my query post is not good. Or meal posts are under the good terms, but, the order of the terms are wrong. Or, worth, nothing happens.</p> <p>Here are two tests, <b>thanks for your time and help</b> :</p> <pre><code>$args_tax = [ 'parent' => 0, 'hide_empty' => 0, 'meta_key' => 'ordre',// I added an ACF with number from 1 to 8 to order 'orderby' => 'meta_value', 'order' => 'ASC' ]; $terms = get_terms('cat_meal', $args_tax); // tax cat_meal // print_r($terms); if (!empty($terms)): foreach ($terms as $term): $argsPost = [ 'post_type' => 'meal',//CPT meal 'posts_per_page' => -1 ]; $query = new WP_Query($argsPost); while ($query->have_posts()) : $query->the_post(); echo $term->name ; the_title(); endwhile; wp_reset_postdata(); // reset the query endforeach; endif; //PROBLEM : under each term, every posts are displaying ! I don't understand why... </code> </pre> <p>Second version from this question <a href="https://wordpress.stackexchange.com/questions/43426/get-all-categories-and-posts-in-those-categories?noredirect=1&amp;lq=1">Get all categories and posts in those categories</a></p> <pre> <code> $args = array( 'post_type' => 'meal', 'posts_per_page' => -1 ); $query = new WP_Query($args); $q = array(); while ( $query->have_posts() ) { $query->the_post(); $a = '' . get_the_title() .''; $terms = wp_get_post_terms( $post->ID, 'cat_meal', $args ); foreach ( $terms as $term) { $term_link = get_term_link( $term ); $b = ''.$term->name.''; } $q[$b][] = $a; } wp_reset_postdata(); foreach ($q as $key=>$values) { echo $key; foreach ($values as $value){ echo $value; } } </code> </pre> <p>The posts are well displaying under the terms, BUT the terms have wrong order (dessert before pizza)</p> <p>I've just found this answer too, but I' dont undetsand wher the taxonomy is declared : <a href="https://wordpress.stackexchange.com/questions/134855/ordering-posts-with-custom-taxonomy-terms-array">Ordering Posts with Custom Taxonomy Terms Array</a>.</p> <p>I would really appreciate some advices into my fog : thanks </p>
[ { "answer_id": 317114, "author": "Heres2u", "author_id": 140036, "author_profile": "https://wordpress.stackexchange.com/users/140036", "pm_score": 1, "selected": false, "text": "<p>Without knowing further details of your specific installation:</p>\n\n<ol>\n<li>Make sure you are actually ...
2018/10/19
[ "https://wordpress.stackexchange.com/questions/317084", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/110465/" ]
My question is close to other questions, but I dont' have enough reputation to comment. I'm working for a restaurant and I 'd like, for my menu page, to organise my posts "meal" under terms "cat\_meal". This terms should respect an order (dessert after starter for example). And that's my probleme : I tried so many snippets, that I don't know which one I should write here... Here are some picture to explain, I hope. [![Page menu](https://i.stack.imgur.com/ARAGT.jpg)](https://i.stack.imgur.com/ARAGT.jpg) [![Page menu with comments](https://i.stack.imgur.com/sgJUl.jpg)](https://i.stack.imgur.com/sgJUl.jpg) But, there is always something wrong : either I can display my term in a right order and my query post is not good. Or meal posts are under the good terms, but, the order of the terms are wrong. Or, worth, nothing happens. Here are two tests, **thanks for your time and help** : ``` $args_tax = [ 'parent' => 0, 'hide_empty' => 0, 'meta_key' => 'ordre',// I added an ACF with number from 1 to 8 to order 'orderby' => 'meta_value', 'order' => 'ASC' ]; $terms = get_terms('cat_meal', $args_tax); // tax cat_meal // print_r($terms); if (!empty($terms)): foreach ($terms as $term): $argsPost = [ 'post_type' => 'meal',//CPT meal 'posts_per_page' => -1 ]; $query = new WP_Query($argsPost); while ($query->have_posts()) : $query->the_post(); echo $term->name ; the_title(); endwhile; wp_reset_postdata(); // reset the query endforeach; endif; //PROBLEM : under each term, every posts are displaying ! I don't understand why... ``` Second version from this question [Get all categories and posts in those categories](https://wordpress.stackexchange.com/questions/43426/get-all-categories-and-posts-in-those-categories?noredirect=1&lq=1) ``` $args = array( 'post_type' => 'meal', 'posts_per_page' => -1 ); $query = new WP_Query($args); $q = array(); while ( $query->have_posts() ) { $query->the_post(); $a = '' . get_the_title() .''; $terms = wp_get_post_terms( $post->ID, 'cat_meal', $args ); foreach ( $terms as $term) { $term_link = get_term_link( $term ); $b = ''.$term->name.''; } $q[$b][] = $a; } wp_reset_postdata(); foreach ($q as $key=>$values) { echo $key; foreach ($values as $value){ echo $value; } } ``` The posts are well displaying under the terms, BUT the terms have wrong order (dessert before pizza) I've just found this answer too, but I' dont undetsand wher the taxonomy is declared : [Ordering Posts with Custom Taxonomy Terms Array](https://wordpress.stackexchange.com/questions/134855/ordering-posts-with-custom-taxonomy-terms-array). I would really appreciate some advices into my fog : thanks
Without knowing further details of your specific installation: 1. Make sure you are actually previewing live on the web in a browser to see if the short-code actually is working. 2. Make sure you have spelled the short-code correctly, and have the correct syntax. (See theme's documentation.) 3. If the short-code requires some special JavaScript library, often other plugins that also use JavaScript, can interfere. I've had 3rd party plugins break the default theme functionality on my site. When I deactivate the offending plugin, the theme features work again. 4. Contact the theme developer's support forum or directly for answers. Likely others have the same issue or question. If #1 or #2 or #3 above are not the issue, then the developer or other user in a forum may be able to shed some light on the subject.
317,102
<p>I try to create a scheduled cron job which runs every hour, Its my first time working with wp-cron.</p> <p>In the cron function, I want to update post meta values, if some conditions are met.</p> <p>I also tested the code of the cron function outside of the cron to see/print the results. The results looked ok, but when the cronjob runs no post gets updated.</p> <p>Iam using WP Crontrol to see the all available cronjobs.</p> <p>First I schedule an event (this seems to works): </p> <pre><code>function prfx_hourly_status_update_cron_job() { if ( ! wp_next_scheduled( 'prfx_run_hourly_status_update_cron_job' ) ) { wp_schedule_event( current_time( 'timestamp' ), 'hourly', 'prfx_run_hourly_status_update_cron_job' ); } } add_action( 'wp', 'prfx_hourly_status_update_cron_job' ); </code></pre> <p>After creating this event I than try to run this function.</p> <p>I get all posts which have a meta field where the value is not empty.<br> This field is an date. (Y-m-d)<br> For each post/product I than get two meta values.<br> The deadline-date and a sooner deadline-soon-date.<br> I than compare the todays date with these saved dates and want to update another meta value based on this. </p> <pre><code>function prfx_run_hourly_status_update_cron_job( ) { // create meta query to get all posts which have a deadline date (field not empty) $args = array( 'posts_per_page' =&gt; -1, 'meta_query' =&gt; array( array( 'key' =&gt; '_prfx_custom_product_deadline', 'value' =&gt; '', 'compare' =&gt; '!=' ), ), 'post_type' =&gt; 'product', 'no_found_rows' =&gt; true, //speeds up a query significantly and can be set to 'true' if we don't use pagination 'fields' =&gt; 'ids', //again, for performance ); $posts_array = get_posts( $args ); // start if we have posts if ($posts_array) { // get todays date in Y-m-d format $today = date('Y-m-d'); //now check conditions and update the code foreach( $posts_array as $post_id ){ $saved_deadline = get_post_meta( $post_id, '_prfx_custom_product_deadline', true ); // get deadline-date $soon_deadline = get_post_meta( $post_id, '_prfx_custom_product_deadline_soon', true );// get deadline-soon-date if ($today &gt; $saved_deadline) { // if today is after deadline update_post_meta( $post_id, '_prfx_custom_product_status', 'deadline-met' ); } elseif ($today &lt; $saved_deadline &amp;&amp; $today &gt; $soon_deadline) { // if today is before deadline but after soon-deadline update_post_meta( $post_id, '_prfx_custom_product_status', 'deadline-soon' ); } } } } </code></pre> <p>As said above I tried to dry run this function, instead of update_post_meta I just printed the data out. This seems to work. Iam also using a similar function to echo out some strings on the frontend, so the date compare also works.</p> <hr> <p>Update: So, I cant get this to work with the cronjobs. I just tested the following code inside an plugin, as I activate the plugin, the code runs. The query is working fine, I printed/checked the results, and it is working as simple plugin code. </p> <p>But the same code is not running in the cronjob. When I look at the cron output with Wp Crontrol, I can see the hourly event "prfx_run_hourly_status_update_cron_job", but without any action assigned. However, for example "woocommerce_geoip_updater" has also no action listed.<br> Maybe someone has an idea why? </p> <p>Here is the tested code: </p> <pre><code>add_action('init','prfx_resave_posts'); function prfx_resave_posts(){ $args = array( 'posts_per_page' =&gt; -1, 'post_type' =&gt; 'product', 'meta_query' =&gt; array( array( 'key' =&gt; '_prfx_custom_product_deadline_soon', 'value' =&gt; '', 'compare' =&gt; '!=' ), ), 'no_found_rows' =&gt; true, //speeds up a query significantly and can be set to 'true' if we don't use pagination 'fields' =&gt; 'ids', //again, for performance ); $posts_array = get_posts( $args ); if ($posts_array) { //output: Array ( [0] =&gt; 120399 [1] =&gt; 120431 [2] =&gt; 120469 [3] =&gt; 120401 [4] =&gt; 120433 ) // get todays date in Y-m-d format $today = date('Y-m-d'); foreach ($posts_array as $my_post) { #print_r($my_post); //output example: 120399 $saved_soon_deadline = get_post_meta( $my_post, '_prfx_custom_product_deadline_soon', true ); #print_r($saved_soon_deadline); //output: 2018-11-30 if ($today &gt; $saved_soon_deadline) { update_post_meta( $my_post, '_prfx_custom_product_status', 'my-new-val-here' ); } } } } </code></pre>
[ { "answer_id": 317114, "author": "Heres2u", "author_id": 140036, "author_profile": "https://wordpress.stackexchange.com/users/140036", "pm_score": 1, "selected": false, "text": "<p>Without knowing further details of your specific installation:</p>\n\n<ol>\n<li>Make sure you are actually ...
2018/10/19
[ "https://wordpress.stackexchange.com/questions/317102", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88895/" ]
I try to create a scheduled cron job which runs every hour, Its my first time working with wp-cron. In the cron function, I want to update post meta values, if some conditions are met. I also tested the code of the cron function outside of the cron to see/print the results. The results looked ok, but when the cronjob runs no post gets updated. Iam using WP Crontrol to see the all available cronjobs. First I schedule an event (this seems to works): ``` function prfx_hourly_status_update_cron_job() { if ( ! wp_next_scheduled( 'prfx_run_hourly_status_update_cron_job' ) ) { wp_schedule_event( current_time( 'timestamp' ), 'hourly', 'prfx_run_hourly_status_update_cron_job' ); } } add_action( 'wp', 'prfx_hourly_status_update_cron_job' ); ``` After creating this event I than try to run this function. I get all posts which have a meta field where the value is not empty. This field is an date. (Y-m-d) For each post/product I than get two meta values. The deadline-date and a sooner deadline-soon-date. I than compare the todays date with these saved dates and want to update another meta value based on this. ``` function prfx_run_hourly_status_update_cron_job( ) { // create meta query to get all posts which have a deadline date (field not empty) $args = array( 'posts_per_page' => -1, 'meta_query' => array( array( 'key' => '_prfx_custom_product_deadline', 'value' => '', 'compare' => '!=' ), ), 'post_type' => 'product', 'no_found_rows' => true, //speeds up a query significantly and can be set to 'true' if we don't use pagination 'fields' => 'ids', //again, for performance ); $posts_array = get_posts( $args ); // start if we have posts if ($posts_array) { // get todays date in Y-m-d format $today = date('Y-m-d'); //now check conditions and update the code foreach( $posts_array as $post_id ){ $saved_deadline = get_post_meta( $post_id, '_prfx_custom_product_deadline', true ); // get deadline-date $soon_deadline = get_post_meta( $post_id, '_prfx_custom_product_deadline_soon', true );// get deadline-soon-date if ($today > $saved_deadline) { // if today is after deadline update_post_meta( $post_id, '_prfx_custom_product_status', 'deadline-met' ); } elseif ($today < $saved_deadline && $today > $soon_deadline) { // if today is before deadline but after soon-deadline update_post_meta( $post_id, '_prfx_custom_product_status', 'deadline-soon' ); } } } } ``` As said above I tried to dry run this function, instead of update\_post\_meta I just printed the data out. This seems to work. Iam also using a similar function to echo out some strings on the frontend, so the date compare also works. --- Update: So, I cant get this to work with the cronjobs. I just tested the following code inside an plugin, as I activate the plugin, the code runs. The query is working fine, I printed/checked the results, and it is working as simple plugin code. But the same code is not running in the cronjob. When I look at the cron output with Wp Crontrol, I can see the hourly event "prfx\_run\_hourly\_status\_update\_cron\_job", but without any action assigned. However, for example "woocommerce\_geoip\_updater" has also no action listed. Maybe someone has an idea why? Here is the tested code: ``` add_action('init','prfx_resave_posts'); function prfx_resave_posts(){ $args = array( 'posts_per_page' => -1, 'post_type' => 'product', 'meta_query' => array( array( 'key' => '_prfx_custom_product_deadline_soon', 'value' => '', 'compare' => '!=' ), ), 'no_found_rows' => true, //speeds up a query significantly and can be set to 'true' if we don't use pagination 'fields' => 'ids', //again, for performance ); $posts_array = get_posts( $args ); if ($posts_array) { //output: Array ( [0] => 120399 [1] => 120431 [2] => 120469 [3] => 120401 [4] => 120433 ) // get todays date in Y-m-d format $today = date('Y-m-d'); foreach ($posts_array as $my_post) { #print_r($my_post); //output example: 120399 $saved_soon_deadline = get_post_meta( $my_post, '_prfx_custom_product_deadline_soon', true ); #print_r($saved_soon_deadline); //output: 2018-11-30 if ($today > $saved_soon_deadline) { update_post_meta( $my_post, '_prfx_custom_product_status', 'my-new-val-here' ); } } } } ```
Without knowing further details of your specific installation: 1. Make sure you are actually previewing live on the web in a browser to see if the short-code actually is working. 2. Make sure you have spelled the short-code correctly, and have the correct syntax. (See theme's documentation.) 3. If the short-code requires some special JavaScript library, often other plugins that also use JavaScript, can interfere. I've had 3rd party plugins break the default theme functionality on my site. When I deactivate the offending plugin, the theme features work again. 4. Contact the theme developer's support forum or directly for answers. Likely others have the same issue or question. If #1 or #2 or #3 above are not the issue, then the developer or other user in a forum may be able to shed some light on the subject.
317,113
<p>I added support for <code>align-wide</code> to my theme, but I don't know how to disable this feature for some existing blocks.</p> <p>I check <a href="https://wordpress.org/gutenberg/handbook/" rel="nofollow noreferrer">Gutenberg documentation</a> but I can't find solution.</p> <pre><code>add_theme_support( 'align-wide' ); </code></pre>
[ { "answer_id": 317239, "author": "Danny Cooper", "author_id": 111172, "author_profile": "https://wordpress.stackexchange.com/users/111172", "pm_score": 2, "selected": false, "text": "<p>Are you referring to blocks you've built yourself or existing blocks?</p>\n\n<p>If you are building yo...
2018/10/19
[ "https://wordpress.stackexchange.com/questions/317113", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133863/" ]
I added support for `align-wide` to my theme, but I don't know how to disable this feature for some existing blocks. I check [Gutenberg documentation](https://wordpress.org/gutenberg/handbook/) but I can't find solution. ``` add_theme_support( 'align-wide' ); ```
According to [the gutenberg handbook](https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#blocks-registerblocktype) you can use the `blocks.registerBlockType` filter which allows you to play around with the block settings. For most of the wp core blocks modifying the `supports.align` property works pretty well: ```js wp.hooks.addFilter( 'blocks.registerBlockType', 'my-theme/namespace', function( settings, name ) { if ( name === 'core/pullquote' ) { return lodash.assign( {}, settings, { supports: lodash.assign( {}, settings.supports, { // disable the align-UI completely ... align: false, // ... or only allow specific alignments // align: ['center,'full'], } ), } ); } return settings; } ); ``` In my tests this worked for most of wp core blocks, except for `core/image`, `core/paragraph`, `core/heading` and `core/quote`. Troublesome Image Block ----------------------- As for WP 5.0.3 (and at least up to 5.3) these blocks will receive an additional alignment control like this: [![Additional Alignments](https://i.stack.imgur.com/4izQp.png)](https://i.stack.imgur.com/4izQp.png) with code: ```js ... { align: ['left','full'], } ... ``` To control the available alignments for the `core/image` block, you would have to modify the edit method of a block using the [`editor.BlockEdit`](https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#editor-blockedit) filter. Nasty Headings, Paragraphs & Quotes ----------------------------------- The problem with `core/paragraph`, `core/heading` and `core/quote` is, that block-align (defined by classenames `alignleft`, `alignwide`, ... in the frontend and the `data-align` attribute in the editor) is not clearly separated from the text-align (defined in the style attribute), which leads to odd results like this: [![Odd core/paragraph](https://i.stack.imgur.com/jMhXe.png)](https://i.stack.imgur.com/jMhXe.png) **[UPDATE 2019-11-13]:** As of WP 5.3 this works pretty well with `core/cover` now.
317,124
<p>I need some help with google indexing old PDF pages.</p> <p>Here is the situation:</p> <ul> <li>I have a new URL of <code>new.example.com</code>.</li> <li>The website was rebuilt and the company name has changed.</li> <li>The URL used to be <code>old.example.com</code>.</li> <li>It has been about 7 months since the launch of the new website with the new URL.</li> <li>Google is still indexing PDF pages that show the old URL, and if a user clicks on this PDF/page they will also see the old company name and logo.</li> <li>I put a URL redirect on this PDF/page to go to the new URL, and the PDF will now show the user the new logo.</li> </ul> <p>I have been able to redirect at a URL level and folder level in the past for various reasons. </p> <p>Any suggestions how I can redirect ALL PDF pages at one time... if that makes sense? The problem is that they are not all in the same folder. Not sure if there is some sort of string/code I can add to the <code>.htaccess</code> file for this type of scenario?</p>
[ { "answer_id": 317239, "author": "Danny Cooper", "author_id": 111172, "author_profile": "https://wordpress.stackexchange.com/users/111172", "pm_score": 2, "selected": false, "text": "<p>Are you referring to blocks you've built yourself or existing blocks?</p>\n\n<p>If you are building yo...
2018/10/19
[ "https://wordpress.stackexchange.com/questions/317124", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146762/" ]
I need some help with google indexing old PDF pages. Here is the situation: * I have a new URL of `new.example.com`. * The website was rebuilt and the company name has changed. * The URL used to be `old.example.com`. * It has been about 7 months since the launch of the new website with the new URL. * Google is still indexing PDF pages that show the old URL, and if a user clicks on this PDF/page they will also see the old company name and logo. * I put a URL redirect on this PDF/page to go to the new URL, and the PDF will now show the user the new logo. I have been able to redirect at a URL level and folder level in the past for various reasons. Any suggestions how I can redirect ALL PDF pages at one time... if that makes sense? The problem is that they are not all in the same folder. Not sure if there is some sort of string/code I can add to the `.htaccess` file for this type of scenario?
According to [the gutenberg handbook](https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#blocks-registerblocktype) you can use the `blocks.registerBlockType` filter which allows you to play around with the block settings. For most of the wp core blocks modifying the `supports.align` property works pretty well: ```js wp.hooks.addFilter( 'blocks.registerBlockType', 'my-theme/namespace', function( settings, name ) { if ( name === 'core/pullquote' ) { return lodash.assign( {}, settings, { supports: lodash.assign( {}, settings.supports, { // disable the align-UI completely ... align: false, // ... or only allow specific alignments // align: ['center,'full'], } ), } ); } return settings; } ); ``` In my tests this worked for most of wp core blocks, except for `core/image`, `core/paragraph`, `core/heading` and `core/quote`. Troublesome Image Block ----------------------- As for WP 5.0.3 (and at least up to 5.3) these blocks will receive an additional alignment control like this: [![Additional Alignments](https://i.stack.imgur.com/4izQp.png)](https://i.stack.imgur.com/4izQp.png) with code: ```js ... { align: ['left','full'], } ... ``` To control the available alignments for the `core/image` block, you would have to modify the edit method of a block using the [`editor.BlockEdit`](https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#editor-blockedit) filter. Nasty Headings, Paragraphs & Quotes ----------------------------------- The problem with `core/paragraph`, `core/heading` and `core/quote` is, that block-align (defined by classenames `alignleft`, `alignwide`, ... in the frontend and the `data-align` attribute in the editor) is not clearly separated from the text-align (defined in the style attribute), which leads to odd results like this: [![Odd core/paragraph](https://i.stack.imgur.com/jMhXe.png)](https://i.stack.imgur.com/jMhXe.png) **[UPDATE 2019-11-13]:** As of WP 5.3 this works pretty well with `core/cover` now.
317,131
<p>i have this i answer in reference but seems have upvoted by many <a href="https://wordpress.stackexchange.com/a/48094/145078">https://wordpress.stackexchange.com/a/48094/145078</a></p> <p>but not sure why it is not working for me.. </p> <p>in answer </p> <pre><code> class MyClass { function __construct() { add_action( 'init',array( $this, 'getStuffDone' ) ); } function getStuffDone() { // .. This is where stuff gets done .. } } $var = new MyClass(); </code></pre> <p>don't i have to set the visibility?</p> <pre><code>namespace NS{ class MyClass { public function __construct() { add_action( 'init',array( $this, 'getStuffDone' ) ); } public function getStuffDone() { // .. This is where stuff gets done .. } } } $var = new MyClass(); </code></pre> <p>above code does not works for me, is not correct or any mistake from my side?</p> <p>but this code works fine</p> <pre><code>add_action('init',function(){ $lat = new \NS\MyClass(); $lat-&gt;getStuffDone(); //Sorry not $lath }); </code></pre> <p>i am calling the class file as require get_template_directory(). /myfolder/class/MyClass.php</p>
[ { "answer_id": 317133, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": 0, "selected": false, "text": "<ol>\n<li>don't i have to set the visibility?</li>\n</ol>\n\n<p>You don't have to, but you should. Class proper...
2018/10/19
[ "https://wordpress.stackexchange.com/questions/317131", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
i have this i answer in reference but seems have upvoted by many <https://wordpress.stackexchange.com/a/48094/145078> but not sure why it is not working for me.. in answer ``` class MyClass { function __construct() { add_action( 'init',array( $this, 'getStuffDone' ) ); } function getStuffDone() { // .. This is where stuff gets done .. } } $var = new MyClass(); ``` don't i have to set the visibility? ``` namespace NS{ class MyClass { public function __construct() { add_action( 'init',array( $this, 'getStuffDone' ) ); } public function getStuffDone() { // .. This is where stuff gets done .. } } } $var = new MyClass(); ``` above code does not works for me, is not correct or any mistake from my side? but this code works fine ``` add_action('init',function(){ $lat = new \NS\MyClass(); $lat->getStuffDone(); //Sorry not $lath }); ``` i am calling the class file as require get\_template\_directory(). /myfolder/class/MyClass.php
> > above code does not works for me, is not correct or any mistake from > my side? > > > And it didn't work for me either. Because it throws this fatal error: > > PHP Fatal error: No code may exist outside of namespace {} in ... > > > And that's because the PHP [manual](http://php.net/manual/en/language.namespaces.definitionmultiple.php) says: > > No PHP code may exist outside of the namespace brackets except for an > opening declare statement. > > > So your code could be fixed in two ways: 1. Use the *non-bracketed* syntax. ``` <?php namespace NS; class MyClass { public function __construct() { add_action( 'init',array( $this, 'getStuffDone' ) ); } public function getStuffDone() { // .. This is where stuff gets done .. } } $var = new MyClass(); ``` 2. Put global code (or the `$var = new MyClass();`) inside a namespace statement (`namespace {}`) with no namespace. *Note though*, that you need to use `NS\MyClass` instead of just `MyClass`. ``` <?php // No code here. (except `declare`) namespace NS { class MyClass { public function __construct() { add_action( 'init',array( $this, 'getStuffDone' ) ); } public function getStuffDone() { // .. This is where stuff gets done .. } } } // No code here. (except another `namespace {...}`) namespace { $var = new NS\MyClass(); } // No code here. (except another `namespace {...}`) ``` UPDATE ------ Ok, this is what I have in `wp-content/themes/my-theme/includes/MyClass.php`: ``` <?php namespace NS; class MyClass { public function __construct() { add_action( 'init', array( $this, 'getStuffDone' ) ); add_filter( 'the_content', array( $this, 'test' ) ); } public function getStuffDone() { error_log( __METHOD__ . ' was called' ); } public function test( $content ) { return __METHOD__ . ' in the_content.<hr>' . $content; } } $var = new MyClass(); ``` And I'm including the file from `wp-content/themes/my-theme/functions.php`: ``` require_once get_template_directory() . '/includes/MyClass.php'; ``` Try that out and see if it works for you, because it worked well for me: * You'd see `NS\MyClass::test in the_content.` in the post content (just visit any single post). * You'd see `NS\MyClass::getStuffDone was called` added in the `error_log` file or `wp-content/debug.log` if you enabled [`WP_DEBUG_LOG`](https://codex.wordpress.org/Debugging_in_WordPress#WP_DEBUG_LOG).
317,151
<p>I've created some shortcodes and for some of these, I need to load particular scripts on demand.</p> <p>I've included by default in my function.php file</p> <pre><code>vendor.js myscript.js </code></pre> <p>When i load the shortcode, i need to include a separate script between the two above (meaning that myscript.js requires the new script to be included before it to work).</p> <p>I've created the shortcode like this:</p> <pre><code>function callbackService() { ob_start(); get_template_part('hg_custom_shortcodes/callback'); return ob_get_clean(); } add_shortcode('callbackService', 'callbackService'); </code></pre> <p>the template is loading an angular app.</p> <p>I then tried to load my script (the one that needs to be included only when the shortcode is loaded) by changing the snippet above to this:</p> <pre><code>function callbackService() { ob_start(); wp_enqueue_script('angular-bundle', get_template_directory_uri() . '/scripts/angular-bundle.js', array(), false, true); get_template_part('hg_custom_shortcodes/callback'); return ob_get_clean(); } add_shortcode('callbackService', 'callbackServhowever </code></pre> <p>The script is included, hovewer i think it's included after <code>myscript.js</code> and the whole shortcode (angular app) is not working as "Angular is not defined".</p> <p>How can i tell the enqueue to load the script after? I know that usually i would change the <code>add_action()</code> priority, but in this particular case there's no <code>add_action</code> involved and i don't know what else to try.</p> <p>Any suggestions? thanks</p>
[ { "answer_id": 317170, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 2, "selected": false, "text": "<p>Would <a href=\"https://codex.wordpress.org/Function_Reference/has_shortcode\" rel=\"nofollow norefe...
2018/10/20
[ "https://wordpress.stackexchange.com/questions/317151", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105978/" ]
I've created some shortcodes and for some of these, I need to load particular scripts on demand. I've included by default in my function.php file ``` vendor.js myscript.js ``` When i load the shortcode, i need to include a separate script between the two above (meaning that myscript.js requires the new script to be included before it to work). I've created the shortcode like this: ``` function callbackService() { ob_start(); get_template_part('hg_custom_shortcodes/callback'); return ob_get_clean(); } add_shortcode('callbackService', 'callbackService'); ``` the template is loading an angular app. I then tried to load my script (the one that needs to be included only when the shortcode is loaded) by changing the snippet above to this: ``` function callbackService() { ob_start(); wp_enqueue_script('angular-bundle', get_template_directory_uri() . '/scripts/angular-bundle.js', array(), false, true); get_template_part('hg_custom_shortcodes/callback'); return ob_get_clean(); } add_shortcode('callbackService', 'callbackServhowever ``` The script is included, hovewer i think it's included after `myscript.js` and the whole shortcode (angular app) is not working as "Angular is not defined". How can i tell the enqueue to load the script after? I know that usually i would change the `add_action()` priority, but in this particular case there's no `add_action` involved and i don't know what else to try. Any suggestions? thanks
`wp_enqueue_script` is not going to work in a shortcode, this is because of the loading order. You could use `wp_register_script` and then you could `wp_enqueue_script` in you shortcode function like this example: ``` // Front-end function front_end_scripts() { wp_register_script( 'example-js', '//example.com/shared-web/js/example.js', array(), null, true ); } add_action( 'wp_enqueue_scripts', 'front_end_scripts' ); ``` Then you use this in your shortcode: ``` function example_shortcode() { wp_enqueue_script( 'example-js' ); return; // dont forget to return something } add_shortcode( 'example-shortcode', 'example_shortcode' ); ``` Furthermore, you could use [`has_shortcode`](https://codex.wordpress.org/Function_Reference/has_shortcode) to check if a shortcode is loaded: ``` function custom_shortcode_scripts() { global $post; if( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'custom-shortcode') ) { wp_enqueue_script( 'custom-script'); } } add_action( 'wp_enqueue_scripts', 'custom_shortcode_scripts'); ```
317,158
<p>On my home page I'd like to display the title and content from a few pages (about page, contact page, etc.). It looks like the template tag get_post can be used, but I'm not savvy enough with PHP to make it so. </p> <p>I found the code snippet below and it works.</p> <p><code>&lt;?php $id = 17; $post = get_page($id); $content = apply_filters('the_content', $post-&gt;post_content); $title = $post-&gt;post_title; echo '&lt;h3&gt;'; echo $title; echo '&lt;/h3&gt;'; echo $content; ?&gt;</code></p>
[ { "answer_id": 317170, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 2, "selected": false, "text": "<p>Would <a href=\"https://codex.wordpress.org/Function_Reference/has_shortcode\" rel=\"nofollow norefe...
2018/10/20
[ "https://wordpress.stackexchange.com/questions/317158", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152676/" ]
On my home page I'd like to display the title and content from a few pages (about page, contact page, etc.). It looks like the template tag get\_post can be used, but I'm not savvy enough with PHP to make it so. I found the code snippet below and it works. `<?php $id = 17; $post = get_page($id); $content = apply_filters('the_content', $post->post_content); $title = $post->post_title; echo '<h3>'; echo $title; echo '</h3>'; echo $content; ?>`
`wp_enqueue_script` is not going to work in a shortcode, this is because of the loading order. You could use `wp_register_script` and then you could `wp_enqueue_script` in you shortcode function like this example: ``` // Front-end function front_end_scripts() { wp_register_script( 'example-js', '//example.com/shared-web/js/example.js', array(), null, true ); } add_action( 'wp_enqueue_scripts', 'front_end_scripts' ); ``` Then you use this in your shortcode: ``` function example_shortcode() { wp_enqueue_script( 'example-js' ); return; // dont forget to return something } add_shortcode( 'example-shortcode', 'example_shortcode' ); ``` Furthermore, you could use [`has_shortcode`](https://codex.wordpress.org/Function_Reference/has_shortcode) to check if a shortcode is loaded: ``` function custom_shortcode_scripts() { global $post; if( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'custom-shortcode') ) { wp_enqueue_script( 'custom-script'); } } add_action( 'wp_enqueue_scripts', 'custom_shortcode_scripts'); ```
317,175
<p>I've registered a widget</p> <pre><code>register_widget('Education_Work'); </code></pre> <p>Now can I call a widget by registered name? Is it possible ?</p> <pre><code>dynamic_sidebar('home-1'); // don't need this </code></pre> <p>I want something like <code>dynamic_sidebar('Education_Work');</code></p>
[ { "answer_id": 317183, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>You would use <code>the_widget</code></p>\n<p><a href=\"https://codex.wordpress.org/Function_Reference/the_w...
2018/10/20
[ "https://wordpress.stackexchange.com/questions/317175", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152683/" ]
I've registered a widget ``` register_widget('Education_Work'); ``` Now can I call a widget by registered name? Is it possible ? ``` dynamic_sidebar('home-1'); // don't need this ``` I want something like `dynamic_sidebar('Education_Work');`
You would use `the_widget` <https://codex.wordpress.org/Function_Reference/the_widget> > > This template tag displays an arbitrary widget outside of a sidebar. It can be used anywhere in templates. > > > > ``` > <?php the_widget( $widget, $instance, $args ); ?> > > ``` > > e.g. `<?php the_widget( 'WP_Widget_Archives' ); ?>`
317,176
<p>I am trying to schedule WP Cron that should run every midnight at Local Timestamp, but it is taking UTC only. This the code I am trying with,</p> <pre><code>if ( ! wp_next_scheduled( 'midnight_cron' ) ) { $now = current_time('timestamp', 1 ); $time = strtotime('tomorrow', $now ); wp_schedule_event($time, 'daily', 'midnight_cron'); } </code></pre> <p>I know by default WP cron uses UTC/GMT time, not local time, but what could be the possible way to achieve this?</p> <p><strong>Update:</strong></p> <pre><code>if ( ! wp_next_scheduled( 'midnight_cron' ) ) { $gmt = get_option( 'gmt_offset' ); $time = strtotime('midnight') + ((24 - $gmt) * HOUR_IN_SECONDS); if($time &lt; time()) $time + (24 * HOUR_IN_SECONDS); wp_schedule_event($time, 'daily', 'midnight_cron'); } </code></pre>
[ { "answer_id": 317177, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"https://codex.wordpress.org/Function_Reference/wp_schedule_event\" rel=\"nofollow nore...
2018/10/20
[ "https://wordpress.stackexchange.com/questions/317176", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138263/" ]
I am trying to schedule WP Cron that should run every midnight at Local Timestamp, but it is taking UTC only. This the code I am trying with, ``` if ( ! wp_next_scheduled( 'midnight_cron' ) ) { $now = current_time('timestamp', 1 ); $time = strtotime('tomorrow', $now ); wp_schedule_event($time, 'daily', 'midnight_cron'); } ``` I know by default WP cron uses UTC/GMT time, not local time, but what could be the possible way to achieve this? **Update:** ``` if ( ! wp_next_scheduled( 'midnight_cron' ) ) { $gmt = get_option( 'gmt_offset' ); $time = strtotime('midnight') + ((24 - $gmt) * HOUR_IN_SECONDS); if($time < time()) $time + (24 * HOUR_IN_SECONDS); wp_schedule_event($time, 'daily', 'midnight_cron'); } ```
Part 1. The Time != The Timestamp --------------------------------- [![enter image description here](https://i.stack.imgur.com/m2QtV.jpg)](https://i.stack.imgur.com/m2QtV.jpg) This is your problem: > > every midnight at Local Timestamp > > > There is no such thing as a local timestamp. Timestamps are not timezoned, it's not that WP uses UTC, but rather that UTC timestamps just happen to be +0 hours. If you want it to happen at midnight local time, you need to convert that time into a timestamp, and UTC is the easiest way to do that. For example midnight BST is 11pm UTC, so I would need to schedule a cron job for 11pm for it to run at midnight. If I set the cron job to run at 00:00, then that would be 1am local time, which is not what I wanted. So take your desired localized timezoned time, and convert it to UTC in code. You can always undo the math at a later date if you need to display it. e.g. here we take a UTC date and change it to Moscow time: ``` $date = new DateTime('2012-07-16 01:00:00 +00'); $date->setTimezone(new DateTimeZone('Europe/Moscow')); // +04 echo $date->format('Y-m-d H:i:s'); // 2012-07-15 05:00:00 ``` And here we take a Bangkok time and convert it to UTC: ``` $given = new DateTime("2014-12-12 14:18:00 +07"); echo $given->format("Y-m-d H:i:s e") . "\n"; // 2014-12-12 14:18:00 Asia/Bangkok $given->setTimezone(new DateTimeZone("UTC")); echo $given->format("Y-m-d H:i:s e") . "\n"; // 2014-12-12 07:18:00 UTC ``` If you still want to specify things in local time just write a function to do the conversion, e.g. `$utc_time = convert_to_utc( "time in local timezone")` Part 2. Why UTC? ---------------- Have you ever noticed why some timezones are referenced as **+8** hours or **-2**? That would be UTC+8 or UTC-2. UTC is also known as coordinated universal time. It's the time system used as the base standard that all the usual time systems we use day to day are derived from. So your local time is defined as some offset of UTC. ### So Can I make WP use the local timezone for timestamps? If WP stored everything using local time, then changing your local time would involve modifying every timestamp in the database. It would cause issues with communications with other APIs. It would also cause issues with plugins and themes that try to convert from UTC to your local timezone, doubling the offset, and causing compounding errors. It could also cause issues with the REST API, 2 factor auth, etc It's a very bad idea. It also breaks the fundamental system of a timestamp on your site. Think of it this way. You see times and dates in WordPress with a timezone modifier attached. When WP stores the data, it strips away the modifier, and stores it as a standardised value that all WP sites and computers understand. It then re-applies the timezone modifier whenever it displays the date.
317,185
<p>I recently updated my website after a while, and the custom fields meta box is not showing in the editor anymore. It isn't showing under "Screen Options" either. Any ideas why this could be, and how to get it back?</p> <p><a href="https://i.stack.imgur.com/XQXX6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XQXX6.png" alt="enter image description here"></a></p>
[ { "answer_id": 317187, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 0, "selected": false, "text": "<p>When registering a custom post type you have to declare that it supports the custom fields meta box to get i...
2018/10/20
[ "https://wordpress.stackexchange.com/questions/317185", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50432/" ]
I recently updated my website after a while, and the custom fields meta box is not showing in the editor anymore. It isn't showing under "Screen Options" either. Any ideas why this could be, and how to get it back? [![enter image description here](https://i.stack.imgur.com/XQXX6.png)](https://i.stack.imgur.com/XQXX6.png)
It turns out the latest Advanced Custom Fields update (from version 5.6.0 on) removes the core custom fields metaboxes by default. The way to restore it was to add a filter in `functions.php`: ``` add_filter('acf/settings/remove_wp_meta_box', '__return_false'); ```
317,207
<h2>Background</h2> <p>My website is organised in a grid layout of four columns of divs. Each div is a container for a post and is a square of 200 x 200px. The title is a header at the bottom of the div and there is either an excerpt or a featured image above. Currently, if you click on either the excerpt text/featured image or the header, you will be taken to a page with that specific content. <br><br><br></p> <h2>Problem</h2> <p>I saw <a href="https://codepen.io/noeldelgado/pen/PZJGLx" rel="nofollow noreferrer">this codepen</a>, and I wanted to emulate the same effect (preferably without haml and scss). In any case, what I wanted was for each div post to have a certain background and border colour with just the header in the centre, then after a hover or touchend, move the header down, remove background and border colours and reveal either the excerpt or the featured image. <br></p> <p>I tried doing this by creating a div above each post called the hoverzone. Hovering over the zone would then change that div's class from post to post-hover with it's own separate styling. I got this to work except it would only change the first post's styling.</p> <p>Because of Wordpress's loop, <em>all posts</em> have the same class and ID, i.e. 'post' and 'uniquepost' respectively.</p> <p><strong>Is there a way to do a targeted selection of a specific post and change that post's style only during a hover or after a touchend?</strong></p> <p>I tried using php with the class: hoverzone_&#60;?php the_title_attribute(); ?&#62;, only to realise that this could not be integrated into either JQuery nor CSS.</p> <p>Thank you,</p>
[ { "answer_id": 317187, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 0, "selected": false, "text": "<p>When registering a custom post type you have to declare that it supports the custom fields meta box to get i...
2018/10/21
[ "https://wordpress.stackexchange.com/questions/317207", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152697/" ]
Background ---------- My website is organised in a grid layout of four columns of divs. Each div is a container for a post and is a square of 200 x 200px. The title is a header at the bottom of the div and there is either an excerpt or a featured image above. Currently, if you click on either the excerpt text/featured image or the header, you will be taken to a page with that specific content. Problem ------- I saw [this codepen](https://codepen.io/noeldelgado/pen/PZJGLx), and I wanted to emulate the same effect (preferably without haml and scss). In any case, what I wanted was for each div post to have a certain background and border colour with just the header in the centre, then after a hover or touchend, move the header down, remove background and border colours and reveal either the excerpt or the featured image. I tried doing this by creating a div above each post called the hoverzone. Hovering over the zone would then change that div's class from post to post-hover with it's own separate styling. I got this to work except it would only change the first post's styling. Because of Wordpress's loop, *all posts* have the same class and ID, i.e. 'post' and 'uniquepost' respectively. **Is there a way to do a targeted selection of a specific post and change that post's style only during a hover or after a touchend?** I tried using php with the class: hoverzone\_<?php the\_title\_attribute(); ?>, only to realise that this could not be integrated into either JQuery nor CSS. Thank you,
It turns out the latest Advanced Custom Fields update (from version 5.6.0 on) removes the core custom fields metaboxes by default. The way to restore it was to add a filter in `functions.php`: ``` add_filter('acf/settings/remove_wp_meta_box', '__return_false'); ```
317,250
<p>I am using a plugin, and to get around something I need to add some text to the excerpt field on my posts, but I don't want to display the excerpt field data on the front end, but rather the post content.</p> <p>Is there a way to stop wp from automatically showing the contents of the excerpt field? css won't work, as I want to display the post content like it would if the excerpt field were empty.</p>
[ { "answer_id": 317257, "author": "ManzoorWani", "author_id": 113465, "author_profile": "https://wordpress.stackexchange.com/users/113465", "pm_score": 1, "selected": false, "text": "<p>If you want to always return post content when trying to get post excerpt, you can use <code>get_the_e...
2018/10/22
[ "https://wordpress.stackexchange.com/questions/317250", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151735/" ]
I am using a plugin, and to get around something I need to add some text to the excerpt field on my posts, but I don't want to display the excerpt field data on the front end, but rather the post content. Is there a way to stop wp from automatically showing the contents of the excerpt field? css won't work, as I want to display the post content like it would if the excerpt field were empty.
If you want to always return post content when trying to get post excerpt, you can use `get_the_excerpt` filter like this. ``` add_filter( 'get_the_excerpt', 'wp256_use_content_as_excerpt', 10, 2 ); function wp256_use_content_as_excerpt( $excerpt, $post ) { return wp_strip_all_tags( $post->post_content ); } ```
317,256
<h2>How to UP Page Speed With Widget Defer?</h2> <p>Is there a way to <strong>defer</strong> a widget in the footer?</p> <p>I have an external API in a footer widget which is slowing down my <a href="https://lbryhub.com" rel="nofollow noreferrer">page</a>. It is not needed until the page is loaded.</p> <p>The caching plugin I use (W3 Total Cache) gives me the option to defer other scripts, but not scripts directly coded into the widget. </p> <p>What is the best way to manually <strong>defer</strong> custom code API that is in the WordPress widget area of a footer?</p> <h2>Like This</h2> <p><a href="https://i.stack.imgur.com/UBP1g.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UBP1g.jpg" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/uI7As.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uI7As.jpg" alt="enter image description here"></a></p> <pre><code>&lt;script type="text/javascript"&gt; baseUrl = "https://widgets.cryptocompare.com/"; var scripts = document.getElementsByTagName("script"); var embedder = scripts[ scripts.length - 1 ]; var cccTheme = {"General":{"background":"#ffffff14","borderWidth":"0","borderColor":"none"},"Tabs":{"background":"#ffffff08","color":"#eee","activeBackground":"#ffffff14","activeColor":"#fff"},"Row":{"color":"#eee","borderColor":"#016ac1"},"Trend":{"colorDown":"#b7b6b6","colorUp":"#50dcb6","colorUnchanged":"#dddddd"},"Conversion":{"color":"#006ac1"}}; (function (){ var appName = encodeURIComponent(window.location.hostname); if(appName==""){appName="local";} var s = document.createElement("script"); s.type = "text/javascript"; s.async = true; var theUrl = baseUrl+'serve/v1/coin/multi?fsyms=BTC,LBC,ETH&amp;tsyms=USD,BTC,GBP,CNY'; s.src = theUrl + ( theUrl.indexOf("?") &gt;= 0 ? "&amp;" : "?") + "app=" + appName; embedder.parentNode.appendChild(s); })(); &lt;/script&gt; </code></pre>
[ { "answer_id": 317476, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>This has nothing to do with WordPress. It's about browser behaviour in loading scripts. You are right in noting ...
2018/10/22
[ "https://wordpress.stackexchange.com/questions/317256", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148986/" ]
How to UP Page Speed With Widget Defer? --------------------------------------- Is there a way to **defer** a widget in the footer? I have an external API in a footer widget which is slowing down my [page](https://lbryhub.com). It is not needed until the page is loaded. The caching plugin I use (W3 Total Cache) gives me the option to defer other scripts, but not scripts directly coded into the widget. What is the best way to manually **defer** custom code API that is in the WordPress widget area of a footer? Like This --------- [![enter image description here](https://i.stack.imgur.com/UBP1g.jpg)](https://i.stack.imgur.com/UBP1g.jpg) [![enter image description here](https://i.stack.imgur.com/uI7As.jpg)](https://i.stack.imgur.com/uI7As.jpg) ``` <script type="text/javascript"> baseUrl = "https://widgets.cryptocompare.com/"; var scripts = document.getElementsByTagName("script"); var embedder = scripts[ scripts.length - 1 ]; var cccTheme = {"General":{"background":"#ffffff14","borderWidth":"0","borderColor":"none"},"Tabs":{"background":"#ffffff08","color":"#eee","activeBackground":"#ffffff14","activeColor":"#fff"},"Row":{"color":"#eee","borderColor":"#016ac1"},"Trend":{"colorDown":"#b7b6b6","colorUp":"#50dcb6","colorUnchanged":"#dddddd"},"Conversion":{"color":"#006ac1"}}; (function (){ var appName = encodeURIComponent(window.location.hostname); if(appName==""){appName="local";} var s = document.createElement("script"); s.type = "text/javascript"; s.async = true; var theUrl = baseUrl+'serve/v1/coin/multi?fsyms=BTC,LBC,ETH&tsyms=USD,BTC,GBP,CNY'; s.src = theUrl + ( theUrl.indexOf("?") >= 0 ? "&" : "?") + "app=" + appName; embedder.parentNode.appendChild(s); })(); </script> ```
Your code shows an inline script, which adds a new script tag to the DOM, which probably slows down your website's loading time. This is not an inline script tag then. Try adding this line `s.defer = true;` after `s.async = true;` to add the `defer` attribute to your script tag. It should then look like this: ``` var s = document.createElement("script"); s.type = "text/javascript"; s.async = true; s.defer = true; //add this line var theUrl = baseUrl+'serve/v1/coin/multi?fsyms=BTC,LBC,ETH&tsyms=USD,BTC,GBP,CNY'; s.src = theUrl + ( theUrl.indexOf("?") >= 0 ? "&" : "?") + "app=" + appName; embedder.parentNode.appendChild(s); ``` This should result in adding a new script tag (named `s` in your code) to all the scripts the page will load and it should look like this: ``` <script type="text/javascript" async defer src="https://widgets.cryptocompare.com/serve/v1/coin/multi?fsyms=BTC,LBC,ETH&amp;tsyms=USD,BTC,GBP,CNY"></script> ```
317,263
<p>I'm doing a redesign of the woocommerce dashboard.</p> <p>I had copy the dashboard.php from woocommerce folder to my theme folder.</p> <p>So now I want to get rid of the side menu from dashboard only(Remain on other pages eg. account detail page)</p> <p><a href="https://i.stack.imgur.com/OluYb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OluYb.jpg" alt="enter image description here"></a></p> <p>Tried this code in dashboard.php, doesn't work.</p> <pre><code>add_filter ( 'woocommerce_account_menu_items', 'remove_my_account_links' ); function remove_my_account_links( $menu_links ){ unset( $menu_links['edit-address'] ); return $menu_links; } </code></pre> <p>Understand this should be in function.php, but I only want to remove it from dashboard. How should I do that?</p>
[ { "answer_id": 317476, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>This has nothing to do with WordPress. It's about browser behaviour in loading scripts. You are right in noting ...
2018/10/22
[ "https://wordpress.stackexchange.com/questions/317263", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152730/" ]
I'm doing a redesign of the woocommerce dashboard. I had copy the dashboard.php from woocommerce folder to my theme folder. So now I want to get rid of the side menu from dashboard only(Remain on other pages eg. account detail page) [![enter image description here](https://i.stack.imgur.com/OluYb.jpg)](https://i.stack.imgur.com/OluYb.jpg) Tried this code in dashboard.php, doesn't work. ``` add_filter ( 'woocommerce_account_menu_items', 'remove_my_account_links' ); function remove_my_account_links( $menu_links ){ unset( $menu_links['edit-address'] ); return $menu_links; } ``` Understand this should be in function.php, but I only want to remove it from dashboard. How should I do that?
Your code shows an inline script, which adds a new script tag to the DOM, which probably slows down your website's loading time. This is not an inline script tag then. Try adding this line `s.defer = true;` after `s.async = true;` to add the `defer` attribute to your script tag. It should then look like this: ``` var s = document.createElement("script"); s.type = "text/javascript"; s.async = true; s.defer = true; //add this line var theUrl = baseUrl+'serve/v1/coin/multi?fsyms=BTC,LBC,ETH&tsyms=USD,BTC,GBP,CNY'; s.src = theUrl + ( theUrl.indexOf("?") >= 0 ? "&" : "?") + "app=" + appName; embedder.parentNode.appendChild(s); ``` This should result in adding a new script tag (named `s` in your code) to all the scripts the page will load and it should look like this: ``` <script type="text/javascript" async defer src="https://widgets.cryptocompare.com/serve/v1/coin/multi?fsyms=BTC,LBC,ETH&amp;tsyms=USD,BTC,GBP,CNY"></script> ```
317,267
<p>I have a form like this:</p> <pre><code>&lt;form method="post" action="" id="BookingForm"&gt; &lt;label for="email"&gt;Email&lt;/label&gt; &lt;input type="text" name="email" id="emailId" value="" /&gt; &lt;input type="hidden" name="action" value="1" /&gt; &lt;input type="submit" name="submitname" value="Send" /&gt; &lt;/form&gt; &lt;div id="container"&gt;&lt;/div&gt; </code></pre> <p>My custom js file is in the following path: assets/js/makebooking.js My JS file <strong>makebooking.js</strong> :</p> <pre><code>jQuery(document).ready(function(event) { jQuery('#BookingForm').submit(validateForms); function validateForms(event) { event.preventDefault(); var x = MBAjax.ajaxurl; alert(x); jQuery.ajax({ action: 'makeBooking', type: "POST", url: MBAjax.admin_url, success: function(data) { alert(data); //jQuery("#container" ).append(data); }, fail: function(error){ alert("error" + error); } }); return false; } }); </code></pre> <p><strong>Functions.php</strong> file:</p> <pre><code>// embed the javascript file that makes the AJAX request wp_enqueue_script( 'make-booking-ajax','/wp-content/themes/twentyseventeen/assets/js/makebooking.js', array( 'jquery' ) ); // declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php) wp_localize_script( 'make-booking-ajax', 'MBAjax', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ) ) ); function makeBooking(){ echo "Home again"; return "Home"; } add_action('wp_ajax_make_booking', 'makeBooking'); </code></pre> <blockquote> <p><strong>The problem is that the ajax call returns all the dom and not what the php function returns. The code in the php function does not work; the echo message is not printed</strong></p> </blockquote> <p><em>The image below shows the issue</em>:</p> <p><a href="https://i.stack.imgur.com/KRl3l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KRl3l.png" alt="enter image description here"></a></p> <p>Thanks,</p> <p>Federico</p> <hr> <p><a href="https://i.stack.imgur.com/KRl3l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KRl3l.png" alt="enter image description here"></a></p> <p>This is my status code and my response of ajax</p>
[ { "answer_id": 317268, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 0, "selected": false, "text": "<p>The action seems to be incorrect on your Ajax call. As per the <a href=\"https://codex.wordpress.org...
2018/10/22
[ "https://wordpress.stackexchange.com/questions/317267", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152732/" ]
I have a form like this: ``` <form method="post" action="" id="BookingForm"> <label for="email">Email</label> <input type="text" name="email" id="emailId" value="" /> <input type="hidden" name="action" value="1" /> <input type="submit" name="submitname" value="Send" /> </form> <div id="container"></div> ``` My custom js file is in the following path: assets/js/makebooking.js My JS file **makebooking.js** : ``` jQuery(document).ready(function(event) { jQuery('#BookingForm').submit(validateForms); function validateForms(event) { event.preventDefault(); var x = MBAjax.ajaxurl; alert(x); jQuery.ajax({ action: 'makeBooking', type: "POST", url: MBAjax.admin_url, success: function(data) { alert(data); //jQuery("#container" ).append(data); }, fail: function(error){ alert("error" + error); } }); return false; } }); ``` **Functions.php** file: ``` // embed the javascript file that makes the AJAX request wp_enqueue_script( 'make-booking-ajax','/wp-content/themes/twentyseventeen/assets/js/makebooking.js', array( 'jquery' ) ); // declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php) wp_localize_script( 'make-booking-ajax', 'MBAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); function makeBooking(){ echo "Home again"; return "Home"; } add_action('wp_ajax_make_booking', 'makeBooking'); ``` > > **The problem is that the ajax call returns all the dom and not what the php function returns. The code in the php function does not work; > the echo message is not printed** > > > *The image below shows the issue*: [![enter image description here](https://i.stack.imgur.com/KRl3l.png)](https://i.stack.imgur.com/KRl3l.png) Thanks, Federico --- [![enter image description here](https://i.stack.imgur.com/KRl3l.png)](https://i.stack.imgur.com/KRl3l.png) This is my status code and my response of ajax
It looks like the `MBAjax.ajaxurl` and `MBAjax.admin_url` are probably not set. If it can't post to the correct Wordpress handler, then you will probably get a 404 page HTML returned instead of the PHP function return value. You can test by hard-coding the ajax url to `url: "/wp-admin/admin-ajax.php",` and see if that fixes things. Secondly, I have always added a hidden field on my forms with the action `<input type="hidden" name="action" value="make_booking">` Try that and see how you get on. Also check your browser console `network` tab to see the AJAX request being sent. You can check the data you are POSTing and also the response you get back. Easier than trying to use alerts. [![enter image description here](https://i.stack.imgur.com/2HmpS.png)](https://i.stack.imgur.com/2HmpS.png) You can also use `console.log(x)` instead. Update: I think you're missing sending anything in your AJAX request: ``` jQuery.ajax({ action : 'make_booking', type : "POST", data : { action: 'make_booking' } url : MBAjax.admin_url, success: function(data) { alert(data); //jQuery("#container" ).append(data); }, fail: function(error){ alert("error" + error); } }); ``` Try that.
317,277
<p>I'm looking for a way to get a post content and show it dynamically in a div.</p> <p>My posts are shown in a list on the left of the screen, and i'd like to show the one you click in the right part of the screen (i just need the HTML, since i want to apply another style than the single.php file).</p> <p>I searched on the web for weeks, but still have no clue about how i should do this, excepted i have to use Ajax (which i dont understand completely), and maybe a WP query ?</p> <p>Does anyone have an idea about how to do this, and can explain it to a noob like me ?</p> <p>Thank you very much !!</p> <p>EDIT : OK i figured how to get the post ID in jQuery, and tried to send it to Ajax, so i can call the post content and get it back in jQuery. </p> <p>Here's the jQuery part :</p> <pre><code>jQuery(".post-link").click(function(){ var $post_id = $this.data('id'); jQuery.post( ajaxurl, { 'action': 'load_post_content', 'the_ID': $post_id }, function(response){ jQuery('#the-post-content').html(response); }); return false; }); </code></pre> <p>And the function.php part :</p> <pre><code>add_action( 'wp_ajax_load_post_content', 'load_post_content' ); add_action( 'wp_ajax_nopriv_load_post_content', 'load_post_content' ); function load_post_content() { $the_post_id = $_POST['the_ID']; $args = array( 'p' =&gt; $the_post_id ) $the_query = new WP_query($args); if ($the_query-&gt;have_posts()) : while ($the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); $post_content = the_content(); endwhile; endif; echo $post_content; die(); } </code></pre> <p>I think i'm getting closer, but it still doesn't work, do you think i'm on the right way ?</p> <p>Thanks !</p>
[ { "answer_id": 317300, "author": "Alexander Holsgrove", "author_id": 48962, "author_profile": "https://wordpress.stackexchange.com/users/48962", "pm_score": 0, "selected": false, "text": "<p>This question is asking for quite a lot of fundamental help, but essentially you would want to in...
2018/10/22
[ "https://wordpress.stackexchange.com/questions/317277", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152738/" ]
I'm looking for a way to get a post content and show it dynamically in a div. My posts are shown in a list on the left of the screen, and i'd like to show the one you click in the right part of the screen (i just need the HTML, since i want to apply another style than the single.php file). I searched on the web for weeks, but still have no clue about how i should do this, excepted i have to use Ajax (which i dont understand completely), and maybe a WP query ? Does anyone have an idea about how to do this, and can explain it to a noob like me ? Thank you very much !! EDIT : OK i figured how to get the post ID in jQuery, and tried to send it to Ajax, so i can call the post content and get it back in jQuery. Here's the jQuery part : ``` jQuery(".post-link").click(function(){ var $post_id = $this.data('id'); jQuery.post( ajaxurl, { 'action': 'load_post_content', 'the_ID': $post_id }, function(response){ jQuery('#the-post-content').html(response); }); return false; }); ``` And the function.php part : ``` add_action( 'wp_ajax_load_post_content', 'load_post_content' ); add_action( 'wp_ajax_nopriv_load_post_content', 'load_post_content' ); function load_post_content() { $the_post_id = $_POST['the_ID']; $args = array( 'p' => $the_post_id ) $the_query = new WP_query($args); if ($the_query->have_posts()) : while ($the_query->have_posts() ) : $the_query->the_post(); $post_content = the_content(); endwhile; endif; echo $post_content; die(); } ``` I think i'm getting closer, but it still doesn't work, do you think i'm on the right way ? Thanks !
OK, I managed to make it work, here's how i did : Jquery part : ``` jQuery(".post-link").click(function(){ var post_id = jQuery(this).data('id'); jQuery.post( ajaxurl, { 'action': 'load_post_content', 'the_ID': post_id }, function(response){ jQuery('#the-post-content').html(response); } ); return false; }); ``` And the function.php part : ``` add_action( 'wp_ajax_load_post_content', 'load_post_content' ); add_action( 'wp_ajax_nopriv_load_post_content', 'load_post_content' ); function load_post_content() { $the_post_id = $_POST['the_ID']; $args = array( 'post_type' => 'post', 'p' => $the_post_id ); $ajax_query = new WP_Query($args); $the_content; if ( $ajax_query->have_posts() ) : while ( $ajax_query->have_posts() ) : $ajax_query->the_post(); $the_content = the_content(); endwhile; endif; echo $the_content; wp_reset_postdata(); die(); } ``` Hope it can help !
317,401
<p>I have a taxonomy that will be the brand, and the children’s items the template. <a href="https://i.stack.imgur.com/1G8PE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1G8PE.png" alt="enter image description here"></a></p> <p>I have a code in <code>single.php</code> to show the details.</p> <pre><code> &lt;div class="box2"&gt; &lt;div class="faixa"&gt; &lt;div class="marca"&gt;MARCA &lt;div class="marca"&gt; &lt;?php $term_names = wp_get_post_terms($post-&gt;ID, 'marcamodelo', array('fields' =&gt; 'names', 'parent' =&gt; 0)); if ( ! empty( $term_names ) ) { // echo $term_names[0]; var_dump($term_names); } ?&gt; &lt;/div&gt;&lt;/div&gt; &lt;div class="modelo"&gt;MODELO &lt;div class="marca"&gt; &lt;?php $term_names = wp_get_post_terms($post-&gt;ID, 'marcamodelo', array('fields' =&gt; 'names' )); if ( ! empty( $term_names ) ) { // echo $term_names[0]; var_dump($term_names); } ?&gt; &lt;/div&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>The result is this: <a href="https://i.stack.imgur.com/yDpIj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yDpIj.png" alt="https://imgur.com/a/VsD1xhL"></a></p> <p>But there are some that appear inverted ?! because ? <a href="https://i.stack.imgur.com/sYniQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sYniQ.png" alt="enter image description here"></a></p> <p>I have described all the parts I have done below:</p> <p><a href="https://i.stack.imgur.com/3Xfc2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Xfc2.png" alt="enter image description here"></a></p> <p>So far only the FIAT brand, and UNO model that inverts .. Maybe it’s being organized by alphabetical order or something?</p>
[ { "answer_id": 317302, "author": "Alexander Holsgrove", "author_id": 48962, "author_profile": "https://wordpress.stackexchange.com/users/48962", "pm_score": 0, "selected": false, "text": "<p>Helpful if you shared the markup.</p>\n\n<p>You can always check to see what Google sees with the...
2018/10/23
[ "https://wordpress.stackexchange.com/questions/317401", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152831/" ]
I have a taxonomy that will be the brand, and the children’s items the template. [![enter image description here](https://i.stack.imgur.com/1G8PE.png)](https://i.stack.imgur.com/1G8PE.png) I have a code in `single.php` to show the details. ``` <div class="box2"> <div class="faixa"> <div class="marca">MARCA <div class="marca"> <?php $term_names = wp_get_post_terms($post->ID, 'marcamodelo', array('fields' => 'names', 'parent' => 0)); if ( ! empty( $term_names ) ) { // echo $term_names[0]; var_dump($term_names); } ?> </div></div> <div class="modelo">MODELO <div class="marca"> <?php $term_names = wp_get_post_terms($post->ID, 'marcamodelo', array('fields' => 'names' )); if ( ! empty( $term_names ) ) { // echo $term_names[0]; var_dump($term_names); } ?> </div></div> </div> ``` The result is this: [![https://imgur.com/a/VsD1xhL](https://i.stack.imgur.com/yDpIj.png)](https://i.stack.imgur.com/yDpIj.png) But there are some that appear inverted ?! because ? [![enter image description here](https://i.stack.imgur.com/sYniQ.png)](https://i.stack.imgur.com/sYniQ.png) I have described all the parts I have done below: [![enter image description here](https://i.stack.imgur.com/3Xfc2.png)](https://i.stack.imgur.com/3Xfc2.png) So far only the FIAT brand, and UNO model that inverts .. Maybe it’s being organized by alphabetical order or something?
If you are interested in a way to avoid the uncertainty (as Google will most likely never document what they’ll do in such a case, and it could change anytime, or depend on additional signals etc.): **Give both `Product` items the same URI as ID.** This conveys to consumers that both of the `Product` items are about the same product, not different products. Here is an [example with all three syntaxes (JSON-LD, Microdata, RDFa)](https://webmasters.stackexchange.com/a/117586/17633). (Of course, the ideal solution would be to have only one `Product` item in the first place, but this is often impossible or hard to implement.)
317,477
<p>I'm using a gift card plugin for my woocommerce shop and I would like to add a generated pdf file to allow customers to download the gift card as a pdf.</p> <p>The idea is to use TCpdf or Fpdf to generate the pdf and output it as a string. </p> <pre><code>// Close and output PDF document // This method has several options, check the source code documentation for more information. echo $pdf-&gt;Output('S'); </code></pre> <p>The problem is to get this file as an attachment with wp_mail. Right now, I have this code from the plugin, and i don't know how to call the pdf :</p> <pre><code>/** * Hooks before the email is sent * * @since 2.1 */ do_action( 'kodiak_email_send_before', $this ); $subject = $this-&gt;parse_tags( $subject ); $message = $this-&gt;parse_tags( $message ); $message = $this-&gt;build_email( $message ); $attachments = ??; $sent = wp_mail( $to, $subject, $message, $this-&gt;get_headers(), $attachments ); $log_errors = apply_filters( 'kodiak_log_email_errors', true, $to, $subject, $message ); if( ! $sent &amp;&amp; true === $log_errors ) { if ( is_array( $to ) ) { $to = implode( ',', $to ); } $log_message = sprintf( __( "Email from Gift Cards failed to send.\nSend time: %s\nTo: %s\nSubject: %s\n\n", 'kodiak-giftcards' ), date_i18n( 'F j Y H:i:s', current_time( 'timestamp' ) ), $to, $subject ); } </code></pre> <p>Is someone can help me with this ?</p> <p>Thank you for the answer !</p>
[ { "answer_id": 317638, "author": "Friss", "author_id": 62392, "author_profile": "https://wordpress.stackexchange.com/users/62392", "pm_score": -1, "selected": false, "text": "<p>Usually I proceed like this</p>\n\n<pre><code>$attachment = array(filepath);\n</code></pre>\n\n<p>Where filepa...
2018/10/24
[ "https://wordpress.stackexchange.com/questions/317477", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152887/" ]
I'm using a gift card plugin for my woocommerce shop and I would like to add a generated pdf file to allow customers to download the gift card as a pdf. The idea is to use TCpdf or Fpdf to generate the pdf and output it as a string. ``` // Close and output PDF document // This method has several options, check the source code documentation for more information. echo $pdf->Output('S'); ``` The problem is to get this file as an attachment with wp\_mail. Right now, I have this code from the plugin, and i don't know how to call the pdf : ``` /** * Hooks before the email is sent * * @since 2.1 */ do_action( 'kodiak_email_send_before', $this ); $subject = $this->parse_tags( $subject ); $message = $this->parse_tags( $message ); $message = $this->build_email( $message ); $attachments = ??; $sent = wp_mail( $to, $subject, $message, $this->get_headers(), $attachments ); $log_errors = apply_filters( 'kodiak_log_email_errors', true, $to, $subject, $message ); if( ! $sent && true === $log_errors ) { if ( is_array( $to ) ) { $to = implode( ',', $to ); } $log_message = sprintf( __( "Email from Gift Cards failed to send.\nSend time: %s\nTo: %s\nSubject: %s\n\n", 'kodiak-giftcards' ), date_i18n( 'F j Y H:i:s', current_time( 'timestamp' ) ), $to, $subject ); } ``` Is someone can help me with this ? Thank you for the answer !
It is possible to add an attachment using the standard 'wp\_mail' function, however you would need to hook into the `phpmailer_init` action to do so. Because this will require calling another function where you don't have any context, you may need to register the action function anonymously with the `use ( $attachments )` statement, store the attachment content as a global variable or property, or place the attachment generation code into the new function. I can see that OP's code seems to be in the context of a class method, so I'll try to create an example which should be compatible / consistent. ``` // Previous Code... // Use this action to generate and/or attach files. add_filter( 'phpmailer_init', array( $this, 'add_attachments' ) ); // And/or store the attachments as a property. $this->set_attachments( $attachments ); $sent = wp_mail( $to, $subject, $message, $this->get_headers() ); // Log errors etc... if ( ! $sent ) { //... $this->log_error( $error_message ); } } /** * Add attachments to the email. * * This method must be public in order to work as an action. * @param PHPMailer\PHPMailer\PHPMailer $phpmailer */ public function add_attachments( $phpmailer ) { // Remove filter to prevent attaching the files to subsequent emails. remove_action( 'phpmailer_init', array( $this, 'add_attachments' ) ); // Get or generate the attachments somehow. foreach ( $this->get_attachments() as $filename, $file_contents ) { try { $phpmailer->addStringAttachment( $file_contents, $filename ); } catch( \Exception $ex ) { // An exception may thrown which would prevent the remaining files from being attached, so we'll catch these and log the errors. // This email may be sent without attachments. Do not try/catch if you don't want the email to be sent without all the attachments. $this->log_error( $ex->getMessage() ); } } } /** * Abstraction for the logging code to make it reusable. * @param string $log_message */ protected function log_error( $log_message ) { if ( ! $this->log_errors ) { return; } // Log errors here. } ```
317,507
<p>How can I change the output display of my pagination? I have been trying for the past few hours to format the output of my pagination links (1,2,3, etc.) to resemble the below:</p> <p><a href="https://i.stack.imgur.com/aIWT5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aIWT5.png" alt="Pagination Screenshot - GOAL"></a></p> <p>I have been unable to modify the code to get it even close to this. Could someone please point me in the right direction of what I need to be doing?</p> <p>Here is my code:</p> <pre><code>&lt;?php if ( get_query_var( 'paged' ) ) { $paged = get_query_var('paged'); }elseif( get_query_var( 'page' ) ) { $paged = get_query_var( 'page' ); }else{ $paged = 1; } $per_page = 3; $number_of_terms = wp_count_terms( 'series' ); // This counts the total number terms in the taxonomy with a function) $paged_offset = ($paged - 1) * $per_page; $args = array( 'orderby' =&gt; 'ID', 'order' =&gt; 'DESC', 'hide_empty' =&gt; 0, 'number' =&gt; $per_page, 'offset' =&gt; $paged_offset ); $terms = get_terms('series', $args); foreach($terms as $term){ ?&gt; &lt;div class="block_item article"&gt; &lt;div class="article_image" style="background: url('&lt;?php the_field('series_artwork', $term); ?&gt;'); background-size: cover; background-position: 50%;"&gt;&lt;/div&gt; &lt;h4 class="section_label"&gt;&lt;?php the_field('date', $term); ?&gt;&lt;/h4&gt; &lt;div class="block_item_content"&gt; &lt;h3&gt;&lt;?php echo $term-&gt;name; ?&gt;&lt;/h3&gt; &lt;p&gt;&lt;?php echo $term-&gt;description; ?&gt;&lt;/p&gt; &lt;a href="&lt;?php echo get_term_link($term-&gt;slug, 'series'); ?&gt;" class="button_styling"&gt; Read More &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } $big = 999999999; // need an unlikely integer echo paginate_links( array( 'before_page_number' =&gt; '&lt;div class="pagination"&gt;&lt;span&gt;Page '. $paged .' of ' . $term-&gt;max_num_pages . '&lt;/span&gt;&lt;/div&gt;', 'base' =&gt; str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' =&gt; '/page/%#%', 'current' =&gt; max( 1, get_query_var('paged') ), 'total' =&gt; ceil( $number_of_terms / $per_page ), 'prev_text' =&gt; __(''), 'next_text' =&gt; __('') ) ); ?&gt; </code></pre> <p>If you can get it to work with my existing function (something I have been trying to do) then bonus points to you!</p> <p><strong>functions.php</strong></p> <pre><code>// numbered pagination function pagination($pages = '', $range = 4) { $showitems = ($range * 2)+1; global $paged; if(empty($paged)) $paged = 1; if($pages == '') { global $wp_query; $pages = $wp_query-&gt;max_num_pages; if(!$pages) { $pages = 1; } } if(1 != $pages) { echo "&lt;div class=\"pagination\"&gt;&lt;span&gt;Page ".$paged." of ".$pages."&lt;/span&gt;"; if($paged &gt; 2 &amp;&amp; $paged &gt; $range+1 &amp;&amp; $showitems &lt; $pages) echo "&lt;a href='".get_pagenum_link(1)."'&gt;&amp;laquo; First&lt;/a&gt;"; if($paged &gt; 1 &amp;&amp; $showitems &lt; $pages) echo "&lt;a href='".get_pagenum_link($paged - 1)."'&gt;&amp;lsaquo; Previous&lt;/a&gt;"; for ($i=1; $i &lt;= $pages; $i++) { if (1 != $pages &amp;&amp;( !($i &gt;= $paged+$range+1 || $i &lt;= $paged-$range-1) || $pages &lt;= $showitems )) { echo ($paged == $i)? "&lt;span class=\"current\"&gt;".$i."&lt;/span&gt;":"&lt;a href='".get_pagenum_link($i)."' class=\"inactive\"&gt;".$i."&lt;/a&gt;"; } } if ($paged &lt; $pages &amp;&amp; $showitems &lt; $pages) echo "&lt;a href=\"".get_pagenum_link($paged + 1)."\"&gt;Next &amp;rsaquo;&lt;/a&gt;"; if ($paged &lt; $pages-1 &amp;&amp; $paged+$range-1 &lt; $pages &amp;&amp; $showitems &lt; $pages) echo "&lt;a href='".get_pagenum_link($pages)."'&gt;Last &amp;raquo;&lt;/a&gt;"; echo "&lt;/div&gt;\n"; } } </code></pre> <p><strong>Function Call</strong></p> <pre><code>&lt;?php if (function_exists("pagination")) { pagination($terms-&gt;max_num_pages); } ?&gt; </code></pre> <p>Thank you for any help that can be provided!</p>
[ { "answer_id": 317558, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 1, "selected": false, "text": "<p>I could see that you are trying to achieve the following output:</p>\n\n<pre><code>&lt;div class=\"paginat...
2018/10/24
[ "https://wordpress.stackexchange.com/questions/317507", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151946/" ]
How can I change the output display of my pagination? I have been trying for the past few hours to format the output of my pagination links (1,2,3, etc.) to resemble the below: [![Pagination Screenshot - GOAL](https://i.stack.imgur.com/aIWT5.png)](https://i.stack.imgur.com/aIWT5.png) I have been unable to modify the code to get it even close to this. Could someone please point me in the right direction of what I need to be doing? Here is my code: ``` <?php if ( get_query_var( 'paged' ) ) { $paged = get_query_var('paged'); }elseif( get_query_var( 'page' ) ) { $paged = get_query_var( 'page' ); }else{ $paged = 1; } $per_page = 3; $number_of_terms = wp_count_terms( 'series' ); // This counts the total number terms in the taxonomy with a function) $paged_offset = ($paged - 1) * $per_page; $args = array( 'orderby' => 'ID', 'order' => 'DESC', 'hide_empty' => 0, 'number' => $per_page, 'offset' => $paged_offset ); $terms = get_terms('series', $args); foreach($terms as $term){ ?> <div class="block_item article"> <div class="article_image" style="background: url('<?php the_field('series_artwork', $term); ?>'); background-size: cover; background-position: 50%;"></div> <h4 class="section_label"><?php the_field('date', $term); ?></h4> <div class="block_item_content"> <h3><?php echo $term->name; ?></h3> <p><?php echo $term->description; ?></p> <a href="<?php echo get_term_link($term->slug, 'series'); ?>" class="button_styling"> Read More </a> </div> </div> <?php } $big = 999999999; // need an unlikely integer echo paginate_links( array( 'before_page_number' => '<div class="pagination"><span>Page '. $paged .' of ' . $term->max_num_pages . '</span></div>', 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '/page/%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => ceil( $number_of_terms / $per_page ), 'prev_text' => __(''), 'next_text' => __('') ) ); ?> ``` If you can get it to work with my existing function (something I have been trying to do) then bonus points to you! **functions.php** ``` // numbered pagination function pagination($pages = '', $range = 4) { $showitems = ($range * 2)+1; global $paged; if(empty($paged)) $paged = 1; if($pages == '') { global $wp_query; $pages = $wp_query->max_num_pages; if(!$pages) { $pages = 1; } } if(1 != $pages) { echo "<div class=\"pagination\"><span>Page ".$paged." of ".$pages."</span>"; if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."'>&laquo; First</a>"; if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>&lsaquo; Previous</a>"; for ($i=1; $i <= $pages; $i++) { if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems )) { echo ($paged == $i)? "<span class=\"current\">".$i."</span>":"<a href='".get_pagenum_link($i)."' class=\"inactive\">".$i."</a>"; } } if ($paged < $pages && $showitems < $pages) echo "<a href=\"".get_pagenum_link($paged + 1)."\">Next &rsaquo;</a>"; if ($paged < $pages-1 && $paged+$range-1 < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($pages)."'>Last &raquo;</a>"; echo "</div>\n"; } } ``` **Function Call** ``` <?php if (function_exists("pagination")) { pagination($terms->max_num_pages); } ?> ``` Thank you for any help that can be provided!
The following will loop through a custom taxonomy and pull all the associated terms. ``` <?php if ( get_query_var( 'paged' ) ) { $page = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; } $per_page = 9; $totalterms = wp_count_terms( 'series' ); $totalpages = ceil( $totalterms / $per_page ); $paged_offset = ( $page > 0 ) ? $per_page * ( $page - 1 ) : 1; $args = array( 'orderby' => 'ID', 'order' => 'DSC', 'hide_empty' => true, 'exclude' => array(), 'exclude_tree' => array(), 'include' => array(), 'number' => $per_page, 'fields' => 'all', 'slug' => '', 'parent' => '', 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '', 'pad_counts' => false, 'offset' => $paged_offset, 'search' => '', 'cache_domain' => 'core' ); $terms = get_terms('series', $args); foreach($terms as $term){ ?> <div class="block_item article"> <div class="block_item_overlay"></div> <div class="article_image" style="background: url('<?php the_field('series_artwork', $term); ?>'); background-size: cover; background-position: 50%;"></div> <h4 class="section_label"><?php the_field('date', $term); ?></h4> <div class="block_item_content"> <h3><?php echo $term->name; ?></h3> <p><?php echo $term->description; ?></p> <a href="<?php echo get_term_link($term->slug, 'series'); ?>" class="button_styling"> Read More </a> </div> </div> <?php } $big = 999999999; // need an unlikely integer printf( '<div class="pagination"><span>Page '.$page.' of '.$totalpages.'</span>', custom_page_navi( $totalpages, $page, 3, 0 ) ); echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '/page/%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => ceil( $totalterms / $per_page ), 'prev_next' => false ) ); ?> </div> ```
317,518
<p>With template builders like Divi and Elementor, is hand coding still required? We are building a B2B website on WordPress and there are no transactions involved in it. Our content will vary from page to page.</p>
[ { "answer_id": 317558, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 1, "selected": false, "text": "<p>I could see that you are trying to achieve the following output:</p>\n\n<pre><code>&lt;div class=\"paginat...
2018/10/24
[ "https://wordpress.stackexchange.com/questions/317518", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152912/" ]
With template builders like Divi and Elementor, is hand coding still required? We are building a B2B website on WordPress and there are no transactions involved in it. Our content will vary from page to page.
The following will loop through a custom taxonomy and pull all the associated terms. ``` <?php if ( get_query_var( 'paged' ) ) { $page = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; } $per_page = 9; $totalterms = wp_count_terms( 'series' ); $totalpages = ceil( $totalterms / $per_page ); $paged_offset = ( $page > 0 ) ? $per_page * ( $page - 1 ) : 1; $args = array( 'orderby' => 'ID', 'order' => 'DSC', 'hide_empty' => true, 'exclude' => array(), 'exclude_tree' => array(), 'include' => array(), 'number' => $per_page, 'fields' => 'all', 'slug' => '', 'parent' => '', 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '', 'pad_counts' => false, 'offset' => $paged_offset, 'search' => '', 'cache_domain' => 'core' ); $terms = get_terms('series', $args); foreach($terms as $term){ ?> <div class="block_item article"> <div class="block_item_overlay"></div> <div class="article_image" style="background: url('<?php the_field('series_artwork', $term); ?>'); background-size: cover; background-position: 50%;"></div> <h4 class="section_label"><?php the_field('date', $term); ?></h4> <div class="block_item_content"> <h3><?php echo $term->name; ?></h3> <p><?php echo $term->description; ?></p> <a href="<?php echo get_term_link($term->slug, 'series'); ?>" class="button_styling"> Read More </a> </div> </div> <?php } $big = 999999999; // need an unlikely integer printf( '<div class="pagination"><span>Page '.$page.' of '.$totalpages.'</span>', custom_page_navi( $totalpages, $page, 3, 0 ) ); echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '/page/%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => ceil( $totalterms / $per_page ), 'prev_next' => false ) ); ?> </div> ```
317,530
<p>Hi guys so I have some data hitting my WP from an external company at /wp-json/wp/v2/jobs/ to be imported as a post.</p> <p>This data contains JSON that needs to be imported, however it tried to set taxonomies using strings e.g. "Manager" rather than the term_id which would be say "381". This means I get an error returned.</p> <pre><code>{ "code": "rest_invalid_param", "message": "Invalid parameter(s): job_location, job_industry, job_sector", "data": { "status": 400, "params": { "job_location": "job_location[0] is not of type integer.", "job_industry": "job_industry[0] is not of type integer.", "job_sector": "job_sector[0] is not of type integer." } } } </code></pre> <p>So what I want is when they post this value to us, for example:</p> <blockquote> <p>"job_sector":"Manager"</p> </blockquote> <p>I want to instead loop through our taxonomies, and find the ID for this "Manager" job_sector, rebuild the JSON and <strong>THEN</strong> have WP import the data I pass, error free with the proper ID.</p> <p>Can anyone help on how I can intercept the JSON and pass it along in the proper format?</p> <p>I tried "rest_pre_dispatch" but this seems to be only editing the result sent back to them, it has already been processed by WP.</p> <p>EDIT: Here is my code:</p> <pre><code> function wpse281916_rest_check_referer( $result, $server, $request ) { if ( null !== $result ) { // Core starts with a null value. // If it is no longer null, another callback has claimed this request. // Up to you how to handle - for this example we will just return early. return $result; } $array = json_decode($result, true); $term = get_term_by('name',$array["job_sector"],'job_sector'); $term = json_decode(json_encode($term),true); $termid = $term['term_id']; $array['job_sector'] = $termid; $result = json_encode($array); return $result; } // add the filter add_filter( 'rest_pre_dispatch', 'wpse281916_rest_check_referer', 10, 3 ); </code></pre> <p>EDIT2: After suggestion</p> <pre><code> function wpse281916_rest_check_referer( $result, $server, $request ) { if ( null !== $result ) { // Core starts with a null value. // If it is no longer null, another callback has claimed this request. // Up to you how to handle - for this example we will just return early. return $result; } $array = json_decode($request, true); $term = get_term_by('name',$array["job_sector"],'job_sector'); $term = json_decode(json_encode($term),true); $termid = $term['term_id']; $array['job_sector'] = $termid; $request = json_encode($array); return null; } // add the filter add_filter( 'rest_pre_dispatch', 'wpse281916_rest_check_referer', 10, 3 ); </code></pre>
[ { "answer_id": 317531, "author": "BenB", "author_id": 62909, "author_profile": "https://wordpress.stackexchange.com/users/62909", "pm_score": 2, "selected": false, "text": "<p>Seems like you looking for the <a href=\"https://developer.wordpress.org/reference/hooks/rest_pre_dispatch/\" re...
2018/10/24
[ "https://wordpress.stackexchange.com/questions/317530", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81335/" ]
Hi guys so I have some data hitting my WP from an external company at /wp-json/wp/v2/jobs/ to be imported as a post. This data contains JSON that needs to be imported, however it tried to set taxonomies using strings e.g. "Manager" rather than the term\_id which would be say "381". This means I get an error returned. ``` { "code": "rest_invalid_param", "message": "Invalid parameter(s): job_location, job_industry, job_sector", "data": { "status": 400, "params": { "job_location": "job_location[0] is not of type integer.", "job_industry": "job_industry[0] is not of type integer.", "job_sector": "job_sector[0] is not of type integer." } } } ``` So what I want is when they post this value to us, for example: > > "job\_sector":"Manager" > > > I want to instead loop through our taxonomies, and find the ID for this "Manager" job\_sector, rebuild the JSON and **THEN** have WP import the data I pass, error free with the proper ID. Can anyone help on how I can intercept the JSON and pass it along in the proper format? I tried "rest\_pre\_dispatch" but this seems to be only editing the result sent back to them, it has already been processed by WP. EDIT: Here is my code: ``` function wpse281916_rest_check_referer( $result, $server, $request ) { if ( null !== $result ) { // Core starts with a null value. // If it is no longer null, another callback has claimed this request. // Up to you how to handle - for this example we will just return early. return $result; } $array = json_decode($result, true); $term = get_term_by('name',$array["job_sector"],'job_sector'); $term = json_decode(json_encode($term),true); $termid = $term['term_id']; $array['job_sector'] = $termid; $result = json_encode($array); return $result; } // add the filter add_filter( 'rest_pre_dispatch', 'wpse281916_rest_check_referer', 10, 3 ); ``` EDIT2: After suggestion ``` function wpse281916_rest_check_referer( $result, $server, $request ) { if ( null !== $result ) { // Core starts with a null value. // If it is no longer null, another callback has claimed this request. // Up to you how to handle - for this example we will just return early. return $result; } $array = json_decode($request, true); $term = get_term_by('name',$array["job_sector"],'job_sector'); $term = json_decode(json_encode($term),true); $termid = $term['term_id']; $array['job_sector'] = $termid; $request = json_encode($array); return null; } // add the filter add_filter( 'rest_pre_dispatch', 'wpse281916_rest_check_referer', 10, 3 ); ```
Using the `rest_pre_dispatch` hook is probably the most straightforward way to go, but you need to be careful about putting your new request data back into the `WP_REST_Request` object properly. You were reassigning the `WP_REST_Request` object to an array of request data. Those changes are not persisted because the parameter is not passed by reference. Instead, you want to modify the `WP_REST_Request` object. You can assign a parameter to the request object using array like syntax, or by using `WP_REST_Request::set_param( $param_name, $param_value )`. You should also check to make sure you are only running this code on the correct route. I'd also move the priority to fire the hook earlier since you essentially are saying that this change should apply to everything happening on this request. ``` function wpse281916_rest_check_referer( $result, $server, $request ) { if ( '/wp/v2/jobs' !== $request->get_route() || 'POST' !== $request->get_method()) { return $result; } $job_sector = $request['job_sector']; if ( null === $job_sector ) { return $result; } $term = get_term_by( 'name', $job_sector, 'job_sector' ); if ( $term && ! is_wp_error( $term ) ) { $request['job_sector'] = $term->term_id; } else { $request['job_sector'] = 0; } return $result; } // add the filter add_filter( 'rest_pre_dispatch', 'wpse281916_rest_check_referer', 0, 3 ); ```
317,562
<p>With <code>define('WP_DEBUG', true);</code> in wp-config.php, I get the following notice:</p> <blockquote> <p>Constant EMPTY_TRASH_DAYS already defined in /wp-config.php on line 83</p> </blockquote> <p>I have checked this file, and this constant is defined just once. I've also searched through all of the php files on the server and don't see that it's defined anywhere else. I've run a thorough search. The only other place it's defined is in <code>default-constants.php</code>:</p> <blockquote> <p>if ( !defined( 'EMPTY_TRASH_DAYS' ) ) <br /> define( 'EMPTY_TRASH_DAYS', 30 );</p> </blockquote> <p>By commenting out the second line, the notice disappears. But it doesn't make sense to have to edit <code>default-constants.php</code> in order to define the constant in the proper place, which is <code>wp-config.php</code>.</p> <p>How should I define this constant properly, without editing <code>default-constants.php</code>, which risks being overwritten during an upgrade?</p>
[ { "answer_id": 317569, "author": "ManzoorWani", "author_id": 113465, "author_profile": "https://wordpress.stackexchange.com/users/113465", "pm_score": -1, "selected": false, "text": "<p>It means that the constant <code>EMPTY_TRASH_DAYS</code> has been defined twice. You need to check and...
2018/10/25
[ "https://wordpress.stackexchange.com/questions/317562", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/34991/" ]
With `define('WP_DEBUG', true);` in wp-config.php, I get the following notice: > > Constant EMPTY\_TRASH\_DAYS already defined in /wp-config.php on line 83 > > > I have checked this file, and this constant is defined just once. I've also searched through all of the php files on the server and don't see that it's defined anywhere else. I've run a thorough search. The only other place it's defined is in `default-constants.php`: > > if ( !defined( 'EMPTY\_TRASH\_DAYS' ) ) > > define( 'EMPTY\_TRASH\_DAYS', 30 ); > > > By commenting out the second line, the notice disappears. But it doesn't make sense to have to edit `default-constants.php` in order to define the constant in the proper place, which is `wp-config.php`. How should I define this constant properly, without editing `default-constants.php`, which risks being overwritten during an upgrade?
When defining any WordPress constants in wp-config.php you need to do it before this line: ``` require_once( ABSPATH . 'wp-settings.php' ); ``` That line loads many of WordPress’s default constants, and if you haven’t already defined them yourself then they’ll be defined in that line, meaning that any of them that you try to define after this line will have already been defined.
317,577
<p>How can I get a total word count of one author's posts? Thanks.</p> <p>To be more clear, I wanna show the total word count in the author archive page, preferably using code.</p>
[ { "answer_id": 317578, "author": "cgs themes", "author_id": 152960, "author_profile": "https://wordpress.stackexchange.com/users/152960", "pm_score": 0, "selected": false, "text": "<p>Tools to Manage Your WordPress Word Count</p>\n\n<p>PublishPress is a great WordPress plugin for content...
2018/10/25
[ "https://wordpress.stackexchange.com/questions/317577", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152235/" ]
How can I get a total word count of one author's posts? Thanks. To be more clear, I wanna show the total word count in the author archive page, preferably using code.
Here's a basic concept how I'd do the word counting and showing the count. Hopefully this serves as a starting point. I think it would be a good idea to store the word count in a [transient](https://codex.wordpress.org/Transients_API), so it isn't calculated on each and every author archive page load. ``` function author_word_count() { // get current author $author_id = get_queried_object_id(); // check if there's valid word count transient, show that if so $word_count = get_transient( $author_id . '_word_count' ); if ( $word_count ) { echo $word_count; } else { // fallback to calculating word count, show it and save it as transient $word_count = calculate_author_posts_words( $author_id ); echo $word_count; } } ``` Helper function for calculation ``` function calculate_author_posts_words( $author_id ) { $author_posts = get_author_posts( $author_id ); $count = 0; if ( ! empty( $author_posts->posts ) ) { // If you have gazillion posts, then this might hit your server hard I guess. // There might be more performant ways to doing this, but I can't think of any right now foreach( $author_posts->posts as $p ) { $count = $count + prefix_wcount( $p->post_content ); } } set_transient( $author_id . '_word_count', $count, $expiration ); // Save the count, set suitable expiration time return $count; } ``` Helper function to get authors posts ``` function get_author_posts( $id ) { // Do WP_Query with author's id and return it } ``` Helper function to count single post's word count. Modified from [Counting words in a post](https://wordpress.stackexchange.com/questions/52456/counting-words-in-a-post) ``` function prefix_wcount( $post_content ){ return sizeof(explode(" ", $post_content)); } ``` You could also hook a custom update function to [`save_post`](https://codex.wordpress.org/Plugin_API/Action_Reference/save_post) to update the word count transient when a new post is made or and existing one is updated. ``` function update_word_count_transient( $post_id ) { // check that we're intentionally saving / updating post // get post content // get transient // calculate words and and it to transient count // save transient } add_action( 'save_post', 'update_word_count_transient' ); ``` This is just a concept and I haven't tested the code examples. Please add prefixes, validation, sanitizing, fix typos/bugs and fine tune functions as needed before using in production. *If you don't know php and are looking for a copy-and-paste solution, then please hire a professional to do the work for you*
317,606
<p>I have a multisite network, where the admins of each site are able to add users to their site. My problem is that if they select the same username it will not work.</p> <p>So I am thinking if it is possible to save the Username field with a prefix. Say the admin adds a user called <code>johndoe</code> to a site called <code>mysite</code> then the user should be saved as <code>mysite-johndoe</code>. Would this be possible to achieve?</p> <p>I am talking about the Users->Add New User in the backend.</p> <p>Hope there is a way to do this! Either with PHP or jQuery?</p>
[ { "answer_id": 317709, "author": "Nikolay", "author_id": 100555, "author_profile": "https://wordpress.stackexchange.com/users/100555", "pm_score": 0, "selected": false, "text": "<p>I am not sure that they would like that prefix, maybe they would prefer to come up with a new username that...
2018/10/25
[ "https://wordpress.stackexchange.com/questions/317606", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/143279/" ]
I have a multisite network, where the admins of each site are able to add users to their site. My problem is that if they select the same username it will not work. So I am thinking if it is possible to save the Username field with a prefix. Say the admin adds a user called `johndoe` to a site called `mysite` then the user should be saved as `mysite-johndoe`. Would this be possible to achieve? I am talking about the Users->Add New User in the backend. Hope there is a way to do this! Either with PHP or jQuery?
I have noticed that the code our friend shares has an error. Add the prefix twice. I share other code with this error resolved. ``` <?php add_filter( 'pre_user_login', 'sneakily_add_prefix_to_username' ); function sneakily_add_prefix_to_username( $username ) { if ( ! current_user_can( 'manage_network' ) ) { $blog_id = get_current_blog_id(); $blog_details = get_blog_details( $blog_id ); $sanitized_path = str_replace( '/', '', get_blog_details()->path ); //error_log($sanitized_path); if ( $sanitized_path != '') { if(false === stripos($username, $sanitized_path)) { return $sanitized_path . '-' . $username; } else { return $username; } } else { $domain_parts = explode( '.', $blog_details->domain ); if ( is_array( $domain_parts ) ) { $sanitized_subdomain = sanitize_user( $domain_parts[0], true ); //error_log($sanitized_subdomain); if ( $sanitized_subdomain != '' ) { if(false === stripos($username, $sanitized_subdomain)) { return $sanitized_subdomain . '-' . $username; } else { return $username; } } } } } return $username; } ```
317,622
<p>I created a function in function.php which send an email with user information at registration. I succeed to get the ID but I can't get custom fields... I only can get these ones : - ID - user_login - user_pass - user_nicename - user_email - user_url - user_registered - display_name</p> <p>I can't either get these the user_meta like first_name or last_name. I don't understand why...</p> <p>Does someone know how I can do it ? In my case, my custom field is 'code_postal'.</p> <p>I show you what I have done :</p> <pre><code>function mailInscriptionSecteurRhone( $user_ID ) { $headers = array('Content-Type: text/html; charset=UTF-8'); $candidat = get_userdata( $user_ID ); $codePostalCandidat = get_field('code_postal', 'user_' . $user_ID ); wp_mail( 'test@test.fr', 'Test', $codePostalCandidat, $headers ); } add_action( 'user_register', 'mailInscriptionSecteurRhone', 1 ); </code></pre> <p>Thank you in advance for your help :-)</p> <p><a href="https://i.stack.imgur.com/gcMMT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gcMMT.png" alt="enter image description here"></a></p>
[ { "answer_id": 317625, "author": "Friss", "author_id": 62392, "author_profile": "https://wordpress.stackexchange.com/users/62392", "pm_score": 1, "selected": false, "text": "<p><strong>EDIT</strong></p>\n\n<p>I think the solution given by @dboris may work.\nAlternatively you could try to...
2018/10/25
[ "https://wordpress.stackexchange.com/questions/317622", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152992/" ]
I created a function in function.php which send an email with user information at registration. I succeed to get the ID but I can't get custom fields... I only can get these ones : - ID - user\_login - user\_pass - user\_nicename - user\_email - user\_url - user\_registered - display\_name I can't either get these the user\_meta like first\_name or last\_name. I don't understand why... Does someone know how I can do it ? In my case, my custom field is 'code\_postal'. I show you what I have done : ``` function mailInscriptionSecteurRhone( $user_ID ) { $headers = array('Content-Type: text/html; charset=UTF-8'); $candidat = get_userdata( $user_ID ); $codePostalCandidat = get_field('code_postal', 'user_' . $user_ID ); wp_mail( 'test@test.fr', 'Test', $codePostalCandidat, $headers ); } add_action( 'user_register', 'mailInscriptionSecteurRhone', 1 ); ``` Thank you in advance for your help :-) [![enter image description here](https://i.stack.imgur.com/gcMMT.png)](https://i.stack.imgur.com/gcMMT.png)
**EDIT** I think the solution given by @dboris may work. Alternatively you could try to hook your email sending after the user registration like this ``` global $uID; //to keep the value to reuse it later, null at this step function mailInscriptionSecteurRhone() { global $uID; $user_ID = $uID; $headers = array('Content-Type: text/html; charset=UTF-8'); $candidat = get_userdata( $user_ID ); $codePostalCandidat = get_field('code_postal', 'user_' . $user_ID ); wp_mail( 'test@test.fr', 'Test', $codePostalCandidat, $headers ); } function trigger_mailInscriptionSecteurRhone($user_ID) { global $uID; $uID = $user_ID; add_action( 'init', 'mailInscriptionSecteurRhone', 10 ); } add_action( 'user_register', 'trigger_mailInscriptionSecteurRhone', 10,1 ); ``` Instead of sending directly the email with the "not ready" data, we trigger the next init hook which is supposed to do it. We can keep the user id by using a global variable. I did not test this solution, it is a suggestion. **End edit** Ok maybe the user\_register hook is triggered before acf is loaded (acc to your screenshot, you use acf) So, have you tried get\_user\_meta like this ? ``` $codePostalCandidat = get_user_meta($user_ID,'code_postal',true); ```
317,634
<p>I have been killing myself trying to figure this out on my own. And I for the life of me cannot figure out what is causing my issues.</p> <p>I created a template for the testimonials page and used custom post types to fill the content. Everything looks great until I add the side bar then it creates a big gap the length of the sidebar between the first testimonial and the 2nd. And then they start formatting and showing up with the correct amount of space between each one.</p> <p>I can get it to look fine and correct in HTML however once I bring it into wordpress it doesn't want to format correctly. Any ideas as to what could cause this? Thank you all in advance!</p> <p>Screenshots: 1st one is html page that is "working" 2nd is what the wordpress page looks like with the gap.</p> <p><a href="https://i.stack.imgur.com/cuVNw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cuVNw.png" alt="screenshot of html"></a></p> <p><a href="https://i.stack.imgur.com/uTgUu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uTgUu.png" alt="screenshot of wordpress"></a></p> <pre><code>get_header(); ?&gt; &lt;?php $loop = new WP_Query ( array ( 'post_type' =&gt; 'testimonials', 'orderby' =&gt; 'post_id', 'order' =&gt; 'ASC') ); ?&gt; &lt;?php while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post() ?&gt; &lt;section&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-12 col-md-8"&gt; &lt;!-- Testimony --&gt; &lt;div class="row testimonials"&gt; &lt;div class="col-10"&gt; &lt;h5&gt; &lt;?php the_content(); ?&gt; &lt;cite&gt;&amp;mdash; &lt;?php the_title();?&gt;&lt;/cite&gt; &lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;?php get_sidebar(); ?&gt; &lt;/div&gt; &lt;!-- col --&gt; &lt;/div&gt; &lt;!-- row--&gt; &lt;/div&gt; &lt;!-- container --&gt; &lt;/section&gt; &lt;?php endwhile;wp_reset_query(); ?&gt; &lt;?php get_footer(); </code></pre>
[ { "answer_id": 317625, "author": "Friss", "author_id": 62392, "author_profile": "https://wordpress.stackexchange.com/users/62392", "pm_score": 1, "selected": false, "text": "<p><strong>EDIT</strong></p>\n\n<p>I think the solution given by @dboris may work.\nAlternatively you could try to...
2018/10/25
[ "https://wordpress.stackexchange.com/questions/317634", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152991/" ]
I have been killing myself trying to figure this out on my own. And I for the life of me cannot figure out what is causing my issues. I created a template for the testimonials page and used custom post types to fill the content. Everything looks great until I add the side bar then it creates a big gap the length of the sidebar between the first testimonial and the 2nd. And then they start formatting and showing up with the correct amount of space between each one. I can get it to look fine and correct in HTML however once I bring it into wordpress it doesn't want to format correctly. Any ideas as to what could cause this? Thank you all in advance! Screenshots: 1st one is html page that is "working" 2nd is what the wordpress page looks like with the gap. [![screenshot of html](https://i.stack.imgur.com/cuVNw.png)](https://i.stack.imgur.com/cuVNw.png) [![screenshot of wordpress](https://i.stack.imgur.com/uTgUu.png)](https://i.stack.imgur.com/uTgUu.png) ``` get_header(); ?> <?php $loop = new WP_Query ( array ( 'post_type' => 'testimonials', 'orderby' => 'post_id', 'order' => 'ASC') ); ?> <?php while ( $loop->have_posts() ) : $loop->the_post() ?> <section> <div class="container"> <div class="row"> <div class="col-12 col-md-8"> <!-- Testimony --> <div class="row testimonials"> <div class="col-10"> <h5> <?php the_content(); ?> <cite>&mdash; <?php the_title();?></cite> </h5> </div> </div> </div> <div class="col-md-4"> <?php get_sidebar(); ?> </div> <!-- col --> </div> <!-- row--> </div> <!-- container --> </section> <?php endwhile;wp_reset_query(); ?> <?php get_footer(); ```
**EDIT** I think the solution given by @dboris may work. Alternatively you could try to hook your email sending after the user registration like this ``` global $uID; //to keep the value to reuse it later, null at this step function mailInscriptionSecteurRhone() { global $uID; $user_ID = $uID; $headers = array('Content-Type: text/html; charset=UTF-8'); $candidat = get_userdata( $user_ID ); $codePostalCandidat = get_field('code_postal', 'user_' . $user_ID ); wp_mail( 'test@test.fr', 'Test', $codePostalCandidat, $headers ); } function trigger_mailInscriptionSecteurRhone($user_ID) { global $uID; $uID = $user_ID; add_action( 'init', 'mailInscriptionSecteurRhone', 10 ); } add_action( 'user_register', 'trigger_mailInscriptionSecteurRhone', 10,1 ); ``` Instead of sending directly the email with the "not ready" data, we trigger the next init hook which is supposed to do it. We can keep the user id by using a global variable. I did not test this solution, it is a suggestion. **End edit** Ok maybe the user\_register hook is triggered before acf is loaded (acc to your screenshot, you use acf) So, have you tried get\_user\_meta like this ? ``` $codePostalCandidat = get_user_meta($user_ID,'code_postal',true); ```
317,747
<p>I have categories Cats, Dogs and Rabbits.</p> <p>I would like to change the link used for "dogs" when listing category on the front end to a custom page instead of the category archive.</p>
[ { "answer_id": 317752, "author": "SCor", "author_id": 65273, "author_profile": "https://wordpress.stackexchange.com/users/65273", "pm_score": -1, "selected": false, "text": "<p>Depending on how you display categories, you could create a menu where the link to Dogs is a page, instead of t...
2018/10/27
[ "https://wordpress.stackexchange.com/questions/317747", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153091/" ]
I have categories Cats, Dogs and Rabbits. I would like to change the link used for "dogs" when listing category on the front end to a custom page instead of the category archive.
Your goal seems to be to change the link which is output when listing the categories rather than making the existing link point to a different page as my last answer assumed. So I am going to try a different answer with a different solution. Using the filter `term_link` in the function [`get_term_link()`](https://developer.wordpress.org/reference/functions/get_term_link/) you can change the link which is generated for a specific category. ``` function wpse_317747_filter_term_link( $termlink, $term, $taxonomy ) { if ( "category" !== $taxonomy || "dogs" !== $term->slug ) { return $termlink; } return get_permalink( $target_page_id ); } add_filter( "term_link", "wpse_317747_filter_term_link", 10, 3 ); ``` This changes the generated link if working on `category` taxonomy and the current term slug is `dogs`. Just set `$target_page_id` to correspond to the page you want the link to point to.
317,836
<p>I'm using the WP REST API v2 to try and search for all posts with the same title, what I'm trying to do is create a sort of head-to-head/previous meetings page for 2 teams.</p> <p>At the moment i can retrieve a single post with a slug no problem </p> <pre><code>.../wp-json/sportspress/v2/events?slug=team1-vs-team2 </code></pre> <p>When i use a search it retrieves all the events with team1 and team2, but also all references to team1 &amp; 2 from post content which is not what I want...</p> <pre><code>.../wp-json/sportspress/v2/events?search=team1+team2 </code></pre> <p>How do i retrieve a post using the search using the exact post title as shown below in title > rendered ??</p> <pre><code>0 id 60455 date "2016-11-22T19:30:00" date_gmt "2016-11-22T19:30:00" modified "2016-11-23T09:25:29" modified_gmt "2016-11-23T07:25:29" slug "team1-vs-team2" status "publish" type "sp_event" link ".../event/team1-vs-team2/" title rendered "Team1 vs Team2" </code></pre>
[ { "answer_id": 395256, "author": "Rajeev Singh", "author_id": 209620, "author_profile": "https://wordpress.stackexchange.com/users/209620", "pm_score": 0, "selected": false, "text": "<p>Unfortunately, it is not possible, but you can use slug instead.</p>\n<p>Like this:</p>\n<pre><code>ht...
2018/10/28
[ "https://wordpress.stackexchange.com/questions/317836", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153157/" ]
I'm using the WP REST API v2 to try and search for all posts with the same title, what I'm trying to do is create a sort of head-to-head/previous meetings page for 2 teams. At the moment i can retrieve a single post with a slug no problem ``` .../wp-json/sportspress/v2/events?slug=team1-vs-team2 ``` When i use a search it retrieves all the events with team1 and team2, but also all references to team1 & 2 from post content which is not what I want... ``` .../wp-json/sportspress/v2/events?search=team1+team2 ``` How do i retrieve a post using the search using the exact post title as shown below in title > rendered ?? ``` 0 id 60455 date "2016-11-22T19:30:00" date_gmt "2016-11-22T19:30:00" modified "2016-11-23T09:25:29" modified_gmt "2016-11-23T07:25:29" slug "team1-vs-team2" status "publish" type "sp_event" link ".../event/team1-vs-team2/" title rendered "Team1 vs Team2" ```
Of course it's possible! You'll just need to add in a custom endpoint for the REST API. To do that, drop the code below into your functions.php (or better yet, a plugin so it's not tied to your theme). First, register the custom route and allow it to take a "title" parameter. ``` /** * Register the custom route * */ function custom_register_your_post_route() { register_rest_route( 'custom-search/v1', '/posts/(?P<title>.+)', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => 'custom_get_post_sample' ) ) ); } add_action( 'rest_api_init', 'custom_register_your_post_route' ); ``` Next, add in the custom callback function to find and return the posts you're looking for, using the built-in WP\_REST\_Posts\_Controller. ``` /** * Grab all posts with a specific title * * @param WP_REST_Request $request Current request */ function custom_get_post_sample( $request ) { global $wpdb; // params $post_title = $request->get_param( 'title' ); $post_type = 'post'; // get all of the post ids with a title that matches our parameter $id_results = $wpdb->get_results( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", urldecode( $post_title ), $post_type ) ); if ( empty( $id_results ) ) { return rest_ensure_response( $request ); } // format the ids into an array $post_ids = []; foreach( $id_results as $id ) { $post_ids[] = $id->ID; } // grab all of the post objects $args = array( 'post_type' => $post_type, 'post_status' => 'publish', 'posts_per_page' => -1, 'post__in' => $post_ids ); $posts = get_posts( $args ); // prepare the API response $data = array(); $rest_posts_controller = new WP_REST_Posts_Controller( $post_type ); foreach ( $posts as $post ) { $response = $rest_posts_controller->prepare_item_for_response( $post, $request ); $data[] = $rest_posts_controller->prepare_response_for_collection( $response ); } // Return all of our post response data return rest_ensure_response( $data ); } ``` This will give you a response that looks just like the built-in Posts endpoint, including any additional data added by plugins (Yoast SEO for example). There's plenty of additional documentation under the [Extending the REST API](https://developer.wordpress.org/rest-api/extending-the-rest-api/) section at wordpress.org if you need more functionality. Hope this helps!
317,883
<p>I'm currently writing a plugin in which users can select whether they want to insert a google analytics tag or a GTM tag (Google tag manager). I've already figured out how to insert the code after the tag.</p> <p>At the moment the code gets inserted through a custom function in my theme's <code>function.php</code> and calling the function in the themes <code>header.php</code></p> <p><code>Header.php</code></p> <pre><code>&lt;?php wp_after_body();?&gt; </code></pre> <p><code>Functions.php</code></p> <pre><code>function wp_after_body() { do_action('wp_after_body'); } </code></pre> <p>But I was wondering if there is a solution in which I can just use my plugin file to insert the code after the tag (So I don't have to change the theme files everytime I use the plugin).</p> <p>I've already tried this:</p> <p><a href="https://stackoverflow.com/a/27309880/7634982">https://stackoverflow.com/a/27309880/7634982</a></p>
[ { "answer_id": 317890, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": true, "text": "<p>Since you want your plugin to be theme independent you will have to rely on hooks that you may assume are there i...
2018/10/29
[ "https://wordpress.stackexchange.com/questions/317883", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153191/" ]
I'm currently writing a plugin in which users can select whether they want to insert a google analytics tag or a GTM tag (Google tag manager). I've already figured out how to insert the code after the tag. At the moment the code gets inserted through a custom function in my theme's `function.php` and calling the function in the themes `header.php` `Header.php` ``` <?php wp_after_body();?> ``` `Functions.php` ``` function wp_after_body() { do_action('wp_after_body'); } ``` But I was wondering if there is a solution in which I can just use my plugin file to insert the code after the tag (So I don't have to change the theme files everytime I use the plugin). I've already tried this: <https://stackoverflow.com/a/27309880/7634982>
Since you want your plugin to be theme independent you will have to rely on hooks that you may assume are there in any decently made theme. At the moment you can only rely on `wp_head` and `wp_footer`. A hook right after the `<body>` tag [is under discussion](https://core.trac.wordpress.org/ticket/12563), but even if it would be declared standard today, there would still be thousands of existing themes not implementing it. So that's no use for you. The option you tried just buffers most of the page, letting you change the buffer's content before it is printed. It should work, though it is far from elegant and could easily interfere with other plugins using some kind of buffering. So, no, there is no direct WordPressy way to do this in a reliable way. What you could do in a plugin, however, is solve it with json. The idea is fairly simple, though it will require some work (and probably a learning curve). Hooking into `wp_head` add a jquery script file that adds a DOM-element right after the `<body>` tag and [use the rest api](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/) to call the function that you would normally generate the code that you want in that place.
317,896
<p>After cloning my wordpress site and fresh install of it i encountered problem. Plugins won't update. I'm working in Linux environment (Ubuntu). I've tried multiple solutions but still without positive result.</p> <p>First of all i set all permissions for installation folder with <code>chmod -R 777 .</code></p> <p>Then i set <code>define('FS_METHOD', 'direct');</code></p> <p>After that i configured temp folder with : </p> <pre><code>define('WP_TEMP_DIR', dirname(__FILE__) . '/wp-content/temp/'); /* That's all, stop editing! Happy blogging. */ </code></pre> <p>But still warning says that it can't find specified directory or is missing permissions.</p> <p>I've also changed the owner of directory with <code>chown -R $USER:$USER .</code></p> <p>So now as <code>ls -la</code> says i'm the owner of the files and directories and i have full permissions to read, write and execute.</p> <p>Now i run out of ideas what can cause such problem. Any help?</p>
[ { "answer_id": 317924, "author": "Heres2u", "author_id": 140036, "author_profile": "https://wordpress.stackexchange.com/users/140036", "pm_score": 1, "selected": false, "text": "<p>I have Wordpress on Unbutu as well. Maybe this will get you started. (I'm assuming you have access with c...
2018/10/29
[ "https://wordpress.stackexchange.com/questions/317896", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/140315/" ]
After cloning my wordpress site and fresh install of it i encountered problem. Plugins won't update. I'm working in Linux environment (Ubuntu). I've tried multiple solutions but still without positive result. First of all i set all permissions for installation folder with `chmod -R 777 .` Then i set `define('FS_METHOD', 'direct');` After that i configured temp folder with : ``` define('WP_TEMP_DIR', dirname(__FILE__) . '/wp-content/temp/'); /* That's all, stop editing! Happy blogging. */ ``` But still warning says that it can't find specified directory or is missing permissions. I've also changed the owner of directory with `chown -R $USER:$USER .` So now as `ls -la` says i'm the owner of the files and directories and i have full permissions to read, write and execute. Now i run out of ideas what can cause such problem. Any help?
I have Wordpress on Unbutu as well. Maybe this will get you started. (I'm assuming you have access with command line through Terminal via SSH. If that assumption is in error, forgive me.) In a typical Wordpress install there are likely three users, similar to: ``` root:root www-data:www-data (Apache) user:user sudo lxd (WHERE "user" is some name given for SSH access) ``` \*Those users can be found by using the command: ps aux | grep apache I've always found that the only way WP will update plugins, is if the ownership of plugins, and wp-uploads for media, is given to www-data... not the user. In fact I think I even go up to wp-content, then set ownership recursively. I set proper permissions to 755 for directories and 644 for files. (Never 777, that's bad). (All my commands are done as sudo user, because I'm SSH-ing in Terminal as my user) Here are some options. If you want to generically make Apache owner and set permissions on directories and files: ``` sudo chown www-data:www-data -R * sudo . -type d -exec chmod 755 {} \; sudo . -type f -exec chmod 644 {} \; ``` If you want to specifically make Apache owner on a directory, and set permissions: ``` sudo chown www-data:www-data -R /var/www/html/wp-content/ sudo find /var/www/html/wp-content/ -type d -exec chmod 755 {} \; sudo find /var/www/html/wp-content/ -type f -exec chmod 644 {} \; ``` But if you set permissions on everything in the install directory to 777, you're going to want to fix that with something like: ``` sudo find /var/www/html/ -type d -exec -R chmod 755 {} \; sudo find /var/www/html/ -type f -exec -R chmod 644 {} \; ``` Then make sure wp-config is hardened with 660 or even 600 permissions. ``` cd html sudo chmod 660 wp-config.php ```
317,898
<p>Wordpress 4.9.8 when I save a draft/publish return me an error:</p> <pre><code> Gone The requested resource /wp-admin/post.php is no longer available on this server and there is no forwarding address. Please remove all references to this resource. </code></pre> <p>I found that the problem is because my text has " style="bla bla bla" ". If I remove style= it works. I tried disabling all plugins, change to default theme, create a new installation, change PHP version from 5.6 to 7, 7.1, 7.2 : doesn't change. </p> <p>Any ideas?</p>
[ { "answer_id": 317901, "author": "André Kelling", "author_id": 136930, "author_profile": "https://wordpress.stackexchange.com/users/136930", "pm_score": 0, "selected": false, "text": "<p>in general it's not a good idea to insert inline styles. </p>\n\n<p>try with a CSS class and add your...
2018/10/29
[ "https://wordpress.stackexchange.com/questions/317898", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150879/" ]
Wordpress 4.9.8 when I save a draft/publish return me an error: ``` Gone The requested resource /wp-admin/post.php is no longer available on this server and there is no forwarding address. Please remove all references to this resource. ``` I found that the problem is because my text has " style="bla bla bla" ". If I remove style= it works. I tried disabling all plugins, change to default theme, create a new installation, change PHP version from 5.6 to 7, 7.1, 7.2 : doesn't change. Any ideas?
I've had the same issue recently. Inline styles, as well as `<img>` tags, would cause the `410 Gone` status and error message (`The requested resource /wp-admin/post.php is no longer available on this server and there is no forwarding address. Please remove all references to this resource.` upon previewing or publishing the post. The problem was due to the hosting provider doing some maintenance on `mod_security` in cPanel. I found out when I asked them for the Apache logs so that I could look into it more. Contact your hosting provider to get this fixed.
317,927
<p>I'd like to get a list of all the custom posts that belong to a specific taxonomy.</p> <p>I've tried many things including this code, but I get a list of all the posts in the 'members' cpt, and not just posts associated to the 'producers' taxonomy. How can I get it work ?</p> <pre><code>&lt;?php $args = array( 'post_type' =&gt; 'members', 'posts_per_page' =&gt; -1, 'tax_query' =&gt; array( 'taxonomy' =&gt; 'producers' ), ); $the_query = new WP_Query($args); while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); ?&gt; &lt;li class="producers" id="post-&lt;?php the_ID(); ?&gt;"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;/li&gt; &lt;?php endwhile; ?&gt; </code></pre> <p>EDIT 2018-10-31</p> <p>I finally made it through native WP functions and a custom query. I also needed the pagination functionality so I built it this way.</p> <pre><code> $termArray = []; $theTerms = get_terms('producers'); foreach ($theTerms as $singleTerm) { $theSlug = $singleTerm-&gt;slug; array_push($termArray,$theSlug); } $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; $loop = new WP_Query( array( 'post_type' =&gt; 'members', 'orderby' =&gt; 'rand', 'posts_per_page' =&gt; 5, 'paged' =&gt; $paged, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'producers', 'terms' =&gt; $termArray, ) ))); if ( $loop-&gt;have_posts() ) : while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); $terms = get_the_terms( $post-&gt;ID, 'producers'); if ($terms) { /// Here is the code for posts display } endwhile; endif; wp_reset_postdata(); // Pagination $big = 99999; echo paginate_links( array( 'base' =&gt; str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' =&gt; '?paged=%#%', 'current' =&gt; max( 1, get_query_var('paged') ), 'total' =&gt; $loop-&gt;max_num_pages )); </code></pre>
[ { "answer_id": 317901, "author": "André Kelling", "author_id": 136930, "author_profile": "https://wordpress.stackexchange.com/users/136930", "pm_score": 0, "selected": false, "text": "<p>in general it's not a good idea to insert inline styles. </p>\n\n<p>try with a CSS class and add your...
2018/10/29
[ "https://wordpress.stackexchange.com/questions/317927", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147708/" ]
I'd like to get a list of all the custom posts that belong to a specific taxonomy. I've tried many things including this code, but I get a list of all the posts in the 'members' cpt, and not just posts associated to the 'producers' taxonomy. How can I get it work ? ``` <?php $args = array( 'post_type' => 'members', 'posts_per_page' => -1, 'tax_query' => array( 'taxonomy' => 'producers' ), ); $the_query = new WP_Query($args); while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <li class="producers" id="post-<?php the_ID(); ?>"> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> </li> <?php endwhile; ?> ``` EDIT 2018-10-31 I finally made it through native WP functions and a custom query. I also needed the pagination functionality so I built it this way. ``` $termArray = []; $theTerms = get_terms('producers'); foreach ($theTerms as $singleTerm) { $theSlug = $singleTerm->slug; array_push($termArray,$theSlug); } $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; $loop = new WP_Query( array( 'post_type' => 'members', 'orderby' => 'rand', 'posts_per_page' => 5, 'paged' => $paged, 'tax_query' => array( array( 'taxonomy' => 'producers', 'terms' => $termArray, ) ))); if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); $terms = get_the_terms( $post->ID, 'producers'); if ($terms) { /// Here is the code for posts display } endwhile; endif; wp_reset_postdata(); // Pagination $big = 99999; echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => $loop->max_num_pages )); ```
I've had the same issue recently. Inline styles, as well as `<img>` tags, would cause the `410 Gone` status and error message (`The requested resource /wp-admin/post.php is no longer available on this server and there is no forwarding address. Please remove all references to this resource.` upon previewing or publishing the post. The problem was due to the hosting provider doing some maintenance on `mod_security` in cPanel. I found out when I asked them for the Apache logs so that I could look into it more. Contact your hosting provider to get this fixed.