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\">nice API</a>. You can probably get this with a filter like </p>\n\n<pre><code>add_filter( 'wpseo_options', function ( $arr ) {\n return $arr;\n} );\n</code></pre>\n" }, { "answer_id": 315437, "author": "Josh Smith", "author_id": 29089, "author_profile": "https://wordpress.stackexchange.com/users/29089", "pm_score": 1, "selected": true, "text": "<p>Basically this is the answer I was looking for from this question: </p>\n\n<pre><code>function yoastVariableToTitle( $post_id ) {\n $yoast_title = get_post_meta( $post_id, '_yoast_wpseo_title', true );\n $title = strstr( $yoast_title, '%%', true );\n if ( empty( $title ) ) {\n $title = get_the_title( $post_id );\n }\n $wpseo_titles = get_option( 'wpseo_titles' );\n\n $sep_options = WPSEO_Option_Titles::get_instance()-&gt;get_separator_options();\n if ( isset( $wpseo_titles['separator'] ) &amp;&amp; isset( $sep_options[ $wpseo_titles['separator'] ] ) ) {\n $sep = $sep_options[ $wpseo_titles['separator'] ];\n } else {\n $sep = '-'; //setting default separator if Admin didn't set it from backed\n }\n\n $site_title = get_bloginfo( 'name' );\n\n $meta_title = $title . ' ' . $sep . ' ' . $site_title;\n\n return $meta_title;\n} \n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/41361510/is-there-any-way-to-get-yoast-title-inside-page-using-their-variable-i-e-ti\">https://stackoverflow.com/questions/41361510/is-there-any-way-to-get-yoast-title-inside-page-using-their-variable-i-e-ti</a></p>\n" }, { "answer_id": 332369, "author": "baskin", "author_id": 163582, "author_profile": "https://wordpress.stackexchange.com/users/163582", "pm_score": 2, "selected": false, "text": "<p>Ok here is how I parsed the snippets in case anyone else needs to know</p>\n\n<pre><code>$id = get_the_ID();\n\n$post = get_post( $id, ARRAY_A );\n$yoast_title = get_post_meta( $id, '_yoast_wpseo_title', true );\n$yoast_desc = get_post_meta( $id, '_yoast_wpseo_metadesc', true );\n\n$metatitle_val = wpseo_replace_vars($yoast_title, $post );\n$metatitle_val = apply_filters( 'wpseo_title', $metatitle_val );\n\n$metadesc_val = wpseo_replace_vars($yoast_desc, $post );\n$metadesc_val = apply_filters( 'wpseo_metadesc', $metadesc_val );\n\necho $metatitle_val;\necho \"&lt;br&gt;\";\necho $metadesc_val;\n</code></pre>\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\">nice API</a>. You can probably get this with a filter like </p>\n\n<pre><code>add_filter( 'wpseo_options', function ( $arr ) {\n return $arr;\n} );\n</code></pre>\n" }, { "answer_id": 315437, "author": "Josh Smith", "author_id": 29089, "author_profile": "https://wordpress.stackexchange.com/users/29089", "pm_score": 1, "selected": true, "text": "<p>Basically this is the answer I was looking for from this question: </p>\n\n<pre><code>function yoastVariableToTitle( $post_id ) {\n $yoast_title = get_post_meta( $post_id, '_yoast_wpseo_title', true );\n $title = strstr( $yoast_title, '%%', true );\n if ( empty( $title ) ) {\n $title = get_the_title( $post_id );\n }\n $wpseo_titles = get_option( 'wpseo_titles' );\n\n $sep_options = WPSEO_Option_Titles::get_instance()-&gt;get_separator_options();\n if ( isset( $wpseo_titles['separator'] ) &amp;&amp; isset( $sep_options[ $wpseo_titles['separator'] ] ) ) {\n $sep = $sep_options[ $wpseo_titles['separator'] ];\n } else {\n $sep = '-'; //setting default separator if Admin didn't set it from backed\n }\n\n $site_title = get_bloginfo( 'name' );\n\n $meta_title = $title . ' ' . $sep . ' ' . $site_title;\n\n return $meta_title;\n} \n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/41361510/is-there-any-way-to-get-yoast-title-inside-page-using-their-variable-i-e-ti\">https://stackoverflow.com/questions/41361510/is-there-any-way-to-get-yoast-title-inside-page-using-their-variable-i-e-ti</a></p>\n" }, { "answer_id": 332369, "author": "baskin", "author_id": 163582, "author_profile": "https://wordpress.stackexchange.com/users/163582", "pm_score": 2, "selected": false, "text": "<p>Ok here is how I parsed the snippets in case anyone else needs to know</p>\n\n<pre><code>$id = get_the_ID();\n\n$post = get_post( $id, ARRAY_A );\n$yoast_title = get_post_meta( $id, '_yoast_wpseo_title', true );\n$yoast_desc = get_post_meta( $id, '_yoast_wpseo_metadesc', true );\n\n$metatitle_val = wpseo_replace_vars($yoast_title, $post );\n$metatitle_val = apply_filters( 'wpseo_title', $metatitle_val );\n\n$metadesc_val = wpseo_replace_vars($yoast_desc, $post );\n$metadesc_val = apply_filters( 'wpseo_metadesc', $metadesc_val );\n\necho $metatitle_val;\necho \"&lt;br&gt;\";\necho $metadesc_val;\n</code></pre>\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()\n{\n if ( ! is_category() ) {\n return;\n }\n $category = get_queried_object();\n $page = get_page_by_path( $category-&gt;slug );\n if ( $page instanceof WP_Post )\n {\n $url = get_permalink( $page );\n wp_safe_redirect( $url, 301 );\n }\n\n}\n\nadd_action( 'template_redirect', 'pagefromcat_template_redirect' );\n</code></pre>\n" }, { "answer_id": 317402, "author": "Andrew Seabrook", "author_id": 69236, "author_profile": "https://wordpress.stackexchange.com/users/69236", "pm_score": 1, "selected": true, "text": "<p>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.</p>\n\n<p>function pagefromcat_template_redirect()\n{\n if ( ! is_category() ) {\n return;\n }</p>\n\n<pre><code>$category = get_queried_object();\n// $page = get_page_by_path( $category-&gt;slug ); -- doesnt work\n// $page = get_page_by_path( 'destinations/' . $category-&gt;slug); works but with deeper nested locations this will cause a problem, and we will have to have multiple prefixed locations\n// atcivities immediately for instance.\n$page = get_page_by_title($category-&gt;name);\n\nif ( $page instanceof WP_Post )\n{\n $url = get_permalink( $page );\n wp_safe_redirect( $url, 301 );\n}\n</code></pre>\n\n<p>}</p>\n" } ]
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 blocks around a given category in Gutenberg, and therefore we have the method <a href=\"https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#block_categories_all\" rel=\"nofollow noreferrer\"><code>block_categories_all</code></a>. So with a filter, you can extend the default categories with custom ones.</p>\n<p>Here is my example:</p>\n<pre><code>add_filter( 'block_categories_all', function( $categories, $post ) {\n return array_merge(\n $categories,\n array(\n array(\n 'slug' =&gt; 'my-slug',\n 'title' =&gt; 'my-title',\n ),\n )\n );\n}, 10, 2 );\n</code></pre>\n<p>You can find more on this in <a href=\"https://wordpress.org/gutenberg/handbook/block-api\" rel=\"nofollow noreferrer\">the provided API</a>.</p>\n" }, { "answer_id": 330041, "author": "Aamer Shahzad", "author_id": 42772, "author_profile": "https://wordpress.stackexchange.com/users/42772", "pm_score": 1, "selected": false, "text": "<p>It is possible to filter the list of default block categories using the <code>block_categories</code> filter. Place the code in <code>functions.php</code> or <code>your-plugin.php</code> file. <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#managing-block-categories\" rel=\"nofollow noreferrer\">Explained here in WordPress Gutenberg Handbook</a></p>\n\n<pre><code>function my_plugin_block_categories( $categories, $post ) {\n if ( $post-&gt;post_type !== 'post' ) {\n return $categories;\n }\n return array_merge(\n $categories,\n array(\n array(\n 'slug' =&gt; 'my-category',\n 'title' =&gt; __( 'My category', 'my-plugin' ),\n 'icon' =&gt; 'wordpress',\n ),\n )\n );\n}\nadd_filter( 'block_categories', 'my_plugin_block_categories', 10, 2 );\n</code></pre>\n\n<p>To use an svg icon you can replace the icon in js. Define your icon.</p>\n\n<pre><code>const icon = &lt;svg className='components-panel__icon' width='20' height='20' viewBox='0 0 20 20' aria-hidden='true' role='img' focusable='false' xmlns='http://www.w3.org/2000/svg'&gt;\n &lt;rect fill=\"#ffffff\" x=\"0\" y=\"0\" width=\"20\" height=\"20\"/&gt;\n &lt;rect fill=\"#1163EB\" x=\"2\" y=\"2\" width=\"16\" height=\"16\" rx=\"16\"/&gt;\n&lt;/svg&gt;;\n</code></pre>\n\n<p>and replace the icon using <code>updateCategory</code> function from <code>wp.blocks;</code> adding class <code>components-panel__icon</code> will add a <code>6px</code> space to the left side of icon.</p>\n\n<pre><code>( function() {\n wp.blocks.updateCategory( 'my-category', { icon: icon } );\n} )();\n</code></pre>\n" } ]
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 outside of the UI, it won't work because they don't get registered via the database and assigned a permalink.</p>\n\n<p>Use the WordPress UI to upload your images to make sure they become accessible.</p>\n\n<p>As you can see from this image, where I just uploaded an image via cPanel, it does not show in WordPress.</p>\n\n<p><a href=\"https://i.stack.imgur.com/4US5D.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4US5D.jpg\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 402075, "author": "Greg", "author_id": 149765, "author_profile": "https://wordpress.stackexchange.com/users/149765", "pm_score": 1, "selected": false, "text": "<p>Since i was also looking for some sort of keeping submitted images, i found this simple plugin, which gave me a bit insight:\n<a href=\"https://wordpress.org/plugins/store-file-uploads-for-contact-form-7/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/store-file-uploads-for-contact-form-7/</a></p>\n<p>Also if you read a bit on the mentioned &quot;file-uploading-and-attachment&quot; topic in cf7, you should get the point:</p>\n<blockquote>\n<p>For security reasons, specifying files outside of the wp-content\ndirectory for email attachments is not allowed, so place the files in\nthe wp-content or its subdirectory.</p>\n</blockquote>\n<p>I think if you stay within the wp-content dir, your copy-func may have its content.</p>\n" } ]
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>You should use your action hook inside your functions.php.\nAn example of what your function could look like:</p>\n\n<pre><code>add_action( 'pre_get_posts', 'publications_archive_query' );\nfunction publications_archive_query( $query ) {\n if ( !is_admin() &amp;&amp; $query-&gt;is_main_query()) {\n if ( $query-&gt;get('post_type') === 'publications' ) {\n $query-&gt;set( 'posts_per_page', 5 );\n }\n}\n</code></pre>\n\n<p>Narrow down what is the query you are modifying by using conditional checks.</p>\n\n<p><code>$query-&gt;get('post_type')</code> to get current's Query post_type to check against.</p>\n\n<p><code>is_main_query</code> to make sure you are only applying your query modification to the main query.</p>\n\n<p>Read further and find more examples: \n<a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts</a></p>\n" }, { "answer_id": 315592, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": -1, "selected": false, "text": "<p>If you are creating the query yourself inside those <code>.php</code> pages, then it's better to pass <code>-1</code> in argument to obtain unlimited posts:</p>\n\n<pre><code>$args = array( ...... 'posts_per_page'=&gt;-1, .....) \n$your_query = new WP_Query($args);\n</code></pre>\n\n<p>If you dont have access to the query-creating <code>.php</code> file, then you might neeed to use less-recommended <code>pre_get_post</code> version (which affects all pages/queries with that custom-type), like @FFrewin suggested.</p>\n" }, { "answer_id": 372962, "author": "Code357", "author_id": 65666, "author_profile": "https://wordpress.stackexchange.com/users/65666", "pm_score": 0, "selected": false, "text": "<p>Accepted answer isn't working, but this one does:</p>\n<pre><code>function bloom_custom_posts_per_page( $query ) {\n if( !is_admin() &amp;&amp; $query-&gt;query_vars['post_type'] == 'post_type') {\n $query-&gt;query_vars['posts_per_page'] = -1;\n return $query;\n }\n}\nadd_filter( 'pre_get_posts', 'bloom_custom_posts_per_page' );\n</code></pre>\n" } ]
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_action('woocommerce_after_cart_table', 'custom_cart_function');\n</code></pre>\n" }, { "answer_id": 315644, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<p>You already have the right \"action\", which is <code>woocommerce_after_cart_contents</code>.</p>\n\n<p>But when I tried the markup you used:</p>\n\n<pre><code>function quality_certificates(){\n echo '&lt;tr&gt;TEST&lt;/tr&gt;';\n}\n</code></pre>\n\n<p>this was the visual output: <em>(I actually initially tested with the Twenty Seventeen theme; sorry about that. But this one is tested with Storefront)</em></p>\n\n<p><img src=\"https://image.ibb.co/kJJN9K/image.png\"></p>\n\n<p>Then I started thinking that the problem <em>might</em> be the markup, so I changed it to:</p>\n\n<pre><code>&lt;tr&gt;&lt;td colspan=\"6\"&gt;TEST&lt;/td&gt;&lt;/tr&gt;\n</code></pre>\n\n<p>and voila! I got the expected visual output:</p>\n\n<p><img src=\"https://image.ibb.co/haKjOe/image.png\"></p>\n\n<p>So, <strong>use the proper markup/HTML</strong>. =)</p>\n\n<p><em>PS: Those are <strong>actual</strong> screenshots. ;-)</em></p>\n" } ]
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_action('woocommerce_after_cart_table', 'custom_cart_function');\n</code></pre>\n" }, { "answer_id": 315644, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<p>You already have the right \"action\", which is <code>woocommerce_after_cart_contents</code>.</p>\n\n<p>But when I tried the markup you used:</p>\n\n<pre><code>function quality_certificates(){\n echo '&lt;tr&gt;TEST&lt;/tr&gt;';\n}\n</code></pre>\n\n<p>this was the visual output: <em>(I actually initially tested with the Twenty Seventeen theme; sorry about that. But this one is tested with Storefront)</em></p>\n\n<p><img src=\"https://image.ibb.co/kJJN9K/image.png\"></p>\n\n<p>Then I started thinking that the problem <em>might</em> be the markup, so I changed it to:</p>\n\n<pre><code>&lt;tr&gt;&lt;td colspan=\"6\"&gt;TEST&lt;/td&gt;&lt;/tr&gt;\n</code></pre>\n\n<p>and voila! I got the expected visual output:</p>\n\n<p><img src=\"https://image.ibb.co/haKjOe/image.png\"></p>\n\n<p>So, <strong>use the proper markup/HTML</strong>. =)</p>\n\n<p><em>PS: Those are <strong>actual</strong> screenshots. ;-)</em></p>\n" } ]
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_action('woocommerce_after_cart_table', 'custom_cart_function');\n</code></pre>\n" }, { "answer_id": 315644, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<p>You already have the right \"action\", which is <code>woocommerce_after_cart_contents</code>.</p>\n\n<p>But when I tried the markup you used:</p>\n\n<pre><code>function quality_certificates(){\n echo '&lt;tr&gt;TEST&lt;/tr&gt;';\n}\n</code></pre>\n\n<p>this was the visual output: <em>(I actually initially tested with the Twenty Seventeen theme; sorry about that. But this one is tested with Storefront)</em></p>\n\n<p><img src=\"https://image.ibb.co/kJJN9K/image.png\"></p>\n\n<p>Then I started thinking that the problem <em>might</em> be the markup, so I changed it to:</p>\n\n<pre><code>&lt;tr&gt;&lt;td colspan=\"6\"&gt;TEST&lt;/td&gt;&lt;/tr&gt;\n</code></pre>\n\n<p>and voila! I got the expected visual output:</p>\n\n<p><img src=\"https://image.ibb.co/haKjOe/image.png\"></p>\n\n<p>So, <strong>use the proper markup/HTML</strong>. =)</p>\n\n<p><em>PS: Those are <strong>actual</strong> screenshots. ;-)</em></p>\n" } ]
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>[email protected]</p> <p>[email protected]</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_action('woocommerce_after_cart_table', 'custom_cart_function');\n</code></pre>\n" }, { "answer_id": 315644, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<p>You already have the right \"action\", which is <code>woocommerce_after_cart_contents</code>.</p>\n\n<p>But when I tried the markup you used:</p>\n\n<pre><code>function quality_certificates(){\n echo '&lt;tr&gt;TEST&lt;/tr&gt;';\n}\n</code></pre>\n\n<p>this was the visual output: <em>(I actually initially tested with the Twenty Seventeen theme; sorry about that. But this one is tested with Storefront)</em></p>\n\n<p><img src=\"https://image.ibb.co/kJJN9K/image.png\"></p>\n\n<p>Then I started thinking that the problem <em>might</em> be the markup, so I changed it to:</p>\n\n<pre><code>&lt;tr&gt;&lt;td colspan=\"6\"&gt;TEST&lt;/td&gt;&lt;/tr&gt;\n</code></pre>\n\n<p>and voila! I got the expected visual output:</p>\n\n<p><img src=\"https://image.ibb.co/haKjOe/image.png\"></p>\n\n<p>So, <strong>use the proper markup/HTML</strong>. =)</p>\n\n<p><em>PS: Those are <strong>actual</strong> screenshots. ;-)</em></p>\n" } ]
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: [email protected] [email protected] 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} = wp.editor;\n</code></pre>\n\n<p>then inside the <strong>InspectorControls</strong> you call the component</p>\n\n<pre><code>&lt;PanelColorSettings\n title={ __( 'Color Settings' ) }\n colorSettings={ [\n {\n value: color,\n onChange: ( colorValue ) =&gt; setAttributes( { color: colorValue } ),\n label: __( 'Background Color' ),\n },\n {\n value: textColor,\n onChange: ( colorValue ) =&gt; setAttributes( { textColor: colorValue } ),\n label: __( 'Text Color' ),\n },\n ] }\n &gt;\n\n&lt;/PanelColorSettings&gt;\n</code></pre>\n" }, { "answer_id": 351977, "author": "Kaleb Heitzman", "author_id": 36597, "author_profile": "https://wordpress.stackexchange.com/users/36597", "pm_score": 1, "selected": false, "text": "<pre><code>&lt;PanelColorSettings\n title={__('Color Settings')}\n colorSettings={[\n {\n value: props.attributes.backgroundColor,\n onChange: (color) =&gt; props.setAttributes({ backgroundColor: color }),\n label: __('Background Color')\n },\n {\n value: props.attributes.textColor,\n onChange: (color) =&gt; props.setAttributes({ textColor: color }),\n label: __('Text Color'),\n colors: [\n {\n name: 'white',\n color: '#fff'\n },\n {\n name: 'black',\n color: '#222'\n }\n ]\n }\n ]}\n/&gt;\n</code></pre>\n" } ]
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} = wp.editor;\n</code></pre>\n\n<p>then inside the <strong>InspectorControls</strong> you call the component</p>\n\n<pre><code>&lt;PanelColorSettings\n title={ __( 'Color Settings' ) }\n colorSettings={ [\n {\n value: color,\n onChange: ( colorValue ) =&gt; setAttributes( { color: colorValue } ),\n label: __( 'Background Color' ),\n },\n {\n value: textColor,\n onChange: ( colorValue ) =&gt; setAttributes( { textColor: colorValue } ),\n label: __( 'Text Color' ),\n },\n ] }\n &gt;\n\n&lt;/PanelColorSettings&gt;\n</code></pre>\n" }, { "answer_id": 351977, "author": "Kaleb Heitzman", "author_id": 36597, "author_profile": "https://wordpress.stackexchange.com/users/36597", "pm_score": 1, "selected": false, "text": "<pre><code>&lt;PanelColorSettings\n title={__('Color Settings')}\n colorSettings={[\n {\n value: props.attributes.backgroundColor,\n onChange: (color) =&gt; props.setAttributes({ backgroundColor: color }),\n label: __('Background Color')\n },\n {\n value: props.attributes.textColor,\n onChange: (color) =&gt; props.setAttributes({ textColor: color }),\n label: __('Text Color'),\n colors: [\n {\n name: 'white',\n color: '#fff'\n },\n {\n name: 'black',\n color: '#222'\n }\n ]\n }\n ]}\n/&gt;\n</code></pre>\n" } ]
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_menu_item', 10, 2 );\nfunction your_custom_menu_item ( $items, $args ) {\n if ($args-&gt;theme_location == '[YOUR-MENU-LOCATION]') {\n $items .= '--YOUR EXTRA STUFF HERE--';\n }\n return $items;\n}\n</code></pre>\n\n<p>Hope it will help!</p>\n" }, { "answer_id": 361326, "author": "Rostyk Chaikivskyi", "author_id": 184737, "author_profile": "https://wordpress.stackexchange.com/users/184737", "pm_score": 0, "selected": false, "text": "<p>The point is that <code>dynamic_sidebar</code> does <code>echo</code> and we need to get its content not <code>echo</code> it inside <code>wp_nav_menu</code>.\nTry to do like this:</p>\n\n<pre><code>ob_start();\n$sidebar = dynamic_sidebar( 'recipes-dropdown' );\n$sidebar = ob_get_contents();\n$item_output .= $sidebar;\nob_end_clean();\n</code></pre>\n\n<p>This helped me to make it work.</p>\n" } ]
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 ...</p>\n\n<pre><code>function woocommerce_account_orders( $current_page ) {\n $current_page = empty( $current_page ) ? 1 : absint( $current_page );\n $customer_orders = wc_get_orders( apply_filters( 'woocommerce_my_account_my_orders_query', array(\n 'page' =&gt; $current_page,\n 'paginate' =&gt; true,\n\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'mycustom_id',\n 'value' =&gt; get_current_user_id(),\n 'compare' =&gt; '='\n )\n )\n\n ) ) );\n\n wc_get_template(\n 'myaccount/orders.php',\n array(\n 'current_page' =&gt; absint( $current_page ),\n 'customer_orders' =&gt; $customer_orders,\n 'has_orders' =&gt; 0 &lt; $customer_orders-&gt;total,\n )\n );\n}\n</code></pre>\n\n<p>This basically says get all the orders where order <code>meta_key = 'mycustom_id'</code> and <code>meta_value = $current_user_id</code>.</p>\n" }, { "answer_id": 409690, "author": "phagento", "author_id": 145553, "author_profile": "https://wordpress.stackexchange.com/users/145553", "pm_score": 1, "selected": false, "text": "<p>I know this is very old but I would just like to share the solution.</p>\n<p>Apparently, WooCommerce is ignoring the meta_query parameter. What you should do is something like:</p>\n<pre><code>function woocommerce_account_orders( $current_page ) {\n $current_page = empty( $current_page ) ? 1 : absint( $current_page );\n $customer_orders = wc_get_orders( apply_filters( 'woocommerce_my_account_my_orders_query', array(\n 'customer' =&gt; get_current_user_id(),\n 'mycustom_id' =&gt; get_current_user_id(),\n 'page' =&gt; $current_page,\n 'paginate' =&gt; true,\n 'meta_key' =&gt; 'mycustom_id',\n 'meta_compare' =&gt; '=',\n 'meta_value' =&gt; get_current_user_id(),\n ) ) );\n\n wc_get_template(\n 'myaccount/orders.php',\n array(\n 'current_page' =&gt; absint( $current_page ),\n 'customer_orders' =&gt; $customer_orders,\n 'has_orders' =&gt; 0 &lt; $customer_orders-&gt;total,\n )\n );\n}\n</code></pre>\n" } ]
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 ...</p>\n\n<pre><code>function woocommerce_account_orders( $current_page ) {\n $current_page = empty( $current_page ) ? 1 : absint( $current_page );\n $customer_orders = wc_get_orders( apply_filters( 'woocommerce_my_account_my_orders_query', array(\n 'page' =&gt; $current_page,\n 'paginate' =&gt; true,\n\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'mycustom_id',\n 'value' =&gt; get_current_user_id(),\n 'compare' =&gt; '='\n )\n )\n\n ) ) );\n\n wc_get_template(\n 'myaccount/orders.php',\n array(\n 'current_page' =&gt; absint( $current_page ),\n 'customer_orders' =&gt; $customer_orders,\n 'has_orders' =&gt; 0 &lt; $customer_orders-&gt;total,\n )\n );\n}\n</code></pre>\n\n<p>This basically says get all the orders where order <code>meta_key = 'mycustom_id'</code> and <code>meta_value = $current_user_id</code>.</p>\n" }, { "answer_id": 409690, "author": "phagento", "author_id": 145553, "author_profile": "https://wordpress.stackexchange.com/users/145553", "pm_score": 1, "selected": false, "text": "<p>I know this is very old but I would just like to share the solution.</p>\n<p>Apparently, WooCommerce is ignoring the meta_query parameter. What you should do is something like:</p>\n<pre><code>function woocommerce_account_orders( $current_page ) {\n $current_page = empty( $current_page ) ? 1 : absint( $current_page );\n $customer_orders = wc_get_orders( apply_filters( 'woocommerce_my_account_my_orders_query', array(\n 'customer' =&gt; get_current_user_id(),\n 'mycustom_id' =&gt; get_current_user_id(),\n 'page' =&gt; $current_page,\n 'paginate' =&gt; true,\n 'meta_key' =&gt; 'mycustom_id',\n 'meta_compare' =&gt; '=',\n 'meta_value' =&gt; get_current_user_id(),\n ) ) );\n\n wc_get_template(\n 'myaccount/orders.php',\n array(\n 'current_page' =&gt; absint( $current_page ),\n 'customer_orders' =&gt; $customer_orders,\n 'has_orders' =&gt; 0 &lt; $customer_orders-&gt;total,\n )\n );\n}\n</code></pre>\n" } ]
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>\n\n<p>Any extra folder or file that exists in your parent theme <strong>can not</strong> be overridden, unless the developer is using actions and filters that allows you to hook into them. Therefore, a simple <code>require()</code> or <code>include()</code> can't be overridden by a child theme.</p>\n\n<p>What you can do is to track the template file that is calling the files from the <code>inc</code> folder, and then override those in your theme's folder. You might need to go as back as <code>functions.php</code>.</p>\n\n<p>For a complete list of default template files, take a look at the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"noreferrer\">template hierarchy</a>.</p>\n" }, { "answer_id": 351883, "author": "Will", "author_id": 177855, "author_profile": "https://wordpress.stackexchange.com/users/177855", "pm_score": 0, "selected": false, "text": "<p>Certain parent themes use locate_template(), which does allow child themes to override non-default files in the parent theme. It's just something the parent theme has to support.</p>\n" } ]
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 parent theme. Child themes are often used when you want to customize or tweak an existing WordPress theme without losing the ability to upgrade that theme.</p>\n\n<p>Any confusion u please tell.</p>\n" }, { "answer_id": 315805, "author": "CoffeeAtMidnight", "author_id": 137723, "author_profile": "https://wordpress.stackexchange.com/users/137723", "pm_score": 0, "selected": false, "text": "<p>hopefully I'm understanding correctly, if not, please explain.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>If you're only going to use the admin interface, and not code anything, you probably don't need a child theme.</p>\n\n<p>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.</p>\n\n<p>Make a little more sense?</p>\n" }, { "answer_id": 315807, "author": "Ruden Ruven", "author_id": 149302, "author_profile": "https://wordpress.stackexchange.com/users/149302", "pm_score": 0, "selected": false, "text": "<p>you use child themes when you plan to customize the FILES for a theme. if you do not use child themes your changes might be overriden when updating the theme.</p>\n\n<p>the \"additional css\" option doesnt change files. this code is stored inside the database.</p>\n\n<p>so, if you plan on changing theme file content, use child theme if you want to be able to update. if not, it doesnt matter</p>\n" }, { "answer_id": 315813, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>From what I understand using a child theme is important if I don't\n want to loose anything when updating the theme. I am a beginner at\n WordPress and so far I have been customizing my site using\n PageBuilder, the onboard customize option on the admin panel and\n putting in a few lines of CSS in the \"additional CSS\" option.</p>\n</blockquote>\n\n<p>None of these changes will be affected by a theme update. The reason changes to themes will be lost when the theme is updated is because when a theme is updated all the files in the theme folder are deleted and replaced with new versions. So if you have modified any of these theme <em>files</em> then those changes will be lost because the file has been replaced.</p>\n\n<p>The types of changes you're referring to are using settings provided by the theme and saved in the database, so they will not be affected if the theme files are replaced.</p>\n\n<p>The theme being a parent theme is not actually relevant here. That's a common misconception. What <em>is</em> relevant is whether or not the theme can be updated, because it's the update process that breaks things. If you download a 3rd-party child theme and modify its files, those changes will also be lost if the theme updated, regardless of whether or not it's a child theme.</p>\n\n<p>It's actually the act of create a brand new theme (child or not) that means your changes can't be lost to an update. This is because no one else will release an update to your theme. Being a child theme just means that you get this benefit while getting to keep all the styles and functionality of another theme.</p>\n\n<blockquote>\n <p>I don't understand if I can design my child theme the exact way I did\n with the parent theme through the admin interface or if I have to code\n everything separately through text editors (on my computer and then\n upload theese through for example an FTP).</p>\n \n <p>Can I still use PageBuilder and all of theese extra CSS lines I\n previously had?</p>\n</blockquote>\n\n<p>It ultimately depends on how the original parent theme was built, but usually a child theme will work exactly the same as the original, so you'll still be able to use the page builder.</p>\n\n<p>Lines of CSS saved to Additional CSS are saved per-theme, so when you switch to the child theme you'll need to copy and paste any CSS from the Additional CSS section.</p>\n\n<blockquote>\n <p>Will changes I make to the child theme through the admin panel add\n code automatically to my child theme, or will most of the changes\n still be made on the parent theme?</p>\n</blockquote>\n\n<p>When you activate the child theme you should be able to make the same types of changes that you made to the parent theme, but when you switch themes the settings will reset and you'll probably need to make them again for the child theme.</p>\n\n<p>I say \"probably\" because it's theoretically possible that the original theme saves these settings in a way that they won't reset. The specifics depend on the theme, and is something you should ask its author about.</p>\n\n<blockquote>\n <p>I've read around a bit and I just can't figure these things out. It\n feels like if you are using a parent theme, you can edit everything\n through the admin panel and so forth, but when you use a child theme\n you have to code it on your computer and then upload it all..</p>\n</blockquote>\n\n<p>Whether a theme is edited in an admin panel or by code has nothing to do with whether or not the theme is a parent or child. The point of a child theme is that <em>if</em> you want to make code changes to the theme, you should do it through a child theme. </p>\n\n<p>Making code changes to a theme that isn't yours isn't safe, because updates can erase the changes, so you should use either a child theme or create a new theme from scratch.</p>\n\n<p>Based on everything you've said though, <strong>you do not need a child theme</strong>. The types of changes you are making are safe from updates.</p>\n" } ]
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 parent theme. Child themes are often used when you want to customize or tweak an existing WordPress theme without losing the ability to upgrade that theme.</p>\n\n<p>Any confusion u please tell.</p>\n" }, { "answer_id": 315805, "author": "CoffeeAtMidnight", "author_id": 137723, "author_profile": "https://wordpress.stackexchange.com/users/137723", "pm_score": 0, "selected": false, "text": "<p>hopefully I'm understanding correctly, if not, please explain.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>If you're only going to use the admin interface, and not code anything, you probably don't need a child theme.</p>\n\n<p>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.</p>\n\n<p>Make a little more sense?</p>\n" }, { "answer_id": 315807, "author": "Ruden Ruven", "author_id": 149302, "author_profile": "https://wordpress.stackexchange.com/users/149302", "pm_score": 0, "selected": false, "text": "<p>you use child themes when you plan to customize the FILES for a theme. if you do not use child themes your changes might be overriden when updating the theme.</p>\n\n<p>the \"additional css\" option doesnt change files. this code is stored inside the database.</p>\n\n<p>so, if you plan on changing theme file content, use child theme if you want to be able to update. if not, it doesnt matter</p>\n" }, { "answer_id": 315813, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>From what I understand using a child theme is important if I don't\n want to loose anything when updating the theme. I am a beginner at\n WordPress and so far I have been customizing my site using\n PageBuilder, the onboard customize option on the admin panel and\n putting in a few lines of CSS in the \"additional CSS\" option.</p>\n</blockquote>\n\n<p>None of these changes will be affected by a theme update. The reason changes to themes will be lost when the theme is updated is because when a theme is updated all the files in the theme folder are deleted and replaced with new versions. So if you have modified any of these theme <em>files</em> then those changes will be lost because the file has been replaced.</p>\n\n<p>The types of changes you're referring to are using settings provided by the theme and saved in the database, so they will not be affected if the theme files are replaced.</p>\n\n<p>The theme being a parent theme is not actually relevant here. That's a common misconception. What <em>is</em> relevant is whether or not the theme can be updated, because it's the update process that breaks things. If you download a 3rd-party child theme and modify its files, those changes will also be lost if the theme updated, regardless of whether or not it's a child theme.</p>\n\n<p>It's actually the act of create a brand new theme (child or not) that means your changes can't be lost to an update. This is because no one else will release an update to your theme. Being a child theme just means that you get this benefit while getting to keep all the styles and functionality of another theme.</p>\n\n<blockquote>\n <p>I don't understand if I can design my child theme the exact way I did\n with the parent theme through the admin interface or if I have to code\n everything separately through text editors (on my computer and then\n upload theese through for example an FTP).</p>\n \n <p>Can I still use PageBuilder and all of theese extra CSS lines I\n previously had?</p>\n</blockquote>\n\n<p>It ultimately depends on how the original parent theme was built, but usually a child theme will work exactly the same as the original, so you'll still be able to use the page builder.</p>\n\n<p>Lines of CSS saved to Additional CSS are saved per-theme, so when you switch to the child theme you'll need to copy and paste any CSS from the Additional CSS section.</p>\n\n<blockquote>\n <p>Will changes I make to the child theme through the admin panel add\n code automatically to my child theme, or will most of the changes\n still be made on the parent theme?</p>\n</blockquote>\n\n<p>When you activate the child theme you should be able to make the same types of changes that you made to the parent theme, but when you switch themes the settings will reset and you'll probably need to make them again for the child theme.</p>\n\n<p>I say \"probably\" because it's theoretically possible that the original theme saves these settings in a way that they won't reset. The specifics depend on the theme, and is something you should ask its author about.</p>\n\n<blockquote>\n <p>I've read around a bit and I just can't figure these things out. It\n feels like if you are using a parent theme, you can edit everything\n through the admin panel and so forth, but when you use a child theme\n you have to code it on your computer and then upload it all..</p>\n</blockquote>\n\n<p>Whether a theme is edited in an admin panel or by code has nothing to do with whether or not the theme is a parent or child. The point of a child theme is that <em>if</em> you want to make code changes to the theme, you should do it through a child theme. </p>\n\n<p>Making code changes to a theme that isn't yours isn't safe, because updates can erase the changes, so you should use either a child theme or create a new theme from scratch.</p>\n\n<p>Based on everything you've said though, <strong>you do not need a child theme</strong>. The types of changes you are making are safe from updates.</p>\n" } ]
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.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters</a>). Default value is <code>'false'</code>: use paging. So it is expected behaviour when you set it to true, the sky comes falling down (if you have a big number of posts that is).</p>\n\n<p>By using only the <code>posts_per_page</code> parameter, the query will grab the number of posts you tell it to and that will be that.</p>\n" }, { "answer_id": 315854, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>If you want to prevent the API from generating pagination links, you can use the <code>found_posts</code> filter to make WordPress think there are never more than 10 posts returned from the current query.</p>\n\n<pre><code>add_filter( 'found_posts', 'wpd_disable_home_pagination', 10, 2 );\nfunction wpd_disable_home_pagination( $found_posts, $query ) {\n if ( !is_admin() &amp;&amp; $query-&gt;is_home() &amp;&amp; $query-&gt;is_main_query() &amp;&amp; $found_posts &gt; 10 ) {\n return 10;\n }\n return $found_posts;\n}\n</code></pre>\n\n<p>EDIT-</p>\n\n<p>You could redirect any paginated URL:</p>\n\n<pre><code>add_action( 'pre_get_posts', 'wpd_redirect_pagination_urls', 10, 2 );\nfunction wpd_redirect_pagination_urls( $query ) {\n if ( !is_admin() &amp;&amp; $query-&gt;is_home() &amp;&amp; $query-&gt;is_main_query() &amp;&amp; $query-&gt;is_paged() ) {\n wp_redirect( get_post_type_archive_link( 'post' ) );\n exit;\n }\n}\n</code></pre>\n" }, { "answer_id": 328236, "author": "Michael Rogers", "author_id": 77283, "author_profile": "https://wordpress.stackexchange.com/users/77283", "pm_score": 2, "selected": true, "text": "<p>This is a mistake it will retrieve of posts:</p>\n\n<pre><code> $query-&gt;set( 'nopaging' , true );\n</code></pre>\n\n<p>What you should do instead is:</p>\n\n<pre><code>if ( !is_admin() &amp;&amp; $query-&gt;is_home() &amp;&amp; $query-&gt;is_main_query() ) {\n $query-&gt;set( 'posts_per_page', 10 );\n $query-&gt;set( 'paged', '1'); // Makes /page/2/, etc links redirect to home\n $query-&gt;set( 'no_found_rows', true ); // Avoid counting rows, faster processing. \n\n }\n</code></pre>\n\n<p>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:</p>\n\n<pre><code>if (!is_home()) {\n// show pagination buttons\n}\n</code></pre>\n" } ]
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.\nAn anatomy of a WordPress Theme consists of required and recommend files.</p>\n\n<p>See <a href=\"https://developer.wordpress.org/themes/release/required-theme-files/\" rel=\"nofollow noreferrer\">developer.wordpress.org/themes/release/required-theme-files</a> and <a href=\"https://codex.wordpress.org/Theme_Development\" rel=\"nofollow noreferrer\">codex.wordpress.org/Theme_Development</a></p>\n\n<p>This simply means that you should contact the developer(s) of the theme and ask them to fix this issue.</p>\n" }, { "answer_id": 315883, "author": "Pratik Patel", "author_id": 143123, "author_profile": "https://wordpress.stackexchange.com/users/143123", "pm_score": 1, "selected": false, "text": "<p><strong>style.css</strong> file is a required file during wordpress theme installation. Because in your style.css file you have to define your theme related information.</p>\n\n<p>Please refere for more information\n<a href=\"https://developer.wordpress.org/themes/release/required-theme-files/\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 315885, "author": "Valentin Genev", "author_id": 99362, "author_profile": "https://wordpress.stackexchange.com/users/99362", "pm_score": 2, "selected": false, "text": "<p>The key part from the error is:</p>\n\n<blockquote>\n <p>The theme is missing the style.css stylesheet.</p>\n</blockquote>\n\n<p>WordPress docs on <a href=\"https://developer.wordpress.org/themes/basics/main-stylesheet-style-css/\" rel=\"nofollow noreferrer\">Main Stylesheet</a> says:</p>\n\n<blockquote>\n <p>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.</p>\n</blockquote>\n\n<p>I would suggest you to unzip the theme and look for <code>style.css</code>. If the file is there open it; there should be some commented lines that will look similar to these:</p>\n\n<pre><code>/*\nTheme Name: Twenty Seventeen\nTheme URI: https://wordpress.org/themes/twentyseventeen/\nAuthor: the WordPress team\nAuthor URI: https://wordpress.org/\nDescription: 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.\nVersion: 1.0\nLicense: GNU General Public License v2 or later\nLicense URI: http://www.gnu.org/licenses/gpl-2.0.html\nText Domain: twentyseventeen\nTags: 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\nThis theme, like WordPress, is licensed under the GPL.\nUse it to make something cool, have fun, and share what you've learned with others.\n*/\n</code></pre>\n\n<p>The following fields should be in every main stylesheet: <code>Theme Name</code>, <code>Author</code>, <code>Description</code>, <code>Version</code>, <code>License</code>, <code>License URI</code> and <code>Text Domain</code>.\nIf any of the mentioned fields are missing I strongly recommend contacting the theme provider.</p>\n\n<p>If you're the owner or the author of the theme make sure to include the mentioned lines and to include the <code>style.css</code> file in the root directory of the theme before uploading the archived theme to your WordPress installation.</p>\n\n<p>Also, make sure to read more on Main Stylesheets here: <a href=\"https://developer.wordpress.org/themes/basics/main-stylesheet-style-css/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/basics/main-stylesheet-style-css/</a></p>\n" }, { "answer_id": 326529, "author": "Pavan V", "author_id": 159587, "author_profile": "https://wordpress.stackexchange.com/users/159587", "pm_score": 0, "selected": false, "text": "<p>If there is style.css file present and even though you are facing issue then it must be a folder permission issue.\nCheck with wp-content/themes folder permissions.If you've migrated the website from one server to another server then this folder permission issue comes. Check with hosting provider or server administrator. Or else change the permission to 777.</p>\n" } ]
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', '[email protected]' ); // 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', '[email protected]' ); // 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, it is often that.</p>\n\n<p>Also, you could try the port 587 instead of 465 for TLS.</p>\n" }, { "answer_id": 318825, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 1, "selected": false, "text": "<p>Quite likely you're using the wrong encryption/port combination. You are using port 465 for tls.</p>\n\n<p>Port 465 should be used for SSL</p>\n\n<p>Port 587 should be used for TLS</p>\n" } ]
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', '[email protected]' ); // 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', '[email protected]' ); // 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 <code>woocommerce_review_order_before_order_total</code> with <code>woocommerce_review_order_after_order_total</code>, which probably now is present two times.</p>\n\n<p>If you see twice what you attached to the hook, is just because the hook is used twice.</p>\n" }, { "answer_id": 360208, "author": "Tony", "author_id": 183946, "author_profile": "https://wordpress.stackexchange.com/users/183946", "pm_score": 3, "selected": false, "text": "<p>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):</p>\n\n<pre><code>echo '&lt;tr&gt;&lt;td colspan=\"2\"&gt;My after totals text&lt;/td&gt;&lt;/tr&gt;';\n</code></pre>\n" } ]
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 WordPress pre-built functionality. you can check it out <a href=\"https://developer.wordpress.org/reference/functions/is_user_logged_in/\" rel=\"nofollow noreferrer\">here</a>. You can copy and paste my code in your functions.php if you don't understand from reference code.</p>\n<pre><code>add_action( 'init', 'check_user_loggedin' );\nfunction check_user_loggedin(){\n if ( is_user_logged_in() ) {\n wp_redirect( 'https://www.google.com' );\n } else {\n echo 'Welcome, visitor!';\n }\n}\n</code></pre>\n<p><strong>Description:</strong></p>\n<p>here <code>is_user_logged_in()</code> is checking user login status and if user login status is true then redirect to link or do whatever you like or if status is false then do something else.Here <code>wp_redirect</code> is WordPress default functionality for redirecting to specified link.</p>\n" }, { "answer_id": 316139, "author": "dhirenpatel22", "author_id": 124380, "author_profile": "https://wordpress.stackexchange.com/users/124380", "pm_score": 2, "selected": true, "text": "<p>Add below code in your <strong>functions.php</strong> 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 <strong>\"um_get_core_page( 'user' )\"</strong> with any page URL where you want to redirect logged-in users.</p>\n\n<pre><code>/* Restrict Login page to logged-in users and redirect to core user page (user profile) */\nadd_action( 'template_redirect', 'um_restrict_login_page_logged_in' );\nfunction um_restrict_login_page_logged_in() {\n if ( um_is_core_page('login') &amp;&amp; is_user_logged_in() ) {\n wp_redirect( um_get_core_page( 'user' ) );\n exit;\n }\n}\n</code></pre>\n\n<p>Hope this works!!</p>\n" } ]
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 paper//\nadd_action( 'wp_footer', 'redirect_cf7' );\n\nfunction redirect_cf7() {\n ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n document.addEventListener( 'wpcf7mailsent', function( event ) {\n if ( '4265' == event.detail.contactFormId ) { // Sends sumissions on form 4265 to the first thank you page\n var pdfLink = '[DOMAIN]/wp/wp-content/uploads/2018/06/file.pdf';\n } else if ( '4266' == event.detail.contactFormId ) { // Sends submissions on form 1070 to the second thank you page\n var pdfLink = '[DOMAIN]/wp/wp-content/uploads/2018/06/file2.pdf';\n }\n else {\n //do nothing\n }\n jQuery.get(pdfLink, (data) -&gt;\n window.location.href = jQuery(this).attr('href');\n )\n }, false );\n &lt;/script&gt;\n &lt;?php\n}\n</code></pre>\n" }, { "answer_id": 316173, "author": "Katie R.", "author_id": 147607, "author_profile": "https://wordpress.stackexchange.com/users/147607", "pm_score": 0, "selected": false, "text": "<p>CF7 has the ability to email PDFs after submission built in already.</p>\n\n<p>If you go to the Mail tab for the form, and check the \"Use Mail (2), you can write a reply email after the form in submitted.</p>\n\n<p>In the \"File Attachments\" text area, enter in:</p>\n\n<pre><code>[your-file]\nuploads/2018/10/the-media-library-url-for-PDF.pdf\n</code></pre>\n\n<p>I would copy that code exactly to that field with the correct file path - that's how I have gotten it to work</p>\n" } ]
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 attachment attributes using, as you suggested, wp_get_attachment_image_src.</p>\n\n<p>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. </p>\n\n<p>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. </p>\n\n<p>So you can call and echo those attributes like in this example:</p>\n\n<pre><code>$img_atts = wp_get_attachment_image_src(get_post_thumbnail_id( $post-&gt;ID ), 'medium');\n$img_src = $img_atts[0];\n</code></pre>\n\n<p>I use this to echo an image's dimensions (atts 1 &amp; 2) to create per-post OG tags for og:image:width and og:image:height (along with other OG tags).</p>\n\n<p>You can find more info here:\n<a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/</a></p>\n" }, { "answer_id": 407823, "author": "Jeff Leeder", "author_id": 224199, "author_profile": "https://wordpress.stackexchange.com/users/224199", "pm_score": 0, "selected": false, "text": "<p>you can add a width and height tag in the svg code to the svg tag and wordpress will see these dimensions</p>\n" } ]
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 attachment attributes using, as you suggested, wp_get_attachment_image_src.</p>\n\n<p>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. </p>\n\n<p>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. </p>\n\n<p>So you can call and echo those attributes like in this example:</p>\n\n<pre><code>$img_atts = wp_get_attachment_image_src(get_post_thumbnail_id( $post-&gt;ID ), 'medium');\n$img_src = $img_atts[0];\n</code></pre>\n\n<p>I use this to echo an image's dimensions (atts 1 &amp; 2) to create per-post OG tags for og:image:width and og:image:height (along with other OG tags).</p>\n\n<p>You can find more info here:\n<a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/</a></p>\n" }, { "answer_id": 407823, "author": "Jeff Leeder", "author_id": 224199, "author_profile": "https://wordpress.stackexchange.com/users/224199", "pm_score": 0, "selected": false, "text": "<p>you can add a width and height tag in the svg code to the svg tag and wordpress will see these dimensions</p>\n" } ]
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 attachment attributes using, as you suggested, wp_get_attachment_image_src.</p>\n\n<p>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. </p>\n\n<p>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. </p>\n\n<p>So you can call and echo those attributes like in this example:</p>\n\n<pre><code>$img_atts = wp_get_attachment_image_src(get_post_thumbnail_id( $post-&gt;ID ), 'medium');\n$img_src = $img_atts[0];\n</code></pre>\n\n<p>I use this to echo an image's dimensions (atts 1 &amp; 2) to create per-post OG tags for og:image:width and og:image:height (along with other OG tags).</p>\n\n<p>You can find more info here:\n<a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/</a></p>\n" }, { "answer_id": 407823, "author": "Jeff Leeder", "author_id": 224199, "author_profile": "https://wordpress.stackexchange.com/users/224199", "pm_score": 0, "selected": false, "text": "<p>you can add a width and height tag in the svg code to the svg tag and wordpress will see these dimensions</p>\n" } ]
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 attachment attributes using, as you suggested, wp_get_attachment_image_src.</p>\n\n<p>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. </p>\n\n<p>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. </p>\n\n<p>So you can call and echo those attributes like in this example:</p>\n\n<pre><code>$img_atts = wp_get_attachment_image_src(get_post_thumbnail_id( $post-&gt;ID ), 'medium');\n$img_src = $img_atts[0];\n</code></pre>\n\n<p>I use this to echo an image's dimensions (atts 1 &amp; 2) to create per-post OG tags for og:image:width and og:image:height (along with other OG tags).</p>\n\n<p>You can find more info here:\n<a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/</a></p>\n" }, { "answer_id": 407823, "author": "Jeff Leeder", "author_id": 224199, "author_profile": "https://wordpress.stackexchange.com/users/224199", "pm_score": 0, "selected": false, "text": "<p>you can add a width and height tag in the svg code to the svg tag and wordpress will see these dimensions</p>\n" } ]
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 attachment attributes using, as you suggested, wp_get_attachment_image_src.</p>\n\n<p>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. </p>\n\n<p>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. </p>\n\n<p>So you can call and echo those attributes like in this example:</p>\n\n<pre><code>$img_atts = wp_get_attachment_image_src(get_post_thumbnail_id( $post-&gt;ID ), 'medium');\n$img_src = $img_atts[0];\n</code></pre>\n\n<p>I use this to echo an image's dimensions (atts 1 &amp; 2) to create per-post OG tags for og:image:width and og:image:height (along with other OG tags).</p>\n\n<p>You can find more info here:\n<a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/</a></p>\n" }, { "answer_id": 407823, "author": "Jeff Leeder", "author_id": 224199, "author_profile": "https://wordpress.stackexchange.com/users/224199", "pm_score": 0, "selected": false, "text": "<p>you can add a width and height tag in the svg code to the svg tag and wordpress will see these dimensions</p>\n" } ]
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 attachment attributes using, as you suggested, wp_get_attachment_image_src.</p>\n\n<p>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. </p>\n\n<p>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. </p>\n\n<p>So you can call and echo those attributes like in this example:</p>\n\n<pre><code>$img_atts = wp_get_attachment_image_src(get_post_thumbnail_id( $post-&gt;ID ), 'medium');\n$img_src = $img_atts[0];\n</code></pre>\n\n<p>I use this to echo an image's dimensions (atts 1 &amp; 2) to create per-post OG tags for og:image:width and og:image:height (along with other OG tags).</p>\n\n<p>You can find more info here:\n<a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/</a></p>\n" }, { "answer_id": 407823, "author": "Jeff Leeder", "author_id": 224199, "author_profile": "https://wordpress.stackexchange.com/users/224199", "pm_score": 0, "selected": false, "text": "<p>you can add a width and height tag in the svg code to the svg tag and wordpress will see these dimensions</p>\n" } ]
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 attachment.</p>\n\n<p>You can do this by using the <a href=\"http://codex.wordpress.org/Function_Reference/register_taxonomy_for_object_type\" rel=\"nofollow noreferrer\">register_taxonomy_for_object_type()</a> function. In your plugin file or theme functions file, add the following:</p>\n\n<pre><code>function wp_add_categories_to_attachments() {\n register_taxonomy_for_object_type( 'category', 'attachment' );\n}\nadd_action( 'init' , 'wp_add_categories_to_attachments' );\n</code></pre>\n" }, { "answer_id": 316452, "author": "gdfgdfg", "author_id": 152132, "author_profile": "https://wordpress.stackexchange.com/users/152132", "pm_score": 0, "selected": false, "text": "<p>This fix the problem:\n<code>wp_set_object_terms($attachment_id, 'poster', 'category', true);</code></p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_set_object_terms/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_set_object_terms/</a></p>\n" } ]
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 attachment.</p>\n\n<p>You can do this by using the <a href=\"http://codex.wordpress.org/Function_Reference/register_taxonomy_for_object_type\" rel=\"nofollow noreferrer\">register_taxonomy_for_object_type()</a> function. In your plugin file or theme functions file, add the following:</p>\n\n<pre><code>function wp_add_categories_to_attachments() {\n register_taxonomy_for_object_type( 'category', 'attachment' );\n}\nadd_action( 'init' , 'wp_add_categories_to_attachments' );\n</code></pre>\n" }, { "answer_id": 316452, "author": "gdfgdfg", "author_id": 152132, "author_profile": "https://wordpress.stackexchange.com/users/152132", "pm_score": 0, "selected": false, "text": "<p>This fix the problem:\n<code>wp_set_object_terms($attachment_id, 'poster', 'category', true);</code></p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_set_object_terms/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_set_object_terms/</a></p>\n" } ]
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><code>function my_custom_rewrite_tag() {\n add_rewrite_tag('%xxx%', '([^&amp;]+)'); //change the regex to your needs\n add_rewrite_tag('%yyy%', '([^&amp;]+)'); //change the regex to your needs\n}\nadd_action('init', 'my_custom_rewrite_tag', 10, 0);\n\n\nfunction my_custom_rewrite_rule() {\n add_rewrite_rule('^tour/([^/]*)/([^/]*)/?','index.php?pagename=tour&amp;xxx=$matches[1]&amp;yyy=$matches[2]','top');\n}\nadd_action('init', 'my_custom_rewrite_rule', 10, 0);\n</code></pre>\n\n<p>Finally, do not forget to flash the permalinks structure from your dashboard.</p>\n" }, { "answer_id": 317460, "author": "user66981", "author_id": 152230, "author_profile": "https://wordpress.stackexchange.com/users/152230", "pm_score": 0, "selected": false, "text": "<p>I just modify {4} => + sign</p>\n\n<p>my all posts is working proper. </p>\n\n<p>{4} means it's taking only 4 digit of tourid</p>\n\n<p>rest of code is same.</p>\n\n<pre><code>add_action('init', 'pub_rewrite_rules');\n\nfunction pub_rewrite_rules() {\n global $wp_rewrite;\n $wp_rewrite-&gt;add_rewrite_tag( '%pstname%', '([^/]+)', 'post_type=tour&amp;name=');\n $wp_rewrite-&gt;add_rewrite_tag( '%tourid%', '([^/]+)', 'tourid=');\n $wp_rewrite-&gt;add_permastruct('tour', '/tour/%pstname%/%tourid%', array( 'walk_dirs' =&gt; false ));\n}\n</code></pre>\n" } ]
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 = array(\n 'sort_order' =&gt; 'ASC',\n 'sort_column' =&gt; 'menu_order',\n 'child_of' =&gt; $page_id\n );\n $childList = get_pages($childArgs);\n\n if($childList &amp;&amp; (!$post-&gt;post_parent || is_page(127))){ ?&gt;\n &lt;ul class=\"menu-items menu-level-1 menu-count-5\"&gt;\n &lt;?php foreach ($childList as $child) { ?&gt;\n &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;\n &lt;a href=\"\"&gt;&lt;?php echo $child-&gt;post_title; ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php } ?&gt;\n &lt;/ul&gt;\n &lt;?php } ?&gt;\n</code></pre>\n" }, { "answer_id": 316613, "author": "Gago", "author_id": 152168, "author_profile": "https://wordpress.stackexchange.com/users/152168", "pm_score": 1, "selected": true, "text": "<p>//The correct code</p>\n\n<p>functions.php</p>\n\n<pre><code> function get_page_parent_id( $id ) {\n$args = array(\n 'sort_order' =&gt; 'ASC',\n 'sort_column' =&gt; 'menu_order',\n 'child_of' =&gt; $id\n);\n$args = get_pages($args);\n\nif(is_array($pages))\n $pageID = $id;\nelse {\n $pageID = wp_get_post_parent_id( $id );\n}\n\nreturn $pageID;\n\n\n}\n ?&gt;\n</code></pre>\n\n<p>page.php</p>\n\n<pre><code>&lt;?php\n $parentID = get_page_parent_id(get_the_ID());\n\n $childArgs = array(\n 'sort_order' =&gt; 'ASC',\n 'sort_column' =&gt; 'menu_order',\n 'child_of' =&gt; $parentID\n ); ?&gt;\n &lt;div class=\"subnav\"&gt;\n &lt;h3 class=\"subnav-headline\"&gt;&lt;a href=\"/over-ons\" class=\"c-dark\"&gt;&lt;?php echo get_the_title($parentID); ?&gt;&lt;/a&gt;&lt;/h3&gt;\n\n &lt;ul class=\"menu-items menu-level-1 menu-count-5\"&gt;\n &lt;?php $pages = get_pages($childArgs);\n foreach($pages as $page ) { ?&gt;\n &lt;li class=\"menu-item item-number-2 item-id-84286 item-even item-page item-node item-alias-over-ons-geschiedenis-leonidas\"&gt;&lt;a href=\"&lt;?php echo get_the_permalink($page);?&gt;\"&gt;&lt;?php echo $page-&gt;post_title;?&gt;&lt;/a&gt;&lt;/li&gt;\n &lt;?php } ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n</code></pre>\n" } ]
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 = array(\n 'sort_order' =&gt; 'ASC',\n 'sort_column' =&gt; 'menu_order',\n 'child_of' =&gt; $page_id\n );\n $childList = get_pages($childArgs);\n\n if($childList &amp;&amp; (!$post-&gt;post_parent || is_page(127))){ ?&gt;\n &lt;ul class=\"menu-items menu-level-1 menu-count-5\"&gt;\n &lt;?php foreach ($childList as $child) { ?&gt;\n &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;\n &lt;a href=\"\"&gt;&lt;?php echo $child-&gt;post_title; ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php } ?&gt;\n &lt;/ul&gt;\n &lt;?php } ?&gt;\n</code></pre>\n" }, { "answer_id": 316613, "author": "Gago", "author_id": 152168, "author_profile": "https://wordpress.stackexchange.com/users/152168", "pm_score": 1, "selected": true, "text": "<p>//The correct code</p>\n\n<p>functions.php</p>\n\n<pre><code> function get_page_parent_id( $id ) {\n$args = array(\n 'sort_order' =&gt; 'ASC',\n 'sort_column' =&gt; 'menu_order',\n 'child_of' =&gt; $id\n);\n$args = get_pages($args);\n\nif(is_array($pages))\n $pageID = $id;\nelse {\n $pageID = wp_get_post_parent_id( $id );\n}\n\nreturn $pageID;\n\n\n}\n ?&gt;\n</code></pre>\n\n<p>page.php</p>\n\n<pre><code>&lt;?php\n $parentID = get_page_parent_id(get_the_ID());\n\n $childArgs = array(\n 'sort_order' =&gt; 'ASC',\n 'sort_column' =&gt; 'menu_order',\n 'child_of' =&gt; $parentID\n ); ?&gt;\n &lt;div class=\"subnav\"&gt;\n &lt;h3 class=\"subnav-headline\"&gt;&lt;a href=\"/over-ons\" class=\"c-dark\"&gt;&lt;?php echo get_the_title($parentID); ?&gt;&lt;/a&gt;&lt;/h3&gt;\n\n &lt;ul class=\"menu-items menu-level-1 menu-count-5\"&gt;\n &lt;?php $pages = get_pages($childArgs);\n foreach($pages as $page ) { ?&gt;\n &lt;li class=\"menu-item item-number-2 item-id-84286 item-even item-page item-node item-alias-over-ons-geschiedenis-leonidas\"&gt;&lt;a href=\"&lt;?php echo get_the_permalink($page);?&gt;\"&gt;&lt;?php echo $page-&gt;post_title;?&gt;&lt;/a&gt;&lt;/li&gt;\n &lt;?php } ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n</code></pre>\n" } ]
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( function ( section ) { \n\n section.expanded.bind( function( isExpanding ) {\n\n if(isExpanding){\n\n console.log(section);\n }\n\n\n });\n\n\n });\n});\n</code></pre>\n" }, { "answer_id": 402549, "author": "Ankit", "author_id": 51280, "author_profile": "https://wordpress.stackexchange.com/users/51280", "pm_score": 0, "selected": false, "text": "<p>If you are targeting particular section, then you can do like:</p>\n<pre><code>wp.customize.section('title_tagline').expanded.bind(function (isExpanded) {\n if( isExpanded ) {\n // Do something here.\n }\n});\n</code></pre>\n" } ]
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( function ( section ) { \n\n section.expanded.bind( function( isExpanding ) {\n\n if(isExpanding){\n\n console.log(section);\n }\n\n\n });\n\n\n });\n});\n</code></pre>\n" }, { "answer_id": 402549, "author": "Ankit", "author_id": 51280, "author_profile": "https://wordpress.stackexchange.com/users/51280", "pm_score": 0, "selected": false, "text": "<p>If you are targeting particular section, then you can do like:</p>\n<pre><code>wp.customize.section('title_tagline').expanded.bind(function (isExpanded) {\n if( isExpanded ) {\n // Do something here.\n }\n});\n</code></pre>\n" } ]
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 numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.</p>\n\n<pre><code>function test_1234567() {\n // Get term by name ''news'' in Categories taxonomy.\n $category = get_term_by('name', 'news', 'category');\n\n // Get term by name ''news'' in Tags taxonomy.\n $tag = get_term_by('name', 'news', 'post_tag');\n\n // Get term by name ''news'' in Custom taxonomy.\n $term = get_term_by('name', 'news', 'my_custom_taxonomy');\n\n // Get term by name ''Default Menu'' from theme's nav menus.\n // (Alternative to using wp_get_nav_menu_items)\n $menu = get_term_by('name', 'Default Menu', 'nav_menu');\n\n var_dump($category);\n}\n\nadd_action( 'init', 'test_1234567' );\n</code></pre>\n\n<p>Also, you do not need to specify the priority, the default is 10.</p>\n" }, { "answer_id": 316813, "author": "djboris", "author_id": 152412, "author_profile": "https://wordpress.stackexchange.com/users/152412", "pm_score": 0, "selected": false, "text": "<p>Try something like this:</p>\n\n<pre><code>add_action( 'init', 'wpse316530_func' );\nfunction wpse316530_func()\n{\n $slug = 'uncategorized';\n $term = get_term_by('slug', $slug, 'category');\n var_dump($term);\n}\n</code></pre>\n\n<p>What I did was to remove the priority argument from <code>add_action</code> function, as you don't really need it.</p>\n" } ]
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 numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.</p>\n\n<pre><code>function test_1234567() {\n // Get term by name ''news'' in Categories taxonomy.\n $category = get_term_by('name', 'news', 'category');\n\n // Get term by name ''news'' in Tags taxonomy.\n $tag = get_term_by('name', 'news', 'post_tag');\n\n // Get term by name ''news'' in Custom taxonomy.\n $term = get_term_by('name', 'news', 'my_custom_taxonomy');\n\n // Get term by name ''Default Menu'' from theme's nav menus.\n // (Alternative to using wp_get_nav_menu_items)\n $menu = get_term_by('name', 'Default Menu', 'nav_menu');\n\n var_dump($category);\n}\n\nadd_action( 'init', 'test_1234567' );\n</code></pre>\n\n<p>Also, you do not need to specify the priority, the default is 10.</p>\n" }, { "answer_id": 316813, "author": "djboris", "author_id": 152412, "author_profile": "https://wordpress.stackexchange.com/users/152412", "pm_score": 0, "selected": false, "text": "<p>Try something like this:</p>\n\n<pre><code>add_action( 'init', 'wpse316530_func' );\nfunction wpse316530_func()\n{\n $slug = 'uncategorized';\n $term = get_term_by('slug', $slug, 'category');\n var_dump($term);\n}\n</code></pre>\n\n<p>What I did was to remove the priority argument from <code>add_action</code> function, as you don't really need it.</p>\n" } ]
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><code>&lt;?php echo do_shortcode( '[mc4wp_form id=\"id\"]' ); ?&gt;\n</code></pre>\n\n<p><code>do_shortcode()</code> is a PHP <a href=\"http://php.net/manual/en/functions.user-defined.php\" rel=\"nofollow noreferrer\">function</a> that takes a <a href=\"http://php.net/manual/en/language.types.string.php\" rel=\"nofollow noreferrer\">String</a> as an <a href=\"http://php.net/manual/en/functions.arguments.php\" rel=\"nofollow noreferrer\">argument</a>. The quotes are required to make the text a string.</p>\n" }, { "answer_id": 316549, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 2, "selected": false, "text": "<p>The common way to approach this is to use <code>do_shortcode()</code>. 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. <a href=\"https://konstantin.blog/2013/dont-do_shortcode/\" rel=\"nofollow noreferrer\">See this post for a more thorough explanation</a>.</p>\n<p>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?</p>\n<p><a href=\"https://codesymphony.co/dont-do_shortcode/\" rel=\"nofollow noreferrer\">J.D. Grimes has provided a good utility function</a> 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:</p>\n<pre><code>/**\n * Call a shortcode function by tag name.\n *\n * @author J.D. Grimes\n * @link https://codesymphony.co/dont-do_shortcode/\n *\n * @param string $tag The shortcode whose function to call.\n * @param array $atts The attributes to pass to the shortcode function. Optional.\n * @param array $content The shortcode's content. Default is null (none).\n *\n * @return string|bool False on failure, the result of the shortcode on success.\n */\nfunction do_shortcode_func( $tag, array $atts = array(), $content = null ) {\n \n global $shortcode_tags;\n \n if ( ! isset( $shortcode_tags[ $tag ] ) )\n return false;\n \n return call_user_func( $shortcode_tags[ $tag ], $atts, $content, $tag );\n}\n</code></pre>\n<p>Then you can call your shortcode this way:</p>\n<pre><code>echo do_shortcode_func( 'mc4wp_form', array( 'id' =&gt; 'id' ) );\n</code></pre>\n" } ]
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 are on. This is fine as a workaround, but it isn't really solving your problem, especially if you have lots of pages/widgets.</p>\n\n<p>B. Call a different widget area in your template file with conditional logic</p>\n\n<pre><code>&lt;ul class=\"row\"&gt;\n &lt;?php if(is_page('my-page')){\n dynamic_sidebar('footer-sidebarprestige');\n } ?&gt; \n&lt;/ul&gt;\n</code></pre>\n\n<p>C. Use a plugin like <a href=\"https://wordpress.org/plugins/widget-logic/\" rel=\"nofollow noreferrer\">Widget Logic</a> to use conditional logic on the widgets themselves. You can then add a condition like <code>is_page('my-page')</code> for displaying the widget, on a widget-per-widget basis.</p>\n" }, { "answer_id": 316553, "author": "Remzi Cavdar", "author_id": 149484, "author_profile": "https://wordpress.stackexchange.com/users/149484", "pm_score": 0, "selected": false, "text": "<p>What I understand is that you want to display a widget on specific pages, right?\nYou could use a plugin for that: <a href=\"https://wordpress.org/plugins/widget-context/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/widget-context/</a></p>\n" }, { "answer_id": 316555, "author": "Joe", "author_id": 146043, "author_profile": "https://wordpress.stackexchange.com/users/146043", "pm_score": 0, "selected": false, "text": "<p>Figured it out with below code:</p>\n\n<pre><code>&lt;ul class=\"row\"&gt;\n\n &lt;?php if ( is_page( 1111 )) : ?&gt;\n &lt;?php dynamic_sidebar('footer-sidebarprestige'); ?&gt;\n &lt;?php else :?&gt;\n &lt;?php dynamic_sidebar('footer-sidebar'); ?&gt;\n &lt;?php endif; ?&gt;\n\n &lt;/ul&gt;\n</code></pre>\n\n<p>Thank you Pim, you sent me on the right track to get my answer</p>\n" } ]
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 the page output. </p>\n\n<p>So the visual output will not be affected. And a very minor effect on the database or processing of the post content.</p>\n\n<p>If you are really concerned about the extra stuff, then you could use <code>the_content</code> filter to remove extra <code>&amp;nbsp;</code> in the content. But you would have to be careful that your filter didn't remove <code>&amp;nbsp;</code> that really needed to be in the content. </p>\n\n<p>Which is why I don't think that the effort to remove is worth it, and may cause unexpected problems.</p>\n\n<p><strong>Added</strong></p>\n\n<p>If you really want to get rid of the extra spaces in the posts, then see the answer <a href=\"https://wordpress.stackexchange.com/questions/35931/how-can-i-edit-post-data-before-it-is-saved\">here</a>, where the <a href=\"http://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data\" rel=\"nofollow noreferrer\">wp_insert_post_data</a> filter is used. That filter fires when the post is saved via the editor.</p>\n\n<p>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: <a href=\"https://regex101.com/\" rel=\"nofollow noreferrer\">https://regex101.com/</a> . I like that site, because it explains things and also creates the PHP code needed to do the Regex.)</p>\n" }, { "answer_id": 316586, "author": "Liam Stewart", "author_id": 121955, "author_profile": "https://wordpress.stackexchange.com/users/121955", "pm_score": 0, "selected": false, "text": "<p>Navigate in your theme files and look for where the content is printing.</p>\n\n<p>You will be looking for a line of code similar to this:</p>\n\n<pre><code>the_content();\n</code></pre>\n\n<p>Replace it with this:</p>\n\n<pre><code>$content = get_the_content(); //grabs the content\n$content = apply_filters('the_content', $content); //adds edit filter\n$content = str_replace('&lt;p&gt;&amp;nbsp;&lt;/p&gt;', '', $content); //replaces line break\necho $content; //prints content\n</code></pre>\n\n<p>It will remove all instances of <code>&lt;p&gt;&amp;nbsp;&lt;/p&gt;</code> with an empty string. This only changes it on the front end, not actually changing how your posts are saved in the database.</p>\n" } ]
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, '[email protected]' );</code></p> <p>I'm assuming that I will either need to update it to</p> <p><code>$emails = array( $email, '[email protected], [email protected]' );</code></p> <p>or</p> <p><code>$emails = array( $email, '[email protected]','[email protected]' );</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>$emails = array( $email, '[email protected]','[email protected]' );\n</code></pre>\n\n<p>Sending an array of emails, the first one (<code>$email</code>) being the dynamic email. The second and third would be hard coded values.</p>\n\n<p>This is assuming the email handler is ready to accept an array of emails to mail to.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>I see some comments regarding your first attempt: </p>\n\n<pre><code>$emails = array( $email, '[email protected], [email protected]' );\n</code></pre>\n\n<p>This is a valid array - however will pass the value of <code>[email protected], [email protected]</code> instead of <code>[email protected]</code> and <code>[email protected]</code> as separate values - which by first glance is how the code is expecting additional email addresses.</p>\n" }, { "answer_id": 316583, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>Because the code snippet is</p>\n\n<pre><code>$emails = array( $email, '[email protected]' );\n</code></pre>\n\n<p>Then I assume the second parameter of the array is the destination email address. Assuming that you don't care if all email addresses are exposed to the recipient (because they are all in the 'to' field), then this would work</p>\n\n<pre><code>$emails = array( $email, '[email protected], [email protected], [email protected]' );\n</code></pre>\n\n<p>Although I am not a fan of multiple emails on the 'to', would rather they were in a 'bcc' field. </p>\n" } ]
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, '[email protected]' );` I'm assuming that I will either need to update it to `$emails = array( $email, '[email protected], [email protected]' );` or `$emails = array( $email, '[email protected]','[email protected]' );` Any insight on which would be correct?
Looking at the snippet you provided the solution seems to be your last solution. ``` $emails = array( $email, '[email protected]','[email protected]' ); ``` 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, '[email protected], [email protected]' ); ``` This is a valid array - however will pass the value of `[email protected], [email protected]` instead of `[email protected]` and `[email protected]` 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 you're looking for does not exist</strong>.</p>\n\n<p>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.</p>\n\n<p>If you want it, I'm afraid you have to take the following steps:</p>\n\n<ul>\n<li>Add a new capability, and add it to the relevant roles</li>\n<li>Remove the standard WP access to those custom post types for those roles</li>\n<li>Implement a UI from scratch, including a listing screen, and an option page for viewing the items</li>\n</ul>\n" }, { "answer_id": 351523, "author": "Enrico", "author_id": 165023, "author_profile": "https://wordpress.stackexchange.com/users/165023", "pm_score": -1, "selected": false, "text": "<p>Just seeing this now... I have implemented something similar to what you wish to implement with the help of <a href=\"https://wordpress.stackexchange.com/users/24260/webaware\">@webaware</a> answer on <a href=\"https://wordpress.stackexchange.com/a/124992/165023\">https://wordpress.stackexchange.com/a/124992/165023</a> if you need further clarification on his code do let me know... Here to help</p>\n" } ]
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 ways that you can resolve this.</p>\n\n<h2>1. Prevent the API from sending the data</h2>\n\n<p>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:</p>\n\n<pre><code>header( 'Content-Type: text/event-stream' );\nheader( 'Cache-Control: no-cache' );\n\n// Echo whatever data you got here\n\n// Prevent the API from continuing\nexit();\n</code></pre>\n\n<p>Since this is not the standard way to use the API, it might cause some issues. I haven't tried this myself.</p>\n\n<h2>2. Use <code>admin-ajax.php</code></h2>\n\n<p>Instead of the rest API, use the admin AJAX. The implementation is the same. Basically if you use <code>json_encode()</code> alongside with <code>die();</code> you'll get the same results as rest API. The <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">codex page</a> on this topic covers almost everything. By using admin AJAX, you can fully control the headers and output type.</p>\n" }, { "answer_id": 316831, "author": "djboris", "author_id": 152412, "author_profile": "https://wordpress.stackexchange.com/users/152412", "pm_score": 0, "selected": false, "text": "<p>I am not able to test this, but can you please try altering the response headers using this hook:</p>\n\n<pre><code>add_action( 'rest_api_init', function() {\n\n remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );\n\n add_filter( 'rest_pre_serve_request', function( $value ) {\n\n header( 'Content-Type', 'text/event-stream' );\n header( 'Cache-Control', 'no-cache' );\n\n return $value;\n\n });\n}, 15 );\n</code></pre>\n\n<p>I got the idea from <a href=\"https://joshpress.net/access-control-headers-for-the-wordpress-rest-api/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 403546, "author": "Edoardo Guzzi", "author_id": 190590, "author_profile": "https://wordpress.stackexchange.com/users/190590", "pm_score": 1, "selected": false, "text": "<p>in your custom end point (<a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/</a>) you can use this part of code for change headers for the response</p>\n<pre><code> $response = new WP_REST_Response($data, 200);\n\n $response-&gt;header( 'Content-Type', 'text/event-stream' );\n $response-&gt;header( 'Cache-Control', 'no-cache' );\n $response-&gt;header( 'Access-Control-Allow-Origin', '*' ); //(this if you need to connect on the externale resource) \n\n return $response;\n</code></pre>\n" } ]
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=\"nofollow noreferrer\">WordPress/gutenberg-examples</a> with placeholder text added.</p>\n\n<pre><code>const { __, setLocaleData } = wp.i18n;\nconst { registerBlockType } = wp.blocks;\nconst { RichText } = wp.editor;\n\nsetLocaleData( window.gutenberg_examples_03_esnext.localeData, 'gutenberg-examples' );\n\nregisterBlockType( 'gutenberg-examples/example-03-editable-esnext', {\n title: __( 'Example: Editable (esnext)', 'gutenberg-examples' ),\n icon: 'universal-access-alt',\n category: 'layout',\n attributes: {\n content: {\n type: 'array',\n source: 'children',\n selector: 'p',\n },\n },\n edit: ( props ) =&gt; {\n const { attributes: { content }, setAttributes, className } = props;\n const onChangeContent = ( newContent ) =&gt; {\n setAttributes( { content: newContent } );\n };\n return (\n &lt;RichText\n tagName=\"p\"\n className={ className }\n onChange={ onChangeContent }\n value={ content }\n placeholder={__('wpse316624 placeholder text', 'custom-block')}\n /&gt;\n );\n },\n save: ( props ) =&gt; {\n return &lt;RichText.Content tagName=\"p\" value={ props.attributes.content } /&gt;;\n },\n} );\n</code></pre>\n" }, { "answer_id": 317241, "author": "Danny Cooper", "author_id": 111172, "author_profile": "https://wordpress.stackexchange.com/users/111172", "pm_score": 3, "selected": true, "text": "<p>There does seem to be a filter to modify the default: <a href=\"https://github.com/WordPress/gutenberg/blob/master/lib/client-assets.php#L1574\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/blob/master/lib/client-assets.php#L1574</a></p>\n\n<pre><code>'bodyPlaceholder' =&gt; apply_filters( 'write_your_story', __( 'Write your story', 'gutenberg' ), $post ),\n</code></pre>\n\n<p>So you should be able to use the WordPress <a href=\"https://developer.wordpress.org/reference/functions/add_filter/\" rel=\"nofollow noreferrer\">add_filter()</a> function.</p>\n" } ]
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. </p>\n\n<p>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.</p>\n\n<p>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.</p>\n" }, { "answer_id": 316649, "author": "Electron", "author_id": 148986, "author_profile": "https://wordpress.stackexchange.com/users/148986", "pm_score": 3, "selected": false, "text": "<h2>You Are Partly Correct</h2>\n\n<p>Your above code <strong>helps</strong> protects your WordPress site by only allowing login requests that come directly from your domain.</p>\n\n<p>Most brute force attacks send POST requests directly to your wp-login.php script. So requiring a POST request to have your domain as the referrer helps stop these bots.</p>\n\n<p>You could go one step further if you have a static IP by using the following code:</p>\n\n<pre><code>RewriteEngine on \nRewriteCond %{REQUEST_URI} ^(.*)?wp-login\\.php(.*)$ [OR]\nRewriteCond %{REQUEST_URI} ^(.*)?wp-admin$\nRewriteCond %{REMOTE_ADDR}!^111\\.111\\.111\\.111$\nRewriteRule ^(.*)$ - [R=403,L]\n</code></pre>\n\n<p>*Replace with your static IP address.</p>\n\n<p>*Might not work if your site is behind a DNS service such as CloudFlare.</p>\n" }, { "answer_id": 316654, "author": "tim", "author_id": 14655, "author_profile": "https://wordpress.stackexchange.com/users/14655", "pm_score": 3, "selected": false, "text": "<p><strong>What this doesn't prevent: Brute Force</strong></p>\n\n<blockquote>\n <p>all it does is prevent automatic brute force attacks?</p>\n</blockquote>\n\n<p>No. This does not prevent brute force attacks.</p>\n\n<p>In a brute force attack, an attacker has control over all parameters of the HTTP request. This includes the referer. As the attacker can send arbitrary referers, this does not prevent brute force attacks. (Almost) all brute force tools will allow the setting of a referer, and setting the site itself as a referer is pretty standard.</p>\n\n<p>Mechanisms that do protect against brute force would be banning or throttling on an IP or username basis, as well as captchas.</p>\n\n<p><strong>What this might be intended to prevent: CSRF</strong></p>\n\n<p>This code might have been indented to add a referer check to all POST requests to the admin area. If the referer is not valid, the request is rejected.</p>\n\n<p>In a CSRF attack, an attacker forces a victim to perform a state-changing POST request. This can eg happen by posting HTML and Javascript code at attacker.com, which then automatically sends a request to victim.com once an authenticated victim visits the site.</p>\n\n<p>Referer checks are one mechanism to protect against CSRF. As only victim.com is accepted as a valid referer, an attacker cannot force the victim to send a request from their own domain.</p>\n\n<p>Of course, WordPress has its own CSRF protection (via anti-CSRF nonces). But it might not catch all cases, and the security of plugins depends very much on the plugin developer.</p>\n\n<p>An additional referer-check can help prevent CSRF vulnerabilities in WP core, and especially in plugins, from being exploitable.</p>\n\n<p>Of course, if this was the intention, the code is bugged. The <code>$</code> in <code>RewriteCond %{REQUEST_URI} ^(.*)?wp-admin$</code> prevents the check for most requests.</p>\n\n<p>The check can also easily be bypassed. The following referers would be accepted:</p>\n\n<pre><code>Referer: http://example.com.org\nReferer: http://not-example.com\nReferer: http://notexample.com\nReferer: http://attacker.com/example.com\n[...]\n</code></pre>\n\n<p>To add anything to the security of the site, these two issues would need to be fixed first. The code could also be further improved by not being restricted to POST requests (in poorly-written applications, GET requests may change server-state as well, or POST requests may be transformable into GET requests). As the check only applies to administrators, this should not restrict usability.</p>\n" } ]
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. </p>\n\n<p>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.</p>\n\n<p>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.</p>\n" }, { "answer_id": 316649, "author": "Electron", "author_id": 148986, "author_profile": "https://wordpress.stackexchange.com/users/148986", "pm_score": 3, "selected": false, "text": "<h2>You Are Partly Correct</h2>\n\n<p>Your above code <strong>helps</strong> protects your WordPress site by only allowing login requests that come directly from your domain.</p>\n\n<p>Most brute force attacks send POST requests directly to your wp-login.php script. So requiring a POST request to have your domain as the referrer helps stop these bots.</p>\n\n<p>You could go one step further if you have a static IP by using the following code:</p>\n\n<pre><code>RewriteEngine on \nRewriteCond %{REQUEST_URI} ^(.*)?wp-login\\.php(.*)$ [OR]\nRewriteCond %{REQUEST_URI} ^(.*)?wp-admin$\nRewriteCond %{REMOTE_ADDR}!^111\\.111\\.111\\.111$\nRewriteRule ^(.*)$ - [R=403,L]\n</code></pre>\n\n<p>*Replace with your static IP address.</p>\n\n<p>*Might not work if your site is behind a DNS service such as CloudFlare.</p>\n" }, { "answer_id": 316654, "author": "tim", "author_id": 14655, "author_profile": "https://wordpress.stackexchange.com/users/14655", "pm_score": 3, "selected": false, "text": "<p><strong>What this doesn't prevent: Brute Force</strong></p>\n\n<blockquote>\n <p>all it does is prevent automatic brute force attacks?</p>\n</blockquote>\n\n<p>No. This does not prevent brute force attacks.</p>\n\n<p>In a brute force attack, an attacker has control over all parameters of the HTTP request. This includes the referer. As the attacker can send arbitrary referers, this does not prevent brute force attacks. (Almost) all brute force tools will allow the setting of a referer, and setting the site itself as a referer is pretty standard.</p>\n\n<p>Mechanisms that do protect against brute force would be banning or throttling on an IP or username basis, as well as captchas.</p>\n\n<p><strong>What this might be intended to prevent: CSRF</strong></p>\n\n<p>This code might have been indented to add a referer check to all POST requests to the admin area. If the referer is not valid, the request is rejected.</p>\n\n<p>In a CSRF attack, an attacker forces a victim to perform a state-changing POST request. This can eg happen by posting HTML and Javascript code at attacker.com, which then automatically sends a request to victim.com once an authenticated victim visits the site.</p>\n\n<p>Referer checks are one mechanism to protect against CSRF. As only victim.com is accepted as a valid referer, an attacker cannot force the victim to send a request from their own domain.</p>\n\n<p>Of course, WordPress has its own CSRF protection (via anti-CSRF nonces). But it might not catch all cases, and the security of plugins depends very much on the plugin developer.</p>\n\n<p>An additional referer-check can help prevent CSRF vulnerabilities in WP core, and especially in plugins, from being exploitable.</p>\n\n<p>Of course, if this was the intention, the code is bugged. The <code>$</code> in <code>RewriteCond %{REQUEST_URI} ^(.*)?wp-admin$</code> prevents the check for most requests.</p>\n\n<p>The check can also easily be bypassed. The following referers would be accepted:</p>\n\n<pre><code>Referer: http://example.com.org\nReferer: http://not-example.com\nReferer: http://notexample.com\nReferer: http://attacker.com/example.com\n[...]\n</code></pre>\n\n<p>To add anything to the security of the site, these two issues would need to be fixed first. The code could also be further improved by not being restricted to POST requests (in poorly-written applications, GET requests may change server-state as well, or POST requests may be transformable into GET requests). As the check only applies to administrators, this should not restrict usability.</p>\n" } ]
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. </p>\n\n<p>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.</p>\n\n<p>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.</p>\n" }, { "answer_id": 316649, "author": "Electron", "author_id": 148986, "author_profile": "https://wordpress.stackexchange.com/users/148986", "pm_score": 3, "selected": false, "text": "<h2>You Are Partly Correct</h2>\n\n<p>Your above code <strong>helps</strong> protects your WordPress site by only allowing login requests that come directly from your domain.</p>\n\n<p>Most brute force attacks send POST requests directly to your wp-login.php script. So requiring a POST request to have your domain as the referrer helps stop these bots.</p>\n\n<p>You could go one step further if you have a static IP by using the following code:</p>\n\n<pre><code>RewriteEngine on \nRewriteCond %{REQUEST_URI} ^(.*)?wp-login\\.php(.*)$ [OR]\nRewriteCond %{REQUEST_URI} ^(.*)?wp-admin$\nRewriteCond %{REMOTE_ADDR}!^111\\.111\\.111\\.111$\nRewriteRule ^(.*)$ - [R=403,L]\n</code></pre>\n\n<p>*Replace with your static IP address.</p>\n\n<p>*Might not work if your site is behind a DNS service such as CloudFlare.</p>\n" }, { "answer_id": 316654, "author": "tim", "author_id": 14655, "author_profile": "https://wordpress.stackexchange.com/users/14655", "pm_score": 3, "selected": false, "text": "<p><strong>What this doesn't prevent: Brute Force</strong></p>\n\n<blockquote>\n <p>all it does is prevent automatic brute force attacks?</p>\n</blockquote>\n\n<p>No. This does not prevent brute force attacks.</p>\n\n<p>In a brute force attack, an attacker has control over all parameters of the HTTP request. This includes the referer. As the attacker can send arbitrary referers, this does not prevent brute force attacks. (Almost) all brute force tools will allow the setting of a referer, and setting the site itself as a referer is pretty standard.</p>\n\n<p>Mechanisms that do protect against brute force would be banning or throttling on an IP or username basis, as well as captchas.</p>\n\n<p><strong>What this might be intended to prevent: CSRF</strong></p>\n\n<p>This code might have been indented to add a referer check to all POST requests to the admin area. If the referer is not valid, the request is rejected.</p>\n\n<p>In a CSRF attack, an attacker forces a victim to perform a state-changing POST request. This can eg happen by posting HTML and Javascript code at attacker.com, which then automatically sends a request to victim.com once an authenticated victim visits the site.</p>\n\n<p>Referer checks are one mechanism to protect against CSRF. As only victim.com is accepted as a valid referer, an attacker cannot force the victim to send a request from their own domain.</p>\n\n<p>Of course, WordPress has its own CSRF protection (via anti-CSRF nonces). But it might not catch all cases, and the security of plugins depends very much on the plugin developer.</p>\n\n<p>An additional referer-check can help prevent CSRF vulnerabilities in WP core, and especially in plugins, from being exploitable.</p>\n\n<p>Of course, if this was the intention, the code is bugged. The <code>$</code> in <code>RewriteCond %{REQUEST_URI} ^(.*)?wp-admin$</code> prevents the check for most requests.</p>\n\n<p>The check can also easily be bypassed. The following referers would be accepted:</p>\n\n<pre><code>Referer: http://example.com.org\nReferer: http://not-example.com\nReferer: http://notexample.com\nReferer: http://attacker.com/example.com\n[...]\n</code></pre>\n\n<p>To add anything to the security of the site, these two issues would need to be fixed first. The code could also be further improved by not being restricted to POST requests (in poorly-written applications, GET requests may change server-state as well, or POST requests may be transformable into GET requests). As the check only applies to administrators, this should not restrict usability.</p>\n" } ]
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_home())\n{\n\n // PUT YOUR HOME PAGE LOGO HERE\n\n}else{\n\n // PUT LOGO FOR INNER PAGES\n\n}\n</code></pre>\n\n<p>Hope it will help you!</p>\n" }, { "answer_id": 364500, "author": "marklchaves", "author_id": 177338, "author_profile": "https://wordpress.stackexchange.com/users/177338", "pm_score": 0, "selected": false, "text": "<p>This <strong>CSS</strong> only example works on the <strong>Terminus</strong> demo site on Themeforest. The only difference is that demo site didn't have a page ID. </p>\n\n<p>You'll need to look up the page/post IDs for the pages/posts you want to have different logos anyway. Then replace the example ID class I have below with your ID class.</p>\n\n<p>Here's how to get the <a href=\"https://dev.to/marklchaves/changing-up-header-logos-26c5#page-post-id\" rel=\"nofollow noreferrer\">page/post ID</a>.</p>\n\n<pre><code>/** \n * Hide the default logo. \n *\n * For posts use .postid-1 format.\n */\n.page-id-1 .logo img {\n display: none;\n}\n\n/** \n * Drop in a different logo.\n *\n * The site link is respected.\n */\n.page-id-1 .logo {\n background-image: url(https://balistreetphotographer.files.wordpress.com/2019/02/balistreetphotographer-logo-2-slashes-65.png);\n background-repeat: no-repeat;\n background-size: 100%;\n display: block;\n position: relative;\n height: 65px;\n width: 65px;\n}\n</code></pre>\n\n<p>Obviously <strong>change</strong> the logo URL and logo dimensions to yours.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 413055, "author": "Arunprasanth M", "author_id": 204208, "author_profile": "https://wordpress.stackexchange.com/users/204208", "pm_score": 0, "selected": false, "text": "<pre><code> &lt;?php if(is_front_page() || is_home()) : ?&gt;\n &lt;a href=&quot;&lt;?php echo esc_url( home_url( '/' )); ?&gt;&quot;&gt;\n&lt;img src=&quot;&lt;?php bloginfo('template_url')?&gt;/images/logo.png&quot; alt=&quot;&lt;?php echo esc_attr( get_bloginfo( 'name' ) ); ?&gt;&quot; class=&quot;logo-width&quot; alt=&quot;logo&quot;&gt;\n &lt;?php else : ?&gt;\n &lt;img src=&quot;&lt;?php bloginfo('template_url')?&gt;/images/white_logo.png&quot; alt=&quot;&lt;?php echo esc_attr( get_bloginfo( 'name' ) ); ?&gt;&quot; class=&quot;logo-width&quot; alt=&quot;white-logo&quot;&gt;\n &lt;?php endif; ?&gt;\n &lt;/a&gt;\n</code></pre>\n" } ]
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/gutenberg/blob/9297fc93a2c7b47575007127ffe038d22101de81/packages/editor/src/components/colors/utils.js\" rel=\"nofollow noreferrer\">take a look at the gutenberg files</a>).</p>\n\n<p>If you have something like</p>\n\n<pre><code>const backgroundColors = [\n {\n name: 'Light Green',\n slug: 'light-green',\n color: '#E6F0F0'\n },\n {\n name: 'Light Gray',\n slug: 'light-gray',\n color: '#F7F7F7'\n }\n ];\n</code></pre>\n\n<p>then you can get the color name by</p>\n\n<pre><code>const test = getColorObjectByColorValue(backgroundColors, backgroundColor);\nconsole.log(test.name);\n</code></pre>\n\n<p>Should also work with the default palette. </p>\n" }, { "answer_id": 381725, "author": "Sjaak Wish", "author_id": 181552, "author_profile": "https://wordpress.stackexchange.com/users/181552", "pm_score": 1, "selected": false, "text": "<p>thanks to: <a href=\"https://javascriptforwp.com/forums/topic/how-to-get-a-color-class-name/\" rel=\"nofollow noreferrer\">https://javascriptforwp.com/forums/topic/how-to-get-a-color-class-name/</a> , Note: wp.editor.getColorObjectByColorValue is deprecated now using wp.blockEditor.getColorObjectByColorValue</p>\n<pre><code> const { select } = wp.data;\n const { getColorObjectByColorValue} = wp.blockEditor;\n\n function onChangeColor ( color ) {\n colorName = '';\n if( color ) {\n const settings = select( 'core/editor' ).getEditorSettings();\n const colorObject = getColorObjectByColorValue( settings.colors, color );\n if( colorObject ) {\n colorName = colorObject.slug;\n }\n }\n props.setAttributes({color: color});\n props.setAttributes({colorName: colorName});\n\n }\n</code></pre>\n" } ]
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 number was inaccurate - but only in respect of <em>one</em> of the post types to which a term was attached.</p>\n\n<p>What was not clear to me was that the Count column is an aggregate count, displaying the count of ANY post objects attached to the corresponding term, even when the context of the taxonomy listing page was clearly clicked through from a specific post type sub-menu.</p>\n\n<p>It is likely that the above code to fix post counts worked successfully.</p>\n\n<p>The answer here lays in explaining what was going on.</p>\n" }, { "answer_id": 404236, "author": "Mort 1305", "author_id": 188811, "author_profile": "https://wordpress.stackexchange.com/users/188811", "pm_score": 1, "selected": true, "text": "<p>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 <a href=\"https://wordpress.stackexchange.com/questions/10953/fixing-category-count\">here</a> and <a href=\"https://wordpress.stackexchange.com/questions/126691/count-number-of-post-in-taxonomy\">here</a> that touch on this subject, there is no &quot;good&quot; answer on the <a href=\"https://stackexchange.com/search?q=update_post_term_count_statuses\">StackExchange family of sites</a> or <a href=\"https://stackoverflow.com/search?q=update_post_term_count_statuses\">StackOverflow</a>.)</p>\n<p>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 <code>wp-admin/edit-tags.php</code> 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.)</p>\n<p>Next, my tracing took me a private function <a href=\"https://core.trac.wordpress.org/browser/tags/5.9/src/wp-includes/taxonomy.php#L4018\" rel=\"nofollow noreferrer\"><code>_update_post_term_count()</code></a>. What I found is that the count is <a href=\"https://core.trac.wordpress.org/browser/tags/5.9/src/wp-includes/taxonomy.php#L4067\" rel=\"nofollow noreferrer\">stored in the database</a>, 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.)</p>\n<p>Anyway, back to <code>_update_post_term_count()</code>: it will only save posts of the specific post type <em>that have published status</em>. 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 <a href=\"https://core.trac.wordpress.org/browser/tags/5.9/src/wp-includes/taxonomy.php#L4041\" rel=\"nofollow noreferrer\"><code>update_post_term_count_statuses</code> hook</a> 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 &quot;All&quot; view:</p>\n<pre><code>add_filter('update_post_term_count_statuses', function($post_statuses, $taxonomy) {\n // Intercept\n if($taxonomy-&gt;name === 'mort-custom-taxonomy') {\n foreach(array(\n // Some post statuses to be included in the count ...\n 'mort-custom-post-status',\n 'draft',\n 'pending',\n 'private'\n ) as $v) {\n // Check to ensure another call hasn't already added the status.\n if(!in_array($v, $post_statuses)) {\n $post_statuses[] = $v;\n }\n }\n }\n // Return\n return $post_statuses;\n}, 10, 2);\n</code></pre>\n<p>Here's how the filter above would be called: <code>_update_post_term_count()</code> is executed by <code>wp_update_term_count_now()</code> when <code>wp_update_term_count()</code> is put into effect by <code>wp_set_object_terms()</code> and <code>_update_term_count_on_transition_post_status()</code> at the time a post is created/updated/published.</p>\n<p>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.</p>\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 number was inaccurate - but only in respect of <em>one</em> of the post types to which a term was attached.</p>\n\n<p>What was not clear to me was that the Count column is an aggregate count, displaying the count of ANY post objects attached to the corresponding term, even when the context of the taxonomy listing page was clearly clicked through from a specific post type sub-menu.</p>\n\n<p>It is likely that the above code to fix post counts worked successfully.</p>\n\n<p>The answer here lays in explaining what was going on.</p>\n" }, { "answer_id": 404236, "author": "Mort 1305", "author_id": 188811, "author_profile": "https://wordpress.stackexchange.com/users/188811", "pm_score": 1, "selected": true, "text": "<p>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 <a href=\"https://wordpress.stackexchange.com/questions/10953/fixing-category-count\">here</a> and <a href=\"https://wordpress.stackexchange.com/questions/126691/count-number-of-post-in-taxonomy\">here</a> that touch on this subject, there is no &quot;good&quot; answer on the <a href=\"https://stackexchange.com/search?q=update_post_term_count_statuses\">StackExchange family of sites</a> or <a href=\"https://stackoverflow.com/search?q=update_post_term_count_statuses\">StackOverflow</a>.)</p>\n<p>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 <code>wp-admin/edit-tags.php</code> 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.)</p>\n<p>Next, my tracing took me a private function <a href=\"https://core.trac.wordpress.org/browser/tags/5.9/src/wp-includes/taxonomy.php#L4018\" rel=\"nofollow noreferrer\"><code>_update_post_term_count()</code></a>. What I found is that the count is <a href=\"https://core.trac.wordpress.org/browser/tags/5.9/src/wp-includes/taxonomy.php#L4067\" rel=\"nofollow noreferrer\">stored in the database</a>, 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.)</p>\n<p>Anyway, back to <code>_update_post_term_count()</code>: it will only save posts of the specific post type <em>that have published status</em>. 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 <a href=\"https://core.trac.wordpress.org/browser/tags/5.9/src/wp-includes/taxonomy.php#L4041\" rel=\"nofollow noreferrer\"><code>update_post_term_count_statuses</code> hook</a> 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 &quot;All&quot; view:</p>\n<pre><code>add_filter('update_post_term_count_statuses', function($post_statuses, $taxonomy) {\n // Intercept\n if($taxonomy-&gt;name === 'mort-custom-taxonomy') {\n foreach(array(\n // Some post statuses to be included in the count ...\n 'mort-custom-post-status',\n 'draft',\n 'pending',\n 'private'\n ) as $v) {\n // Check to ensure another call hasn't already added the status.\n if(!in_array($v, $post_statuses)) {\n $post_statuses[] = $v;\n }\n }\n }\n // Return\n return $post_statuses;\n}, 10, 2);\n</code></pre>\n<p>Here's how the filter above would be called: <code>_update_post_term_count()</code> is executed by <code>wp_update_term_count_now()</code> when <code>wp_update_term_count()</code> is put into effect by <code>wp_set_object_terms()</code> and <code>_update_term_count_on_transition_post_status()</code> at the time a post is created/updated/published.</p>\n<p>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.</p>\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>srcset</code> attribute to those that are less than a given maximum width.</p>\n<p>This code will make it so that only sizes &lt; 500 pixels wide will be used in the <code>srcset</code>:</p>\n<pre><code>/**\n * @param int $max_width The maximum image width to be included in the 'srcset'. Default '1600'.\n * @param array $size_array Array of width and height values in pixels (in that order).\n */\nfunction wpse_316853_srcset_maximum_width( $max_srcset_image_width, $sizes_array ) {\n return 500;\n}\nadd_filter( 'max_srcset_image_width', 'wpse_316853_srcset_maximum_width', 10, 2 );\n</code></pre>\n<p>In your case though, you might only want to apply this limit when the original image is your 250px wide thumbnail. <code>$sizes_array</code> contains the sizes of the current image, so you can use that to check:</p>\n<pre><code>/**\n * @param int $max_width The maximum image width to be included in the 'srcset'. Default '1600'.\n * @param array $size_array Array of width and height values in pixels (in that order).\n */\nfunction wpse_316853_srcset_maximum_width( $max_srcset_image_width, $sizes_array ) {\n if ( $sizes_array[0] === 250 ) {\n $max_srcset_image_width = 500;\n }\n\n return $max_srcset_image_width;\n}\nadd_filter( 'max_srcset_image_width', 'wpse_316853_srcset_maximum_width' );\n</code></pre>\n<p>Or you could do it dynamically, so that the <code>srcset</code> will only include images up to 2x the width of the original image:</p>\n<pre><code>/**\n * @param int $max_width The maximum image width to be included in the 'srcset'. Default '1600'.\n * @param array $size_array Array of width and height values in pixels (in that order).\n */\nfunction wpse_316853_srcset_maximum_width( $max_srcset_image_width, $sizes_array ) {\n return $sizes_array[0] * 2;\n}\nadd_filter( 'max_srcset_image_width', 'wpse_316853_srcset_maximum_width' );\n</code></pre>\n" }, { "answer_id": 317247, "author": "francois", "author_id": 152357, "author_profile": "https://wordpress.stackexchange.com/users/152357", "pm_score": 0, "selected": false, "text": "<p>Thanks Jabob and sorry for the late answer. It took me time to understand just a bit and test things. I lack wordpress and php knowledge.\nThis short article helped me as well as I use ACF (advanced custom fields) :\n<a href=\"https://awesomeacf.com/responsive-images-wordpress-acf/\" rel=\"nofollow noreferrer\">https://awesomeacf.com/responsive-images-wordpress-acf/</a></p>\n\n<p><strong>I could completly manage the srcset and sizes of the main image of my articles (single.php).\nBut not the thumbnails of each articles in my blog page (taxonomy.php)</strong></p>\n\n<p>I did something close to what you wrote in your 2nd and 3rd code and it worked. The alt attribute only doesn't work unfortunatly for no reason I understand.\nHere is what I did :</p>\n\n<p>in function.php :</p>\n\n<pre><code>function responsive_feature_image($image_id,$image_size,$max_width){\n\n function remove_max_srcset_image_width( $max_width ) {\n $max_width = 1350;\n return $max_width;\n }\n add_filter( 'max_srcset_image_width', 'remove_max_srcset_image_width' );\n // check the image ID is not blank\n if($image_id != '') {\n\n // set the default src image size\n $image_src = wp_get_attachment_image_url( $image_id, $image_size );\n\n // set the srcset with various image sizes\n $image_srcset = wp_get_attachment_image_srcset( $image_id, $image_size );\n\n // generate the markup for the responsive image\n echo 'src=\"'.$image_src.'\" srcset=\"'.$image_srcset.'\" sizes=\"(max-width: 449px) 120vw, (max-width: 767px) 576px, (max-width: 1365px) calc( 100vw - 60px - 55% ), '.$max_width.'\"';\n\n }\n}\n</code></pre>\n\n<p>In single.php :</p>\n\n<pre><code>&lt;?php $img = get_field('image_principale'); ?&gt;\n &lt;div class=\"feature-image\"&gt;\n &lt;?php if( $img ): ?&gt;\n &lt;img &lt;?php responsive_feature_image($img,'featured-blog','719px'); ?&gt; alt=\"&lt;?php echo $img['alt']; ?&gt;\" /&gt;\n &lt;?php else: ?&gt;\n &lt;img src=\"&lt;?php echo get_template_directory_uri() ?&gt;/dist/images/article/feature-image-default.jpg\" alt=\"Illustration de l'article\"&gt;\n &lt;?php endif; ?&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>Unfortunatly I couldn't find out how to achieve the same for the thumbnails images of my blog page in the file taxonomy.php. The thumbnails are sorted by categories by a filter menu. It explains that the code is much much more complicated. Just in case you can help me some more.</p>\n\n<p>Here is how the thumbnails are called in taxonomy.php :</p>\n\n<pre><code> &lt;?php $displayCurrentCat = get_field('display_articles-in-page_by_category', $term); ?&gt;\n\n &lt;?php if(!$displayCurrentCat &amp;&amp; $children): ?&gt;\n\n &lt;nav class=\"filter_by_category\"&gt;\n &lt;ul&gt;\n &lt;?php if( $children ): ?&gt;\n &lt;li&gt;Filtrer les articles &lt;/li&gt;\n &lt;li data-filter=\"all\" class=\"actif\"&gt;\n &lt;a href=\"#\"&gt;Toutes les catégories&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php foreach( $children as $child ): ?&gt;\n &lt;?php $child_term = get_term($child) ?&gt;\n &lt;li data-filter=\"&lt;?php echo $child_term-&gt;term_id; ?&gt;\" &gt;\n &lt;a href=\"#\"&gt;&lt;?php echo $child_term-&gt;name; ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php endforeach; ?&gt;\n &lt;?php endif; ?&gt;\n &lt;/ul&gt;\n &lt;/nav&gt;\n\n &lt;?php endif; ?&gt; \n\n &lt;div class=\"all_the_articles tdm__posts &lt;?php if(!$displayCurrentCat){ echo'filtr-container'; } ?&gt;\"&gt;\n &lt;?php if($displayCurrentCat): ?&gt;\n &lt;div class=\"tdm__grid tdm__grid--5\"&gt;\n &lt;?php render_term_thumbnails($term); ?&gt;\n &lt;/div&gt;\n &lt;?php else: ?&gt;\n &lt;?php if( $children ): ?&gt;\n &lt;?php foreach( $children as $child ): ?&gt;\n &lt;?php $child_term = get_term($child) ?&gt;\n &lt;div class=\"filtr-item\" data-category=\"&lt;?php echo $child_term-&gt;term_id; ?&gt;\" data-sort=\"value\"&gt;\n &lt;div class=\"nom_categorie tdm__posts__cat\" &gt;\n &lt;h2&gt;&lt;?php echo $child_term-&gt;name; ?&gt;&lt;/h2&gt;\n &lt;/div&gt;\n &lt;div class=\"tdm__grid tdm__grid--5\"&gt;\n &lt;?php render_term_thumbnails($child); ?&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;?php endforeach; ?&gt;\n &lt;?php endif; ?&gt;\n &lt;?php endif; ?&gt;\n &lt;/div&gt;\n\n&lt;/div&gt;\n</code></pre>\n\n<p>Here is what's in function.php :</p>\n\n<pre><code>function render_content_thumbnail($id){\n $img = get_the_img(get_field(\"thumbnail\", $id), \"thumbnail-blog\");\n if(!$img){\n $img = '&lt;img src=\"'.get_template_directory_uri() . '/dist/images/default_thumb.png\" class=\"attachment-thumbnail-blog size-thumbnail-blog\" alt=\"default '.get_the_title($id).'\"&gt;';\n }\n $title = get_field('titre_court', $id) ? get_field('titre_court', $id) : get_the_title($id);\n echo '\n &lt;article class=\"reveal tdm__post tdm__post--'.$id.' '.get_field('couleur', $id).'\"&gt;\n &lt;a class=\"tdm__post__link\" href=\"'.get_permalink($id).'\"&gt;\n &lt;span class=\"tdm__post__thumbnail\"&gt;'.$img.'&lt;/span&gt;\n &lt;span class=\"tdm__post__title\"&gt;'.$title.'&lt;/span&gt;\n &lt;/a&gt;\n &lt;/article&gt;';\n}\n\nfunction render_term_thumbnails($term){\n $t = get_term($term);\n $args = array(\n 'post_type' =&gt; 'article',\n 'orderby' =&gt; 'menu_order',\n 'order' =&gt; 'ASC',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'categorie',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $t-&gt;slug\n ),\n ),\n );\n $tdmQuery = new WP_Query( $args );\n while ( $tdmQuery-&gt;have_posts() ) : $tdmQuery-&gt;the_post();\n render_content_thumbnail( get_the_id() );\n endwhile;\n wp_reset_postdata();\n}\n\nfunction render_term_menu($term){\n $t = get_term($term);\n $args = array(\n 'post_type' =&gt; 'article',\n 'orderby' =&gt; 'menu_order',\n 'order' =&gt; 'ASC',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'categorie',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $t-&gt;slug\n ),\n ),\n );\n $tdmQuery = new WP_Query( $args );\n while ( $tdmQuery-&gt;have_posts() ) : $tdmQuery-&gt;the_post();\n render_content_menu( get_the_id() );\n endwhile;\n wp_reset_postdata();\n}\nfunction get_the_img($att_id, $size, $diapo = false){\n\n if( $att_id ){\n $imgSrc = wp_get_attachment_image_src($att_id, $size);\n $srcset = wp_get_attachment_image_srcset($att_id, $size);\n $sizes = wp_get_attachment_image_sizes($att_id, $size);\n if(function_exists( 'get_rocket_option' ) &amp;&amp; get_rocket_option( 'lazyload' ) &amp;&amp; !is_user_logged_in() ){\n $i = '&lt;img width=\"'.$imgSrc[1].'\" class=\"-is-lazy\" height=\"'.$imgSrc[2].'\" data-lazy-src=\"'.$imgSrc[0].'\" alt=\"'.$imgSrc[3].'\" data-lazy-srcset=\"'.$srcset.'\" sizes=\"'.$sizes.'\"&gt;';\n }else {\n $i = '&lt;img width=\"'.$imgSrc[1].'\" height=\"'.$imgSrc[2].'\" src=\"'.$imgSrc[0].'\" alt=\"'.$imgSrc[3].'\" srcset=\"'.$srcset.'\" sizes=\"'.$sizes.'\"&gt;';\n }\n\n $legend = wp_get_attachment_caption($att_id);\n\n $credit = get_field('credit', $att_id);\n\n $i = $diapo ? sprintf( '&lt;div class=\"effet_photo\"&gt;%1$s&lt;/div&gt;', $i ) : $i;\n\n $i = $legend || $diapo || $credit ? sprintf( '%1$s&lt;p class=\"description_photo\"&gt;%2$s&lt;span&gt;%3$s&lt;/span&gt;&lt;/p&gt;', $i, $legend, $credit ) : $i;\n\n return $i;\n }\n}\n</code></pre>\n" } ]
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 if that's the case you'll want to review your htaccess to remove the www.my.domain.com redirect. </p>\n\n<p>If that's not the case, ie. you're trying to redirect links that have the wrong subdomain, you'll need to have a catch all subdomain, AKA wildcard subdomain. If you don't have a wildcard subdomain you might as well be redirecting to <em>thisdoesntexist.my.domain.com</em> </p>\n\n<p>If you want to redirect links that go to the wrong domain AND you have a wildcard subdomain, put this in your .htaccess file:</p>\n\n<pre><code>#FORCE WWW\nRewriteEngine On\nRewriteCond %{HTTP_HOST} !=\"\"\nRewriteCond %{HTTP_HOST} ^www\\. [NC]\nRewriteCond %{HTTPS}s ^on(s)|\nRewriteRule ^ http%1://my.domain.com%{REQUEST_URI} [R=301,L]\n</code></pre>\n\n<p>Should work for http and https.</p>\n" }, { "answer_id": 316908, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Forcing www to non-www is simple at the primary domain level.</p>\n</blockquote>\n\n<p>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 <code>www.</code> then remove it.</p>\n\n<p>(Forcing non-www to www for subdomains <em>and</em> main domains is a little more tricky if you want a generic single directive solution.)</p>\n\n<p>The following removes the <code>www</code> subdomain from <em>any</em> hostname.</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP_HOST} ^www\\.(.+) [NC]\nRewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]\n</code></pre>\n\n<p>In addition... If your subdomains are pointing to subdirectories off the main domain (eg. <code>example.com/subdomain</code>) 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 <em>leaked</em> in some way.)</p>\n" }, { "answer_id": 360520, "author": "Asha", "author_id": 92824, "author_profile": "https://wordpress.stackexchange.com/users/92824", "pm_score": 0, "selected": false, "text": "<pre><code># Remove www from any URLs that have them:\nRewriteEngine on\nRewriteCond %{HTTP_HOST} ^www\\.\nRewriteRule ^(.*)$ https://example.com/$1 [R=301,L]\n</code></pre>\n" } ]
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 if that's the case you'll want to review your htaccess to remove the www.my.domain.com redirect. </p>\n\n<p>If that's not the case, ie. you're trying to redirect links that have the wrong subdomain, you'll need to have a catch all subdomain, AKA wildcard subdomain. If you don't have a wildcard subdomain you might as well be redirecting to <em>thisdoesntexist.my.domain.com</em> </p>\n\n<p>If you want to redirect links that go to the wrong domain AND you have a wildcard subdomain, put this in your .htaccess file:</p>\n\n<pre><code>#FORCE WWW\nRewriteEngine On\nRewriteCond %{HTTP_HOST} !=\"\"\nRewriteCond %{HTTP_HOST} ^www\\. [NC]\nRewriteCond %{HTTPS}s ^on(s)|\nRewriteRule ^ http%1://my.domain.com%{REQUEST_URI} [R=301,L]\n</code></pre>\n\n<p>Should work for http and https.</p>\n" }, { "answer_id": 316908, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Forcing www to non-www is simple at the primary domain level.</p>\n</blockquote>\n\n<p>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 <code>www.</code> then remove it.</p>\n\n<p>(Forcing non-www to www for subdomains <em>and</em> main domains is a little more tricky if you want a generic single directive solution.)</p>\n\n<p>The following removes the <code>www</code> subdomain from <em>any</em> hostname.</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP_HOST} ^www\\.(.+) [NC]\nRewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]\n</code></pre>\n\n<p>In addition... If your subdomains are pointing to subdirectories off the main domain (eg. <code>example.com/subdomain</code>) 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 <em>leaked</em> in some way.)</p>\n" }, { "answer_id": 360520, "author": "Asha", "author_id": 92824, "author_profile": "https://wordpress.stackexchange.com/users/92824", "pm_score": 0, "selected": false, "text": "<pre><code># Remove www from any URLs that have them:\nRewriteEngine on\nRewriteCond %{HTTP_HOST} ^www\\.\nRewriteRule ^(.*)$ https://example.com/$1 [R=301,L]\n</code></pre>\n" } ]
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_thumbnail_id( $post_id );\n// featured image url\n$thumbnail_url = wp_get_attachment_url( $thumbnail_id );\n</code></pre>\n\n<p>Then in the HTML, you can use</p>\n\n<pre><code>&lt;div class=\"image \"&gt;\n &lt;img class=\"lazy\" src=\"&lt;?php echo esc_attr( $thumbnail_url ); ?&gt;\" data-src=\"\" alt=\"\" /&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 316935, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 0, "selected": false, "text": "<p>Off top of my head here's two possible solution concepts.</p>\n\n<p>1) Just run the custom loop (I meant to type, query) again and this time use it with only <code>the_post_thumbnail</code>.</p>\n\n<pre><code>&lt;?php if ($myposts-&gt;have_posts() ) : ?&gt;\n&lt;div class=\"image-wrapper e-in\"&gt;\n&lt;?php while ($myposts -&gt;have_posts() ) : $myposts -&gt;the_post(); ?&gt;\n &lt;div class=\"image \"&gt;\n &lt;!--Post Iamge Will Show Herre According To The Posts--&gt;\n &lt;img class=\"lazy\" data-src=\"&lt;?php the_post_thumbnail_url(); ?&gt;\" alt=\"\" /&gt;\n &lt;/div&gt;\n&lt;?php endwhile; wp_reset_postdata(); ?&gt;\n&lt;/div&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n\n<p>2) Push <code>get_the_post_thumbnail</code>'s to a helper array while doing the custom loop. After the custom loop is done, do a <code>foreach</code> for the helper array to echo thumbnail html outside the loop.</p>\n\n<p>First</p>\n\n<pre><code>$myposts = new WP_Query( $args );\nimages_html_array = array();\n</code></pre>\n\n<p>Then inside the loop</p>\n\n<pre><code>images_html_array[] = get_the_post_thumbnail_url();\n</code></pre>\n\n<p>Then</p>\n\n<pre><code>&lt;div class=\"image-wrapper e-in\"&gt;\n &lt;?php foreach( $images_html_array as $img_url ) : ?&gt;\n &lt;div class=\"image \"&gt;\n &lt;!--Post Iamge Will Show Herre According To The Posts--&gt;\n &lt;img class=\"lazy\" data-src=\"&lt;?php echo esc_url( $img_url ); ?&gt;\" alt=\"\" /&gt;\n &lt;/div&gt;\n &lt;?php endforeach; ?&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>Maybe?</p>\n\n<p>These are just rough code examples and I didn't test these yet.</p>\n" } ]
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 wpse316932_redirect_wrong_email() {\n global $errors;\n\n if ( $error = $errors-&gt;get_error_code() ) {\n wp_safe_redirect( 'lost-password/?error=' . $error );\n } else {\n wp_safe_redirect( 'lost-password/' );\n } \n}\n</code></pre>\n\n<p>This is utilizing the <a href=\"https://developer.wordpress.org/reference/hooks/lost_password/\" rel=\"nofollow noreferrer\"><code>lost_password</code> action hook</a> that fires right before the lost password form.</p>\n\n<p>You were experiencing this because WP will only redirect you to the url you specified in <code>redirect_to</code> 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 <code>wp-login.php</code> page. By using this action you can hook into this procedure right before that.</p>\n" }, { "answer_id": 316937, "author": "GigiSan", "author_id": 107437, "author_profile": "https://wordpress.stackexchange.com/users/107437", "pm_score": 0, "selected": false, "text": "<p>I temporarily found a workaround of some sort, but it's not really accurate so <strong>I'm still open to ideas</strong>. :)</p>\n\n<p>I removed the filter</p>\n\n<pre><code>function custom_lost_password_page( $lostpassword_url, $redirect ) {\n return home_url( '/lost-password/' );\n}\nadd_filter( 'lostpassword_url', 'custom_lost_password_page', 10, 2 );\n</code></pre>\n\n<p>and added an action on <code>lost_password</code> instead</p>\n\n<pre><code>function custom_lost_password_page() {\n // If the referrer is lost-password then it's a failed attempt,\n // show the form again with an error\n if (strstr($_SERVER['HTTP_REFERER'], 'lost-password')) {\n wp_redirect(home_url('/lost-password?error=invalidemail')); \n }\n else {\n wp_redirect(home_url('/lost-password/'));\n }\n}\nadd_action( 'lost_password', 'custom_lost_password_page', 10, 0 ); \n</code></pre>\n\n<p>As you can see, it intercepts all calls from itself, masking any possible error as an <code>invalidemail</code> error. It suits the purpose, but it's not very clean.</p>\n" } ]
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_theme_root()</code> returns <code>/opt/bitnami/apps/wordpress/htdocs/wp-content/themes</code>\n<code>get_theme_roots()</code> returns <code>/themes</code></p>\n\n<p>By switching that to <code>get_theme_root()</code> (note singular), it was able to correctly locate the custom <code>.php</code> file.</p>\n" }, { "answer_id": 316959, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 0, "selected": false, "text": "<p>I think you could use <a href=\"https://codex.wordpress.org/Function_Reference/get_stylesheet_directory\" rel=\"nofollow noreferrer\">get_stylesheet_directory()</a> as you're using a child theme. </p>\n\n<p>Something like, \n<code>include_once( get_stylesheet_directory() . '/rs-custom-functions.php');</code></p>\n" }, { "answer_id": 316973, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p><code>get_theme_roots()</code> and <code>get_theme_root()</code> aren't really appropriate functions for getting the path to a file from a theme.</p>\n\n<p>I recommend you use <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_path/\" rel=\"nofollow noreferrer\"><code>get_theme_file_path()</code></a> instead:</p>\n\n<pre><code>include_once get_theme_file_path( 'grow-minimal-child/rs-custom-functions.php' );\n</code></pre>\n" } ]
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_theme_root()</code> returns <code>/opt/bitnami/apps/wordpress/htdocs/wp-content/themes</code>\n<code>get_theme_roots()</code> returns <code>/themes</code></p>\n\n<p>By switching that to <code>get_theme_root()</code> (note singular), it was able to correctly locate the custom <code>.php</code> file.</p>\n" }, { "answer_id": 316959, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 0, "selected": false, "text": "<p>I think you could use <a href=\"https://codex.wordpress.org/Function_Reference/get_stylesheet_directory\" rel=\"nofollow noreferrer\">get_stylesheet_directory()</a> as you're using a child theme. </p>\n\n<p>Something like, \n<code>include_once( get_stylesheet_directory() . '/rs-custom-functions.php');</code></p>\n" }, { "answer_id": 316973, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p><code>get_theme_roots()</code> and <code>get_theme_root()</code> aren't really appropriate functions for getting the path to a file from a theme.</p>\n\n<p>I recommend you use <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_path/\" rel=\"nofollow noreferrer\"><code>get_theme_file_path()</code></a> instead:</p>\n\n<pre><code>include_once get_theme_file_path( 'grow-minimal-child/rs-custom-functions.php' );\n</code></pre>\n" } ]
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>getBlockHierarchyRootClientId</code> will return the parent block id if the current block is inside innerBlocks and will return the same id if it's root</p>\n\n<p>you can call it like this</p>\n\n<pre><code>wp.data.select( 'core/editor' ).getBlockHierarchyRootClientId( clientId );\n\n</code></pre>\n\n<p>additionally, you can define a helper function that you can use in your code</p>\n\n<pre><code>const blockHasParent = ( clientId ) =&gt; clientId !== wp.data.select( 'core/editor' ).getBlockHierarchyRootClientId( clientId );\n\nif ( blockHasParent( yourClientId ) { \n ....\n}\n\n</code></pre>\n" }, { "answer_id": 367947, "author": "Abubakar Wazih Tushar", "author_id": 131830, "author_profile": "https://wordpress.stackexchange.com/users/131830", "pm_score": 3, "selected": false, "text": "<p><code>getBlockParents</code> will work accurately. You can use <code>getBlockParents</code> with the <code>clientId</code> of the block, <code>getBlockParents</code> will return the all parent blocks id if the current block is under any Blocks. It will return blank if current block is not under any Block</p>\n\n<p>here is a method that you can use:</p>\n\n<pre><code>const innerBlock = \"namespace/block-name\";\nconst parentBlocks = wp.data.select( 'core/block-editor' ).getBlockParents(props.clientId); \nconst parentAttributes = wp.data.select('core/block-editor').getBlocksByClientId(parentBlocks);\n\nvar is_under_inner = false;\nfor (i = 0; i &lt; parentAttributes.length; i++) {\n if ( parentAttributes[i].name == innerBlock ) {\n is_under_inner = true;\n }\n}\n\n//console.log(is_under_inner);\n</code></pre>\n" } ]
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=\"nofollow noreferrer\">Post &amp; Page Parameters</a> or <a href=\"https://codex.wordpress.org/Function_Reference/get_page_children\" rel=\"nofollow noreferrer\">get_page_children()</a>.</p>\n\n<pre><code>&lt;?php\nglobal $post;\n$args = array(\n 'post_type' =&gt; 'page',\n 'posts_per_page' =&gt; -1,\n 'post_parent' =&gt; $post-&gt;ID,\n 'order' =&gt; 'ASC',\n 'orderby' =&gt; 'menu_order'\n );\n\n\n$parent = new WP_Query( $args );\n\nif ( $parent-&gt;have_posts() ) : ?&gt;\n\n &lt;?php while ( $parent-&gt;have_posts() ) : $parent-&gt;the_post(); ?&gt;\n\n &lt;div id=\"parent-&lt;?php the_ID(); ?&gt;\" class=\"parent-page\"&gt;\n\n &lt;h1&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\" title=\"&lt;?php the_title(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt;\n\n &lt;/div&gt;\n\n &lt;?php endwhile; ?&gt;\n\n&lt;?php endif; wp_reset_postdata(); ?&gt;\n</code></pre>\n" }, { "answer_id": 317026, "author": "honk31", "author_id": 10994, "author_profile": "https://wordpress.stackexchange.com/users/10994", "pm_score": 0, "selected": false, "text": "<p>i would go for <a href=\"https://codex.wordpress.org/Function_Reference/get_ancestors\" rel=\"nofollow noreferrer\">get_ancestors</a>. it will return an array of ID's that you can use for whatever you want..</p>\n\n<pre><code>$anchestors = get_ancestors( get_the_ID(), 'page' );\nif (!empty($anchestors)) :\n foreach ($anchestors as $anchestor) :\n echo get_the_title( $anchestor );\n endforeach;\nendif;\n</code></pre>\n" } ]
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=\"nofollow noreferrer\">Post &amp; Page Parameters</a> or <a href=\"https://codex.wordpress.org/Function_Reference/get_page_children\" rel=\"nofollow noreferrer\">get_page_children()</a>.</p>\n\n<pre><code>&lt;?php\nglobal $post;\n$args = array(\n 'post_type' =&gt; 'page',\n 'posts_per_page' =&gt; -1,\n 'post_parent' =&gt; $post-&gt;ID,\n 'order' =&gt; 'ASC',\n 'orderby' =&gt; 'menu_order'\n );\n\n\n$parent = new WP_Query( $args );\n\nif ( $parent-&gt;have_posts() ) : ?&gt;\n\n &lt;?php while ( $parent-&gt;have_posts() ) : $parent-&gt;the_post(); ?&gt;\n\n &lt;div id=\"parent-&lt;?php the_ID(); ?&gt;\" class=\"parent-page\"&gt;\n\n &lt;h1&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\" title=\"&lt;?php the_title(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt;\n\n &lt;/div&gt;\n\n &lt;?php endwhile; ?&gt;\n\n&lt;?php endif; wp_reset_postdata(); ?&gt;\n</code></pre>\n" }, { "answer_id": 317026, "author": "honk31", "author_id": 10994, "author_profile": "https://wordpress.stackexchange.com/users/10994", "pm_score": 0, "selected": false, "text": "<p>i would go for <a href=\"https://codex.wordpress.org/Function_Reference/get_ancestors\" rel=\"nofollow noreferrer\">get_ancestors</a>. it will return an array of ID's that you can use for whatever you want..</p>\n\n<pre><code>$anchestors = get_ancestors( get_the_ID(), 'page' );\nif (!empty($anchestors)) :\n foreach ($anchestors as $anchestor) :\n echo get_the_title( $anchestor );\n endforeach;\nendif;\n</code></pre>\n" } ]
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-false/\" rel=\"nofollow noreferrer\">link</a></p>\n\n<p>Then basically in your template wrap the title element in conditional, like this:</p>\n\n<pre><code>if( get_field( 'title_show_or_whatever' ) ) {\n // The title element\n}\n</code></pre>\n" }, { "answer_id": 317025, "author": "David Walz", "author_id": 133943, "author_profile": "https://wordpress.stackexchange.com/users/133943", "pm_score": -1, "selected": false, "text": "<p>You might want to try php <a href=\"http://php.net/manual/en/control-structures.alternative-syntax.php\" rel=\"nofollow noreferrer\">alternative syntax</a> for your if statement.</p>\n\n<pre><code>&lt;?php if (get_field('nav')): ?&gt;\n &lt;a href=\"&lt;?php the_permalink()?&gt;\" class=\"active\"&gt;\n &lt;?php the_title();?&gt; \n &lt;/a&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n" } ]
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 documentation: <a href=\"https://developer.wordpress.org/reference/hooks/style_loader_tag/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/hooks/style_loader_tag/</a></p>\n\n<blockquote>\n <p><code>apply_filters( 'style_loader_tag', $html, $handle, $href, $media )</code><br>Filters the HTML link tag of an enqueued\n style.</p>\n</blockquote>\n\n<p><br>\nFirst enqueue your stylesheet, see documentation: <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/wp_enqueue_style/</a></p>\n\n<pre><code>wp_enqueue_style( 'font-awesome-5', 'https://use.fontawesome.com/releases/v5.5.0/css/all.css', array(), null );\n</code></pre>\n\n<p>The <code>$handle</code> is <code>'font-awesome-5'</code><br>\nI do <code>null</code> so that there is no version number. This way it will be cached.\n<br><br>\n<strong>Simple str_replace</strong><br>\nA simple str_replace is enough to achieve what you want, see example below </p>\n\n<pre><code>function add_font_awesome_5_cdn_attributes( $html, $handle ) {\n if ( 'font-awesome-5' === $handle ) {\n return str_replace( \"media='all'\", \"media='all' integrity='sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU' crossorigin='anonymous'\", $html );\n }\n return $html;\n}\nadd_filter( 'style_loader_tag', 'add_font_awesome_5_cdn_attributes', 10, 2 );\n</code></pre>\n\n<p><br>\n<strong>Add different atributes</strong><br>\nBelow an example to add different atributes to (multiple) different stylesheets</p>\n\n<pre><code>function add_style_attributes( $html, $handle ) {\n\n if ( 'font-awesome-5' === $handle ) {\n return str_replace( \"media='all'\", \"media='all' integrity='sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU' crossorigin='anonymous'\", $html );\n }\n\n if ( 'another-style' === $handle ) {\n return str_replace( \"media='all'\", \"media='all' integrity='blajbsf' example\", $html );\n }\n\n if ( 'bootstrap-css' === $handle ) {\n return str_replace( \"media='all'\", \"media='all' integrity='something-different' crossorigin='anonymous'\", $html );\n }\n\n return $html;\n}\nadd_filter( 'style_loader_tag', 'add_style_attributes', 10, 2 );\n</code></pre>\n\n<p><br>\n<strong>Add attributes to all styles</strong><br>\nBelow an example to add the same atributes to more than one stylesheet</p>\n\n<pre><code>function add_attributes_to_all_styles( $html, $handle ) {\n\n // add style handles to the array below\n $styles = array(\n 'font-awesome-5',\n 'another-style',\n 'bootstrap-css'\n );\n\n foreach ( $styles as $style ) {\n if ( $style === $handle ) {\n return str_replace( \"media='all'\", \"media='all' integrity='sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU' crossorigin='anonymous'\", $html );\n }\n }\n\n return $html;\n}\nadd_filter( 'style_loader_tag', 'add_attributes_to_all_styles', 10, 2 );\n</code></pre>\n\n<p><br>\n<br><br>\n<strong>script_loader_tag</strong><br>\nI also would like to explain the script_loader_tag, because this is also handy, but this API works in combination with <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"noreferrer\">wp_enqueue_script</a>.<br><br>\nThe script_loader_tag API is almost the same, only some small differences, see documentation: <a href=\"https://developer.wordpress.org/reference/hooks/script_loader_tag/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/hooks/script_loader_tag/</a></p>\n\n<blockquote>\n <p><code>apply_filters( 'script_loader_tag', $tag, $handle, $src )</code><br> Filters the\n HTML script tag of an enqueued script.</p>\n</blockquote>\n\n<p><br>\nBelow an example to defer a single script</p>\n\n<pre><code>function add_defer_jquery( $tag, $handle ) {\n if ( 'jquery' === $handle ) {\n return str_replace( \"src\", \"defer src\", $tag );\n }\n return $tag;\n}\nadd_filter( 'script_loader_tag', 'add_defer_jquery', 10, 2 );\n</code></pre>\n\n<p><br>\nBelow an example to defer more than one script</p>\n\n<pre><code>function add_defer_attribute( $tag, $handle ) {\n\n // add script handles to the array below\n $scripts_to_defer = array(\n 'jquery',\n 'jquery-migrate',\n 'bootstrap-bundle-js'\n );\n\n foreach ( $scripts_to_defer as $defer_script ) {\n if ( $defer_script === $handle ) {\n return str_replace( \"src\", \"defer src\", $tag );\n }\n }\n\n return $tag;\n}\nadd_filter( 'script_loader_tag', 'add_defer_attribute', 10, 2 );\n</code></pre>\n\n<p>So I have explained both API's <code>style_loader_tag</code> and <code>script_loader_tag</code>. 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.\n<br><br><br></p>\n\n<p><strong>UPDATE</strong><br>\n@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 <a href=\"https://wordpress.org\" rel=\"noreferrer\">https://wordpress.org</a> you're essentially forced to abide by the \"<a href=\"https://make.wordpress.org/core/handbook/best-practices/coding-standards/\" rel=\"noreferrer\">WordPress Coding Standards</a>\" or they will simply reject your theme and/or plugin.\n<br><br>\nThat'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.\n<br><br>\nAnd 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.\n<br><br>\nAs 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.</p>\n\n<p><strong>EDIT</strong><br>\n@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:</p>\n\n<blockquote>\n <p><strong>Question:</strong> Why are some of the CSS and JS files not being merged?<br>\n <strong>Answer:</strong> The plugin only processes JS and CSS files enqueued using the\n official WordPress API method –\n <a href=\"https://developer.wordpress.org/themes/basics/including-css-javascript/\" rel=\"noreferrer\">https://developer.wordpress.org/themes/basics/including-css-javascript/</a>\n -as well as files from the same domain (unless specified on the settings).</p>\n</blockquote>\n\n<p>See FAQ: <a href=\"https://wordpress.org/plugins/fast-velocity-minify/\" rel=\"noreferrer\">https://wordpress.org/plugins/fast-velocity-minify/</a></p>\n" }, { "answer_id": 319924, "author": "CK MacLeod", "author_id": 35923, "author_profile": "https://wordpress.stackexchange.com/users/35923", "pm_score": 0, "selected": false, "text": "<p>The review of script_ and style_loader_tag by @Remzi Cavdar is interesting, but, at the risk of provoking some outrage, and in the hope that someone can remind me what the advantage of using the WP queue would be in cases like this one, I'll recommend taking the easy way out, and loading Fontawesome's stylesheet via hook.</p>\n\n<pre><code>/* ADD FONTAWESOME 5.5.0 via action hook */\nadd_action( 'wp_head', 'sewpd_add_fontawesome' );\n\nfunction sewpd_add_fontawesome() {\n\necho '\n&lt;!--FONTAWESOME 5.5.0 added via functions.php --&gt;\n&lt;link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.5.0/css/all.css\" integrity=\"sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU\" crossorigin=\"anonymous\"&gt;\n&lt;!--END FONTAWESOME --&gt;\n'; \n\n}\n</code></pre>\n\n<p>Some might even argue that, if you're using FA only for, say, some icons in the theme footer or within posts, you should add it lower, within the body of the page, since that way it won't come up as render-blocking, but I confess I've never done that... And I won't go as far as to recommend adding it directly to a header.php or other template file. That would be wrong. ;)</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Remzi Cavdar was kind enough to reply to my request for a reminder as to why simply adding a Fontawesome or similar tag via wp_head() hook might be less desirable than utilizing the WordPress queue. He refers generally to the notion of best practices and somewhat more specifically to the idea that caching plugins might need to be able to access the stylesheet via the queue. </p>\n\n<p>Before I go into detail, I'll say that, though I don't actually know of any significant particular justification other than that it's kind of \"the WordPress Way,\" I like Comrade Cavdar's approach, and may use it myself in the future. </p>\n\n<p>His other claims for it, however, are not persuasive to me. Maybe he or someone else can add to them. If so, I'm all ears. Bottom-line, as far as I can tell, after running over 20 tests on Pingdom and GTMetrix comparing \"add via queue\" vs \"add via head\" on a test blog, there is no significant and consistent difference in terms of graded performance, total number of page requests, or load times (e.g., \"First Paint,\" \"First Contentful Paint,\" and \"OnLoad\" at GTMetrix) between the two approaches. </p>\n\n<p>Regarding caching specifically, caching plugins can't do very much with externally hosted files, whether or not they're added to the WP queue. The files themselves will remain unaffected, and your page will still generate a request for each one. </p>\n\n<p>More generally, I've seen a wide range of different approaches for loading scripts and styles. Some of them will partly or entirely bypass the WP queue. It's certainly conceivable that there will be instances - a function that utilizes an array of style handles while preventing them from being loaded on particular pages, say - where having the Fontawesome or other 3rd Party Tag enqueued will be marginally useful, and that initial deploying two functions - enqueueing and filtering - will actually turn out to be more parsimonious than simply loading one. </p>\n\n<p>In the case of FA, the stylesheet is <em>already minified</em> and is loaded via FA's own CDN. Its intrinsic impact on performance will be minimal, though, whether loaded via wp_head() or via the queue, it will still register demerits in multiple spots on performance graders - the same ones, like Google Page Speed Insights and the aforementioned GTMetrix and Pingdom, that will dock you a performance point for not saving a few bytes (not even kilobytes) re-optimizing one or another image file. </p>\n\n<p>Loading via wp_head rather than the queue may trip a \"correct order of scripts and styles\" check (even though someone else will grade you higher for loading the externally hosted file after locally hosted ones), but, if you're really concerned about loading FA in the best possible way for your site, then you'd try <a href=\"https://fontawesome.com/how-to-use/on-the-web/setup/hosting-font-awesome-yourself\" rel=\"nofollow noreferrer\">locally hosting its files and sub-files</a>, both its style and the fonts that its stylesheet calls via @font-face. In that case you could enqueue the stylesheet just like any other local file, concatenate and combine it via an optimizing plugin or directly \"by hand.\" You could even make your own awesome modifications of Fontawesome and integrate them with your theme stylesheet and structure. Or (as earlier briefly mentioned) you could try out some more exotic performance optimization tactics like adding the CSS inline right before it was needed in the structure of a specific page. </p>\n\n<p>Anyway, you wouldn't need to worry about the new \"integrity\" and \"cross-origin\" tags, and you also wouldn't have to worry if someday Fontawesome forgets to pay its CDN bill. </p>\n\n<p>Or you may be working on a site that's already a complete mess under the hood, with stylesheets and scripts loaded in every which way, and it might be easier just to have your latest addition at the top of the functions.php file so you or the next developer can locate it again easily...</p>\n" } ]
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 theme.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n" }, { "answer_id": 317059, "author": "djboris", "author_id": 152412, "author_profile": "https://wordpress.stackexchange.com/users/152412", "pm_score": 0, "selected": false, "text": "<p>With <code>wp_head</code> hook you are inserting content into the <code>&lt;head&gt;</code> of the HTML page, which is not what you want. Also, with <code>the_content</code>, you are basically inserting stuff into the post content.</p>\n\n<p>You can hook to the <a href=\"https://developer.wordpress.org/reference/hooks/loop_start/\" rel=\"nofollow noreferrer\"><code>loop_start</code></a> action, I believe that will give you the results you need.</p>\n\n<p>Note that this will add your content before any loop you have on your website. You might want to access the <code>WP_Query</code> object you have in parameters, and do additional checks.</p>\n" } ]
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 theme.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n" }, { "answer_id": 317059, "author": "djboris", "author_id": 152412, "author_profile": "https://wordpress.stackexchange.com/users/152412", "pm_score": 0, "selected": false, "text": "<p>With <code>wp_head</code> hook you are inserting content into the <code>&lt;head&gt;</code> of the HTML page, which is not what you want. Also, with <code>the_content</code>, you are basically inserting stuff into the post content.</p>\n\n<p>You can hook to the <a href=\"https://developer.wordpress.org/reference/hooks/loop_start/\" rel=\"nofollow noreferrer\"><code>loop_start</code></a> action, I believe that will give you the results you need.</p>\n\n<p>Note that this will add your content before any loop you have on your website. You might want to access the <code>WP_Query</code> object you have in parameters, and do additional checks.</p>\n" } ]
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 previewing live on the web in a browser\nto see if the short-code actually is working. </li>\n<li>Make sure you have spelled the short-code correctly, and have the correct syntax. (See theme's documentation.)</li>\n<li>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.</li>\n<li>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.</li>\n</ol>\n" }, { "answer_id": 317128, "author": "Martin Jarvis", "author_id": 147693, "author_profile": "https://wordpress.stackexchange.com/users/147693", "pm_score": 0, "selected": false, "text": "<p>Usually, a dropcap is reserved for a single character at the start of a sentence. I suspect that by putting a complete sentence into the dropcap shortcode 'output' area, you are confusing the code, and it may be the apostrophe (quote) within your sentence that is breaking it. Please try it again with a single letter ('I') and then enter the rest of your sentence after the dropcap shortcode in the text edit area. If this doesn't work, try adding a dropcap plugin (just search for 'wordpress dropcap plugin' and install one of those).</p>\n" } ]
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 previewing live on the web in a browser\nto see if the short-code actually is working. </li>\n<li>Make sure you have spelled the short-code correctly, and have the correct syntax. (See theme's documentation.)</li>\n<li>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.</li>\n<li>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.</li>\n</ol>\n" }, { "answer_id": 317128, "author": "Martin Jarvis", "author_id": 147693, "author_profile": "https://wordpress.stackexchange.com/users/147693", "pm_score": 0, "selected": false, "text": "<p>Usually, a dropcap is reserved for a single character at the start of a sentence. I suspect that by putting a complete sentence into the dropcap shortcode 'output' area, you are confusing the code, and it may be the apostrophe (quote) within your sentence that is breaking it. Please try it again with a single letter ('I') and then enter the rest of your sentence after the dropcap shortcode in the text edit area. If this doesn't work, try adding a dropcap plugin (just search for 'wordpress dropcap plugin' and install one of those).</p>\n" } ]
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 previewing live on the web in a browser\nto see if the short-code actually is working. </li>\n<li>Make sure you have spelled the short-code correctly, and have the correct syntax. (See theme's documentation.)</li>\n<li>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.</li>\n<li>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.</li>\n</ol>\n" }, { "answer_id": 317128, "author": "Martin Jarvis", "author_id": 147693, "author_profile": "https://wordpress.stackexchange.com/users/147693", "pm_score": 0, "selected": false, "text": "<p>Usually, a dropcap is reserved for a single character at the start of a sentence. I suspect that by putting a complete sentence into the dropcap shortcode 'output' area, you are confusing the code, and it may be the apostrophe (quote) within your sentence that is breaking it. Please try it again with a single letter ('I') and then enter the rest of your sentence after the dropcap shortcode in the text edit area. If this doesn't work, try adding a dropcap plugin (just search for 'wordpress dropcap plugin' and install one of those).</p>\n" } ]
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 your own blocks you can do something like this:</p>\n\n<p><code>&lt;BlockControls key=\"controls\"&gt;\n &lt;BlockAlignmentToolbar\n value={ align }\n onChange={ ( align ) =&gt; setAttributes( { align } ) }\n controls={ [ 'wide', 'full' ] }\n /&gt;\n&lt;/BlockControls&gt;\n</code></p>\n\n<p>Make sure you include the components:</p>\n\n<p><code>const { BlockControls, BlockAlignmentToolbar } = wp.editor;</code></p>\n\n<p>If you are looking to limit the Alignment of existing blocks, then I'm not sure if that is possible at the moment.</p>\n" }, { "answer_id": 326667, "author": "Jörn Lund", "author_id": 35723, "author_profile": "https://wordpress.stackexchange.com/users/35723", "pm_score": 3, "selected": false, "text": "<p>According to <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#blocks-registerblocktype\" rel=\"noreferrer\">the gutenberg handbook</a> you can use the <code>blocks.registerBlockType</code> filter which allows you to play around with the block settings.</p>\n\n<p>For most of the wp core blocks modifying the <code>supports.align</code> property works pretty well:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>wp.hooks.addFilter(\n 'blocks.registerBlockType',\n 'my-theme/namespace',\n function( settings, name ) {\n if ( name === 'core/pullquote' ) {\n return lodash.assign( {}, settings, {\n supports: lodash.assign( {}, settings.supports, {\n // disable the align-UI completely ...\n align: false, \n // ... or only allow specific alignments\n // align: ['center,'full'], \n } ),\n } );\n }\n return settings;\n }\n);\n</code></pre>\n\n<p>In my tests this worked for most of wp core blocks, except for <code>core/image</code>, <code>core/paragraph</code>, <code>core/heading</code> and <code>core/quote</code>. </p>\n\n<h2>Troublesome Image Block</h2>\n\n<p>As for WP 5.0.3 (and at least up to 5.3) these blocks will receive an additional alignment control like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/4izQp.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4izQp.png\" alt=\"Additional Alignments\"></a></p>\n\n<p>with code:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code> ...\n {\n align: ['left','full'], \n }\n ...\n</code></pre>\n\n<p>To control the available alignments for the <code>core/image</code> block, you would have to modify the edit method of a block using the <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#editor-blockedit\" rel=\"noreferrer\"><code>editor.BlockEdit</code></a> filter. </p>\n\n<h2>Nasty Headings, Paragraphs &amp; Quotes</h2>\n\n<p>The problem with <code>core/paragraph</code>, <code>core/heading</code> and <code>core/quote</code> is, that block-align (defined by classenames <code>alignleft</code>, <code>alignwide</code>, ... in the frontend and the <code>data-align</code> attribute in the editor) is not clearly separated from the text-align (defined in the style attribute), which leads to odd results like this: \n<a href=\"https://i.stack.imgur.com/jMhXe.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/jMhXe.png\" alt=\"Odd core/paragraph\"></a></p>\n\n<p><strong>[UPDATE 2019-11-13]:</strong> As of WP 5.3 this works pretty well with <code>core/cover</code> now. </p>\n" } ]
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 your own blocks you can do something like this:</p>\n\n<p><code>&lt;BlockControls key=\"controls\"&gt;\n &lt;BlockAlignmentToolbar\n value={ align }\n onChange={ ( align ) =&gt; setAttributes( { align } ) }\n controls={ [ 'wide', 'full' ] }\n /&gt;\n&lt;/BlockControls&gt;\n</code></p>\n\n<p>Make sure you include the components:</p>\n\n<p><code>const { BlockControls, BlockAlignmentToolbar } = wp.editor;</code></p>\n\n<p>If you are looking to limit the Alignment of existing blocks, then I'm not sure if that is possible at the moment.</p>\n" }, { "answer_id": 326667, "author": "Jörn Lund", "author_id": 35723, "author_profile": "https://wordpress.stackexchange.com/users/35723", "pm_score": 3, "selected": false, "text": "<p>According to <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#blocks-registerblocktype\" rel=\"noreferrer\">the gutenberg handbook</a> you can use the <code>blocks.registerBlockType</code> filter which allows you to play around with the block settings.</p>\n\n<p>For most of the wp core blocks modifying the <code>supports.align</code> property works pretty well:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>wp.hooks.addFilter(\n 'blocks.registerBlockType',\n 'my-theme/namespace',\n function( settings, name ) {\n if ( name === 'core/pullquote' ) {\n return lodash.assign( {}, settings, {\n supports: lodash.assign( {}, settings.supports, {\n // disable the align-UI completely ...\n align: false, \n // ... or only allow specific alignments\n // align: ['center,'full'], \n } ),\n } );\n }\n return settings;\n }\n);\n</code></pre>\n\n<p>In my tests this worked for most of wp core blocks, except for <code>core/image</code>, <code>core/paragraph</code>, <code>core/heading</code> and <code>core/quote</code>. </p>\n\n<h2>Troublesome Image Block</h2>\n\n<p>As for WP 5.0.3 (and at least up to 5.3) these blocks will receive an additional alignment control like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/4izQp.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4izQp.png\" alt=\"Additional Alignments\"></a></p>\n\n<p>with code:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code> ...\n {\n align: ['left','full'], \n }\n ...\n</code></pre>\n\n<p>To control the available alignments for the <code>core/image</code> block, you would have to modify the edit method of a block using the <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#editor-blockedit\" rel=\"noreferrer\"><code>editor.BlockEdit</code></a> filter. </p>\n\n<h2>Nasty Headings, Paragraphs &amp; Quotes</h2>\n\n<p>The problem with <code>core/paragraph</code>, <code>core/heading</code> and <code>core/quote</code> is, that block-align (defined by classenames <code>alignleft</code>, <code>alignwide</code>, ... in the frontend and the <code>data-align</code> attribute in the editor) is not clearly separated from the text-align (defined in the style attribute), which leads to odd results like this: \n<a href=\"https://i.stack.imgur.com/jMhXe.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/jMhXe.png\" alt=\"Odd core/paragraph\"></a></p>\n\n<p><strong>[UPDATE 2019-11-13]:</strong> As of WP 5.3 this works pretty well with <code>core/cover</code> now. </p>\n" } ]
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 properties and methods without visibility will be implied to be \"public\", but it's best practice to be explicit when defining members.</p>\n\n<ol start=\"2\">\n<li>above code does not works for me, is not correct or any mistake from my side?</li>\n</ol>\n\n<p>Your code looks fine. I did notice that your class uses the <code>admin_init</code> hook, but your closure example uses <code>init</code>. Bear in mind that <code>admin_init</code> <em>only fires in the WordPress admin</em>, and not on the front-end. It could be possible that your code isn't hooking in at the right time, but that's unlikely.</p>\n\n<p>Try this: </p>\n\n<pre><code>class MyClass {\n public function __construct() {\n }\n\n public function hooks() {\n add_action( 'admin_init', array( $this, 'doAdminTest' ) );\n add_action( 'init', array( $this, 'doGeneralTest' ) );\n }\n\n public function doAdminTest() {\n die( 'We are in the admin area.' );\n }\n\n public function doGeneralTest() {\n die( 'We are in the init hook.' );\n }\n}\n\n$var = new MyClass();\n\nadd_action( 'plugins_loaded', array( $var, 'hooks' ) );\n</code></pre>\n\n<p>Now, if you go to /wp-admin/ or your front-end, you should get the result of <code>doGeneralTest</code>. If you comment out the <code>add_action</code> line for <code>init</code>, you should see the result of <code>doAdminTest</code> at /wp-admin/</p>\n" }, { "answer_id": 317138, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<blockquote>\n <p>above code does not works for me, is not correct or any mistake from\n my side?</p>\n</blockquote>\n\n<p>And it didn't work for me either. Because it throws this fatal error:</p>\n\n<blockquote>\n <p>PHP Fatal error: No code may exist outside of namespace {} in ...</p>\n</blockquote>\n\n<p>And that's because the PHP <a href=\"http://php.net/manual/en/language.namespaces.definitionmultiple.php\" rel=\"nofollow noreferrer\">manual</a> says:</p>\n\n<blockquote>\n <p>No PHP code may exist outside of the namespace brackets except for an\n opening declare statement.</p>\n</blockquote>\n\n<p>So your code could be fixed in two ways:</p>\n\n<ol>\n<li><p>Use the <em>non-bracketed</em> syntax.</p>\n\n<pre><code>&lt;?php\nnamespace NS;\n\nclass MyClass {\n public function __construct() {\n add_action( 'init',array( $this, 'getStuffDone' ) );\n }\n public function getStuffDone() {\n // .. This is where stuff gets done ..\n }\n}\n\n$var = new MyClass();\n</code></pre></li>\n<li><p>Put global code (or the <code>$var = new MyClass();</code>) inside a namespace statement (<code>namespace {}</code>) with no namespace. <em>Note though</em>, that you need to use <code>NS\\MyClass</code> instead of just <code>MyClass</code>.</p>\n\n<pre><code>&lt;?php\n// No code here. (except `declare`)\n\nnamespace NS {\n\n class MyClass {\n public function __construct() {\n add_action( 'init',array( $this, 'getStuffDone' ) );\n }\n public function getStuffDone() {\n // .. This is where stuff gets done ..\n }\n }\n}\n// No code here. (except another `namespace {...}`)\n\nnamespace {\n $var = new NS\\MyClass();\n}\n// No code here. (except another `namespace {...}`)\n</code></pre></li>\n</ol>\n\n<h2>UPDATE</h2>\n\n<p>Ok, this is what I have in <code>wp-content/themes/my-theme/includes/MyClass.php</code>:</p>\n\n<pre><code>&lt;?php\nnamespace NS;\n\nclass MyClass {\n public function __construct() {\n add_action( 'init', array( $this, 'getStuffDone' ) );\n add_filter( 'the_content', array( $this, 'test' ) );\n }\n\n public function getStuffDone() {\n error_log( __METHOD__ . ' was called' );\n }\n\n public function test( $content ) {\n return __METHOD__ . ' in the_content.&lt;hr&gt;' . $content;\n }\n}\n\n$var = new MyClass();\n</code></pre>\n\n<p>And I'm including the file from <code>wp-content/themes/my-theme/functions.php</code>:</p>\n\n<pre><code>require_once get_template_directory() . '/includes/MyClass.php';\n</code></pre>\n\n<p>Try that out and see if it works for you, because it worked well for me:</p>\n\n<ul>\n<li><p>You'd see <code>NS\\MyClass::test in the_content.</code> in the post content (just visit any single post).</p></li>\n<li><p>You'd see <code>NS\\MyClass::getStuffDone was called</code> added in the <code>error_log</code> file or <code>wp-content/debug.log</code> if you enabled <a href=\"https://codex.wordpress.org/Debugging_in_WordPress#WP_DEBUG_LOG\" rel=\"nofollow noreferrer\"><code>WP_DEBUG_LOG</code></a>.</p></li>\n</ul>\n" } ]
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 noreferrer\"><code>has_shortcode</code></a> help you solve your problem?</p>\n\n<p>On the codex there's an example,</p>\n\n<blockquote>\n <p>Enqueue some script when some post uses some shortcode</p>\n</blockquote>\n\n<pre><code>function custom_shortcode_scripts() {\n global $post;\n if( is_a( $post, 'WP_Post' ) &amp;&amp; has_shortcode( $post-&gt;post_content, 'custom-shortcode') ) {\n wp_enqueue_script( 'custom-script');\n }\n}\nadd_action( 'wp_enqueue_scripts', 'custom_shortcode_scripts');\n</code></pre>\n" }, { "answer_id": 317186, "author": "Remzi Cavdar", "author_id": 149484, "author_profile": "https://wordpress.stackexchange.com/users/149484", "pm_score": 4, "selected": true, "text": "<p><code>wp_enqueue_script</code> is not going to work in a shortcode, this is because of the loading order.</p>\n\n<p>You could use <code>wp_register_script</code> and then you could <code>wp_enqueue_script</code> in you shortcode function like this example:</p>\n\n<pre><code>// Front-end\nfunction front_end_scripts() {\n wp_register_script( 'example-js', '//example.com/shared-web/js/example.js', array(), null, true );\n}\nadd_action( 'wp_enqueue_scripts', 'front_end_scripts' );\n</code></pre>\n\n<p>Then you use this in your shortcode:</p>\n\n<pre><code>function example_shortcode() {\n\n wp_enqueue_script( 'example-js' );\n return; // dont forget to return something\n\n}\nadd_shortcode( 'example-shortcode', 'example_shortcode' );\n</code></pre>\n\n<p>Furthermore, you could use <a href=\"https://codex.wordpress.org/Function_Reference/has_shortcode\" rel=\"nofollow noreferrer\"><code>has_shortcode</code></a> to check if a shortcode is loaded:</p>\n\n<pre><code>function custom_shortcode_scripts() {\nglobal $post;\nif( is_a( $post, 'WP_Post' ) &amp;&amp; has_shortcode( $post-&gt;post_content, 'custom-shortcode') ) {\n wp_enqueue_script( 'custom-script');\n}\n}\nadd_action( 'wp_enqueue_scripts', 'custom_shortcode_scripts');\n</code></pre>\n" }, { "answer_id": 348350, "author": "Christian Žagarskas", "author_id": 144474, "author_profile": "https://wordpress.stackexchange.com/users/144474", "pm_score": 1, "selected": false, "text": "<p>We can indeed conditionally load CSS and JS files via shortcode without using any <em>overly elaborate</em> functions:</p>\n\n<p>First, let's assume we registered all of our CSS/JS files previously (perhaps when <code>wp_enqueue_scripts</code> ran) </p>\n\n<pre><code>function prep_css_and_js() {\n wp_register_style('my-css', $_css_url);\n wp_register_script('my-js', $_js_url);\n}\nadd_action( 'wp_enqueue_scripts', 'prep_css_and_js', 5 );\n</code></pre>\n\n<p>Next, lets examine our shortcode function:</p>\n\n<pre><code>function my_shortcode_func( $atts, $content = null ) {\n if( ! wp_style_is( \"my-css\", $list = 'enqueued' ) ) { wp_enqueue_style('my-css'); }\n if( ! wp_script_is( \"my-js\", $list = 'enqueued' ) ) { wp_enqueue_script('my-js'); }\n ...\n}\n</code></pre>\n\n<p>Simple. Done.\n<strong>Ergo: we can \"conditionally load\" css/js files, (only when [shortcode] runs).</strong></p>\n\n<p>Let's consider the following ideology: </p>\n\n<ul>\n<li>We want to load certain CSS/JS files (but only when shortcode is triggered)</li>\n<li>Maybe we do not want those files to load on every page, or at all if the shortcode is not used on a page/post. (light weight)</li>\n<li>We can accomplish this by making sure WP registers ALL of the css/js files prior to calling the shortcode and prior to the enqueue.</li>\n<li><em>IE: Maybe during my <code>prep_css_and_js()</code> function I load ALL .css/.js files that are in certain folders...</em></li>\n</ul>\n\n<p>Now that WP see's them as registered scripts, we can indeed call them, conditionally, based on a verity of situations, including but not limited to <code>my_shortcode_func()</code></p>\n\n<p>Benefits: (no MySQL, no advanced functions and no filters needed)</p>\n\n<ul>\n<li>this is \"WP orthodix\", elegant, fast loading, easy and simple</li>\n<li>allows compilers/minifiers to detect such scripts</li>\n<li>uses the WP functions (wp_register_style/wp_register_script)</li>\n<li>compatible with more themes/plugins that might want to de-register those scripts for a verity of reasons.</li>\n<li>will not trigger multiple times</li>\n<li>very little processing or code is involved</li>\n</ul>\n\n<p>References:</p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/wp_script_is\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_script_is</a></li>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/wp_register_style\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_register_style</a></li>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/wp_register_script\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_register_script</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_scripts/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_enqueue_scripts/</a></li>\n</ul>\n" } ]
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 noreferrer\"><code>has_shortcode</code></a> help you solve your problem?</p>\n\n<p>On the codex there's an example,</p>\n\n<blockquote>\n <p>Enqueue some script when some post uses some shortcode</p>\n</blockquote>\n\n<pre><code>function custom_shortcode_scripts() {\n global $post;\n if( is_a( $post, 'WP_Post' ) &amp;&amp; has_shortcode( $post-&gt;post_content, 'custom-shortcode') ) {\n wp_enqueue_script( 'custom-script');\n }\n}\nadd_action( 'wp_enqueue_scripts', 'custom_shortcode_scripts');\n</code></pre>\n" }, { "answer_id": 317186, "author": "Remzi Cavdar", "author_id": 149484, "author_profile": "https://wordpress.stackexchange.com/users/149484", "pm_score": 4, "selected": true, "text": "<p><code>wp_enqueue_script</code> is not going to work in a shortcode, this is because of the loading order.</p>\n\n<p>You could use <code>wp_register_script</code> and then you could <code>wp_enqueue_script</code> in you shortcode function like this example:</p>\n\n<pre><code>// Front-end\nfunction front_end_scripts() {\n wp_register_script( 'example-js', '//example.com/shared-web/js/example.js', array(), null, true );\n}\nadd_action( 'wp_enqueue_scripts', 'front_end_scripts' );\n</code></pre>\n\n<p>Then you use this in your shortcode:</p>\n\n<pre><code>function example_shortcode() {\n\n wp_enqueue_script( 'example-js' );\n return; // dont forget to return something\n\n}\nadd_shortcode( 'example-shortcode', 'example_shortcode' );\n</code></pre>\n\n<p>Furthermore, you could use <a href=\"https://codex.wordpress.org/Function_Reference/has_shortcode\" rel=\"nofollow noreferrer\"><code>has_shortcode</code></a> to check if a shortcode is loaded:</p>\n\n<pre><code>function custom_shortcode_scripts() {\nglobal $post;\nif( is_a( $post, 'WP_Post' ) &amp;&amp; has_shortcode( $post-&gt;post_content, 'custom-shortcode') ) {\n wp_enqueue_script( 'custom-script');\n}\n}\nadd_action( 'wp_enqueue_scripts', 'custom_shortcode_scripts');\n</code></pre>\n" }, { "answer_id": 348350, "author": "Christian Žagarskas", "author_id": 144474, "author_profile": "https://wordpress.stackexchange.com/users/144474", "pm_score": 1, "selected": false, "text": "<p>We can indeed conditionally load CSS and JS files via shortcode without using any <em>overly elaborate</em> functions:</p>\n\n<p>First, let's assume we registered all of our CSS/JS files previously (perhaps when <code>wp_enqueue_scripts</code> ran) </p>\n\n<pre><code>function prep_css_and_js() {\n wp_register_style('my-css', $_css_url);\n wp_register_script('my-js', $_js_url);\n}\nadd_action( 'wp_enqueue_scripts', 'prep_css_and_js', 5 );\n</code></pre>\n\n<p>Next, lets examine our shortcode function:</p>\n\n<pre><code>function my_shortcode_func( $atts, $content = null ) {\n if( ! wp_style_is( \"my-css\", $list = 'enqueued' ) ) { wp_enqueue_style('my-css'); }\n if( ! wp_script_is( \"my-js\", $list = 'enqueued' ) ) { wp_enqueue_script('my-js'); }\n ...\n}\n</code></pre>\n\n<p>Simple. Done.\n<strong>Ergo: we can \"conditionally load\" css/js files, (only when [shortcode] runs).</strong></p>\n\n<p>Let's consider the following ideology: </p>\n\n<ul>\n<li>We want to load certain CSS/JS files (but only when shortcode is triggered)</li>\n<li>Maybe we do not want those files to load on every page, or at all if the shortcode is not used on a page/post. (light weight)</li>\n<li>We can accomplish this by making sure WP registers ALL of the css/js files prior to calling the shortcode and prior to the enqueue.</li>\n<li><em>IE: Maybe during my <code>prep_css_and_js()</code> function I load ALL .css/.js files that are in certain folders...</em></li>\n</ul>\n\n<p>Now that WP see's them as registered scripts, we can indeed call them, conditionally, based on a verity of situations, including but not limited to <code>my_shortcode_func()</code></p>\n\n<p>Benefits: (no MySQL, no advanced functions and no filters needed)</p>\n\n<ul>\n<li>this is \"WP orthodix\", elegant, fast loading, easy and simple</li>\n<li>allows compilers/minifiers to detect such scripts</li>\n<li>uses the WP functions (wp_register_style/wp_register_script)</li>\n<li>compatible with more themes/plugins that might want to de-register those scripts for a verity of reasons.</li>\n<li>will not trigger multiple times</li>\n<li>very little processing or code is involved</li>\n</ul>\n\n<p>References:</p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/wp_script_is\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_script_is</a></li>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/wp_register_style\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_register_style</a></li>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/wp_register_script\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_register_script</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_scripts/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_enqueue_scripts/</a></li>\n</ul>\n" } ]
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_widget\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/the_widget</a></p>\n<blockquote>\n<p>This template tag displays an arbitrary widget outside of a sidebar. It can be used anywhere in templates.</p>\n<pre><code> &lt;?php the_widget( $widget, $instance, $args ); ?&gt;\n</code></pre>\n</blockquote>\n<p>e.g. <code>&lt;?php the_widget( 'WP_Widget_Archives' ); ?&gt;</code></p>\n" }, { "answer_id": 317184, "author": "Remzi Cavdar", "author_id": 149484, "author_profile": "https://wordpress.stackexchange.com/users/149484", "pm_score": 0, "selected": false, "text": "<p>In Wordpress, widgets are shown in a sidebar. You should register a sidebar first, a footer and/or header widget area is also registered with a sidebar.</p>\n\n<p>I don't know if you're developing a plugin or theme.\nIf you're developing a theme you should do this in <strong>functions.php</strong> and for the plugin, it doesn't matter where you register a widget.</p>\n\n<p>See documantation: <a href=\"https://codex.wordpress.org/Function_Reference/register_sidebar\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_sidebar</a><br>\nFirst of all, let's register a sidebar:</p>\n\n<pre><code>function themename_widgets_init() {\nregister_sidebar( array(\n 'name' =&gt; __( 'Primary Sidebar', 'theme_name' ),\n 'id' =&gt; 'primary-sidebar',\n 'before_widget' =&gt; '&lt;aside id=\"%1$s\" class=\"widget %2$s\"&gt;',\n 'after_widget' =&gt; '&lt;/aside&gt;',\n 'before_title' =&gt; '&lt;h1 class=\"widget-title\"&gt;',\n 'after_title' =&gt; '&lt;/h1&gt;',\n) );\n\nregister_sidebar( array(\n 'name' =&gt; __( 'Footer', 'theme_name' ),\n 'id' =&gt; 'footer',\n 'before_widget' =&gt; '&lt;aside id=\"%1$s\" class=\"widget %2$s\"&gt;',\n 'after_widget' =&gt; '&lt;/aside&gt;',\n 'before_title' =&gt; '&lt;h1 class=\"widget-title\"&gt;',\n 'after_title' =&gt; '&lt;/h1&gt;',\n) );\n\n}\nadd_action( 'widgets_init', 'themename_widgets_init' );\n</code></pre>\n\n<p>See documantation: <a href=\"https://developer.wordpress.org/themes/functionality/sidebars/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/functionality/sidebars/</a><br>\nTo display these sidebars you need to put <code>&lt;?php get_sidebar(); ?&gt;</code> somewhere and create the <strong>sidebar.php</strong> template file and display the sidebar using the dynamic_sidebar function like so:<br> <code>&lt;?php dynamic_sidebar( 'primary-sidebar' ); ?&gt;</code></p>\n\n<p>See documentation: <a href=\"https://codex.wordpress.org/Widgets_API\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Widgets_API</a><br>\nThen we create our widget:</p>\n\n<pre><code>/**\n * Adds Foo_Widget widget.\n */\nclass Foo_Widget extends WP_Widget {\n\n/**\n * Register widget with WordPress.\n */\nfunction __construct() {\n parent::__construct(\n 'foo_widget', // Base ID\n esc_html__( 'Widget Title', 'text_domain' ), // Name\n array( 'description' =&gt; esc_html__( 'A Foo Widget', 'text_domain' ), ) // Args\n );\n}\n\n/**\n * Front-end display of widget.\n *\n * @see WP_Widget::widget()\n *\n * @param array $args Widget arguments.\n * @param array $instance Saved values from database.\n */\npublic function widget( $args, $instance ) {\n echo $args['before_widget'];\n if ( ! empty( $instance['title'] ) ) {\n echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];\n }\n echo esc_html__( 'Hello, World!', 'text_domain' );\n echo $args['after_widget'];\n}\n\n/**\n * Back-end widget form.\n *\n * @see WP_Widget::form()\n *\n * @param array $instance Previously saved values from database.\n */\npublic function form( $instance ) {\n $title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( 'New title', 'text_domain' );\n ?&gt;\n &lt;p&gt;\n &lt;label for=\"&lt;?php echo esc_attr( $this-&gt;get_field_id( 'title' ) ); ?&gt;\"&gt;&lt;?php esc_attr_e( 'Title:', 'text_domain' ); ?&gt;&lt;/label&gt; \n &lt;input class=\"widefat\" id=\"&lt;?php echo esc_attr( $this-&gt;get_field_id( 'title' ) ); ?&gt;\" name=\"&lt;?php echo esc_attr( $this-&gt;get_field_name( 'title' ) ); ?&gt;\" type=\"text\" value=\"&lt;?php echo esc_attr( $title ); ?&gt;\"&gt;\n &lt;/p&gt;\n &lt;?php \n}\n\n/**\n * Sanitize widget form values as they are saved.\n *\n * @see WP_Widget::update()\n *\n * @param array $new_instance Values just sent to be saved.\n * @param array $old_instance Previously saved values from database.\n *\n * @return array Updated safe values to be saved.\n */\npublic function update( $new_instance, $old_instance ) {\n $instance = array();\n $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? sanitize_text_field( $new_instance['title'] ) : '';\n\n return $instance;\n}\n\n} // class Foo_Widget\n</code></pre>\n\n<p>And finally you need to register this widget:</p>\n\n<pre><code>// register Foo_Widget widget\nfunction register_foo_widget() {\n register_widget( 'Foo_Widget' );\n}\nadd_action( 'widgets_init', 'register_foo_widget' );\n</code></pre>\n" } ]
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 noreferrer\"><code>wp_schedule_event</code></a> function has the <a href=\"https://developer.wordpress.org/reference/hooks/schedule_event/\" rel=\"nofollow noreferrer\"><code>schedule_event</code></a> filter inside it. If you take a look at the <a href=\"https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/cron.php#L102\" rel=\"nofollow noreferrer\">wp-includes/cron.php lines 102-106</a> you can see how it is used.</p>\n\n<p>Perhaps you could hook a custom function to that filter. In your custom filter function you could then do some local time check and short circuit the main function (<em>i.e. return false</em>), if it's the wrong time.</p>\n\n<p>I haven't tested or done this myself before, but this idea just came to my mind.</p>\n" }, { "answer_id": 317182, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<h2>Part 1. The Time != The Timestamp</h2>\n\n<p><a href=\"https://i.stack.imgur.com/m2QtV.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/m2QtV.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>This is your problem:</p>\n\n<blockquote>\n <p>every midnight at Local Timestamp</p>\n</blockquote>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>e.g. here we take a UTC date and change it to Moscow time:</p>\n\n<pre><code>$date = new DateTime('2012-07-16 01:00:00 +00');\n$date-&gt;setTimezone(new DateTimeZone('Europe/Moscow')); // +04\n\necho $date-&gt;format('Y-m-d H:i:s'); // 2012-07-15 05:00:00 \n</code></pre>\n\n<p>And here we take a Bangkok time and convert it to UTC:</p>\n\n<pre><code>$given = new DateTime(\"2014-12-12 14:18:00 +07\");\necho $given-&gt;format(\"Y-m-d H:i:s e\") . \"\\n\"; // 2014-12-12 14:18:00 Asia/Bangkok\n\n$given-&gt;setTimezone(new DateTimeZone(\"UTC\"));\necho $given-&gt;format(\"Y-m-d H:i:s e\") . \"\\n\"; // 2014-12-12 07:18:00 UTC\n</code></pre>\n\n<p>If you still want to specify things in local time just write a function to do the conversion, e.g. <code>$utc_time = convert_to_utc( \"time in local timezone\")</code></p>\n\n<h2>Part 2. Why UTC?</h2>\n\n<p>Have you ever noticed why some timezones are referenced as <strong>+8</strong> hours or <strong>-2</strong>? That would be UTC+8 or UTC-2. UTC is also known as coordinated universal time.</p>\n\n<p>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.</p>\n\n<h3>So Can I make WP use the local timezone for timestamps?</h3>\n\n<p>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</p>\n\n<p>It's a very bad idea. It also breaks the fundamental system of a timestamp on your site.</p>\n\n<p>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.</p>\n" } ]
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 it, e.g.:</p>\n\n<pre><code>'supports' =&gt; array( 'title', 'editor', 'custom-fields' )\n</code></pre>\n\n<p>But most people don't do this, and build real metaboxes instead. This way instead they can put in radio buttons and drop downs etc</p>\n" }, { "answer_id": 317230, "author": "Pim", "author_id": 50432, "author_profile": "https://wordpress.stackexchange.com/users/50432", "pm_score": 4, "selected": true, "text": "<p>It turns out the latest Advanced Custom Fields update (from version 5.6.0 on) removes the core custom fields metaboxes by default.</p>\n\n<p>The way to restore it was to add a filter in <code>functions.php</code>:</p>\n\n<pre><code>add_filter('acf/settings/remove_wp_meta_box', '__return_false');\n</code></pre>\n" } ]
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 it, e.g.:</p>\n\n<pre><code>'supports' =&gt; array( 'title', 'editor', 'custom-fields' )\n</code></pre>\n\n<p>But most people don't do this, and build real metaboxes instead. This way instead they can put in radio buttons and drop downs etc</p>\n" }, { "answer_id": 317230, "author": "Pim", "author_id": 50432, "author_profile": "https://wordpress.stackexchange.com/users/50432", "pm_score": 4, "selected": true, "text": "<p>It turns out the latest Advanced Custom Fields update (from version 5.6.0 on) removes the core custom fields metaboxes by default.</p>\n\n<p>The way to restore it was to add a filter in <code>functions.php</code>:</p>\n\n<pre><code>add_filter('acf/settings/remove_wp_meta_box', '__return_false');\n</code></pre>\n" } ]
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_excerpt</code> filter like this.</p>\n\n<pre><code>add_filter( 'get_the_excerpt', 'wp256_use_content_as_excerpt', 10, 2 );\nfunction wp256_use_content_as_excerpt( $excerpt, $post ) {\n return wp_strip_all_tags( $post-&gt;post_content );\n}\n</code></pre>\n" }, { "answer_id": 414322, "author": "jimmynesham", "author_id": 230457, "author_profile": "https://wordpress.stackexchange.com/users/230457", "pm_score": 0, "selected": false, "text": "<p>To display full post content instead of the excerpt in WordPress, you can modify the code in the template file that displays the post on your website. Here are the steps:</p>\n<p>Locate the template file for the post display on your WordPress website. The most common file is single.php for single posts, or archive.php for archive pages.</p>\n<p>Open the template file in a code editor.</p>\n<p>Find the code that displays the post excerpt. This is usually represented by the the_excerpt() function.</p>\n<p>Replace the_excerpt() with the_content(). This will display the full post content instead of the excerpt.</p>\n<p>Save the changes to the template file and refresh the page to see the updated content display.</p>\n<p>Note that this change will affect all posts that use this template file. If you want to only display full content for specific posts, you can use a plugin or custom field to indicate which posts should display full content instead of an excerpt.</p>\n<p>I did same for my client website</p>\n" } ]
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 that <a href=\"https://www.w3schools.com/tags/att_script_defer.asp\" rel=\"nofollow noreferrer\"><code>defer</code></a> will not work with inline scripts. So, the easiest approach is to add an <a href=\"https://www.w3schools.com/jsref/met_document_addeventlistener.asp\" rel=\"nofollow noreferrer\">event listener</a> to the script which will hold up the execution until the page is loaded:</p>\n\n<pre><code>window.addEventListener (\"load\", function() {\n ... your script ...\n }\n</code></pre>\n" }, { "answer_id": 317490, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 2, "selected": false, "text": "<p>@cjbj is right, I upvote him. However, you can try another approach if you want - move that script into a file (i.e. <code>wp-content/your_script.js</code>) and then insert it into widget with <code>defer</code>:</p>\n\n<pre><code>&lt;script src=\"https://yoursite.com/wp-content/your_script.js\" defer&gt;&lt;/script&gt;\n</code></pre>\n\n<p>p.s. your specific script looks not professional though(probably not written by javascript specialists). To force it to stay within your specific html area, do this:</p>\n\n<ul>\n<li>put the script inside div: <code>&lt;div id=\"my_cripto\"&gt;&lt;script src.......&gt;&lt;/div&gt;</code></li>\n<li><p>in the <code>.js</code> file, do this modification:</p>\n\n<p><code>var embedder = document.getElementById(\"my_cripto\");</code></p></li>\n</ul>\n" }, { "answer_id": 317524, "author": "Александр Фишер", "author_id": 63128, "author_profile": "https://wordpress.stackexchange.com/users/63128", "pm_score": 3, "selected": true, "text": "<p>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 <code>s.defer = true;</code> after <code>s.async = true;</code> to add the <code>defer</code> attribute to your script tag. It should then look like this:</p>\n\n<pre><code>var s = document.createElement(\"script\");\ns.type = \"text/javascript\";\ns.async = true;\ns.defer = true; //add this line\nvar theUrl = baseUrl+'serve/v1/coin/multi?fsyms=BTC,LBC,ETH&amp;tsyms=USD,BTC,GBP,CNY';\ns.src = theUrl + ( theUrl.indexOf(\"?\") &gt;= 0 ? \"&amp;\" : \"?\") + \"app=\" + appName;\nembedder.parentNode.appendChild(s);\n</code></pre>\n\n<p>This should result in adding a new script tag (named <code>s</code> in your code) to all the scripts the page will load and it should look like this:</p>\n\n<pre><code>&lt;script type=\"text/javascript\" async defer src=\"https://widgets.cryptocompare.com/serve/v1/coin/multi?fsyms=BTC,LBC,ETH&amp;amp;tsyms=USD,BTC,GBP,CNY\"&gt;&lt;/script&gt;\n</code></pre>\n" } ]
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 that <a href=\"https://www.w3schools.com/tags/att_script_defer.asp\" rel=\"nofollow noreferrer\"><code>defer</code></a> will not work with inline scripts. So, the easiest approach is to add an <a href=\"https://www.w3schools.com/jsref/met_document_addeventlistener.asp\" rel=\"nofollow noreferrer\">event listener</a> to the script which will hold up the execution until the page is loaded:</p>\n\n<pre><code>window.addEventListener (\"load\", function() {\n ... your script ...\n }\n</code></pre>\n" }, { "answer_id": 317490, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 2, "selected": false, "text": "<p>@cjbj is right, I upvote him. However, you can try another approach if you want - move that script into a file (i.e. <code>wp-content/your_script.js</code>) and then insert it into widget with <code>defer</code>:</p>\n\n<pre><code>&lt;script src=\"https://yoursite.com/wp-content/your_script.js\" defer&gt;&lt;/script&gt;\n</code></pre>\n\n<p>p.s. your specific script looks not professional though(probably not written by javascript specialists). To force it to stay within your specific html area, do this:</p>\n\n<ul>\n<li>put the script inside div: <code>&lt;div id=\"my_cripto\"&gt;&lt;script src.......&gt;&lt;/div&gt;</code></li>\n<li><p>in the <code>.js</code> file, do this modification:</p>\n\n<p><code>var embedder = document.getElementById(\"my_cripto\");</code></p></li>\n</ul>\n" }, { "answer_id": 317524, "author": "Александр Фишер", "author_id": 63128, "author_profile": "https://wordpress.stackexchange.com/users/63128", "pm_score": 3, "selected": true, "text": "<p>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 <code>s.defer = true;</code> after <code>s.async = true;</code> to add the <code>defer</code> attribute to your script tag. It should then look like this:</p>\n\n<pre><code>var s = document.createElement(\"script\");\ns.type = \"text/javascript\";\ns.async = true;\ns.defer = true; //add this line\nvar theUrl = baseUrl+'serve/v1/coin/multi?fsyms=BTC,LBC,ETH&amp;tsyms=USD,BTC,GBP,CNY';\ns.src = theUrl + ( theUrl.indexOf(\"?\") &gt;= 0 ? \"&amp;\" : \"?\") + \"app=\" + appName;\nembedder.parentNode.appendChild(s);\n</code></pre>\n\n<p>This should result in adding a new script tag (named <code>s</code> in your code) to all the scripts the page will load and it should look like this:</p>\n\n<pre><code>&lt;script type=\"text/javascript\" async defer src=\"https://widgets.cryptocompare.com/serve/v1/coin/multi?fsyms=BTC,LBC,ETH&amp;amp;tsyms=USD,BTC,GBP,CNY\"&gt;&lt;/script&gt;\n</code></pre>\n" } ]
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/Plugin_API/Action_Reference/wp_ajax_(action)\" rel=\"nofollow noreferrer\">wp_ajax_{action}</a> codex entry, </p>\n\n<blockquote>\n <p>The wp_ajax_ hooks follows the format \"wp_ajax_$youraction\", where $youraction is the 'action' field submitted to admin-ajax.php. </p>\n</blockquote>\n\n<p>So try changing <code>action: 'makeBooking',</code> to <code>action: 'make_booking',</code> and see if it works then.</p>\n\n<p>And if you want the ajax call to work for non-logged-in users, use also the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)\" rel=\"nofollow noreferrer\">wp_ajax_nopriv_{action}</a> action hook. Like this</p>\n\n<pre><code>add_action('wp_ajax_nopriv_make_booking', 'makeBooking');\n</code></pre>\n\n<p><strong>EDIT:</strong> Oh, silly me. You're also missing <code>wp_die();</code> from the end of your ajax response. See <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">codex / AJAX in Plugins</a> for more details.</p>\n\n<pre><code>function makeBooking(){\n echo \"Home again\";\n wp_die(); // this is required to terminate immediately and return a proper response\n}\n</code></pre>\n\n<p><strong>EDIT 2:</strong> You could also use <a href=\"https://codex.wordpress.org/Function_Reference/wp_send_json\" rel=\"nofollow noreferrer\"><code>wp_send_json</code></a> instead of echoing your response.</p>\n" }, { "answer_id": 317282, "author": "Mehul", "author_id": 152745, "author_profile": "https://wordpress.stackexchange.com/users/152745", "pm_score": -1, "selected": false, "text": "<p>add below actions</p>\n\n<pre><code>add_action( 'wp_ajax_makeBooking', 'makeBooking');\nadd_action( 'wp_ajax_nopriv_makeBooking', 'makeBooking');\n</code></pre>\n" }, { "answer_id": 317301, "author": "Alexander Holsgrove", "author_id": 48962, "author_profile": "https://wordpress.stackexchange.com/users/48962", "pm_score": 2, "selected": true, "text": "<p>It looks like the <code>MBAjax.ajaxurl</code> and <code>MBAjax.admin_url</code> 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.</p>\n\n<p>You can test by hard-coding the ajax url to <code>url: \"/wp-admin/admin-ajax.php\",</code> and see if that fixes things.</p>\n\n<p>Secondly, I have always added a hidden field on my forms with the action <code>&lt;input type=\"hidden\" name=\"action\" value=\"make_booking\"&gt;</code></p>\n\n<p>Try that and see how you get on. Also check your browser console <code>network</code> 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.</p>\n\n<p><a href=\"https://i.stack.imgur.com/2HmpS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2HmpS.png\" alt=\"enter image description here\"></a></p>\n\n<p>You can also use <code>console.log(x)</code> instead.</p>\n\n<p>Update: I think you're missing sending anything in your AJAX request:</p>\n\n<pre><code>jQuery.ajax({\n action : 'make_booking',\n type : \"POST\",\n data : {\n action: 'make_booking'\n }\n url : MBAjax.admin_url,\n success: function(data) {\n alert(data);\n //jQuery(\"#container\" ).append(data);\n },\n fail: function(error){\n alert(\"error\" + error);\n }\n});\n</code></pre>\n\n<p>Try that.</p>\n" } ]
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 include <code>the_content()</code> for each of your posts on the left hand side. Wrap this content with <code>&lt;div class=\"article-content\"&gt;..&lt;/div&gt;</code> so that you can easily access it with javascript.</p>\n\n<p>Next, you need to add the click handler to do display the post content on the right hand side when you click one of the posts.</p>\n\n<p>If you had this structure:</p>\n\n<pre><code>&lt;div class=\"left\"&gt;\n &lt;article&gt;\n &lt;h2&gt;My post title&lt;/h2&gt;\n &lt;div class=\"article-content\"&gt;&lt;p&gt;Lorem Ipsum&lt;/p&gt;&lt;/div&gt;\n &lt;/article&gt;\n\n &lt;article&gt;\n &lt;h2&gt;Another post title&lt;/h2&gt;\n &lt;div class=\"article-content\"&gt;&lt;p&gt;Lorem Ipsum&lt;/p&gt;&lt;/div&gt;\n &lt;/article&gt;\n\n &lt;article&gt;\n &lt;h2&gt;Third post title&lt;/h2&gt;\n &lt;div class=\"article-content\"&gt;&lt;p&gt;Lorem Ipsum&lt;/p&gt;&lt;/div&gt;\n &lt;/article&gt;\n&lt;/div&gt;\n</code></pre>\n\n\n\n<p>I'm assuming jQuery is available, so you could use the following:</p>\n\n<pre><code>$('.left article').on('click', function(event) {\n var article_content = $(this).children('.article-content').html()\n $('.right').html(article_content);\n});\n</code></pre>\n\n<p>I've made a handy fiddle for you. It's very basic, but it gives you something to start with: <a href=\"https://jsfiddle.net/g0bxwy6k/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/g0bxwy6k/</a></p>\n" }, { "answer_id": 317470, "author": "Cesar H", "author_id": 152738, "author_profile": "https://wordpress.stackexchange.com/users/152738", "pm_score": 1, "selected": false, "text": "<p>OK, I managed to make it work, here's how i did : </p>\n\n<p>Jquery part : </p>\n\n<pre><code>jQuery(\".post-link\").click(function(){\n var post_id = jQuery(this).data('id');\n\n jQuery.post(\n ajaxurl,\n {\n 'action': 'load_post_content',\n 'the_ID': post_id\n },\n function(response){\n jQuery('#the-post-content').html(response);\n }\n );\n\n return false;\n});\n</code></pre>\n\n<p>And the function.php part : </p>\n\n<pre><code>add_action( 'wp_ajax_load_post_content', 'load_post_content' );\nadd_action( 'wp_ajax_nopriv_load_post_content', 'load_post_content' );\n\nfunction load_post_content() {\n\n $the_post_id = $_POST['the_ID'];\n $args = array(\n 'post_type' =&gt; 'post',\n 'p' =&gt; $the_post_id\n );\n\n $ajax_query = new WP_Query($args);\n\n $the_content;\n\n if ( $ajax_query-&gt;have_posts() ) : while ( $ajax_query-&gt;have_posts() ) : $ajax_query-&gt;the_post();\n $the_content = the_content();\n endwhile;\n endif; \n\n echo $the_content;\n\n wp_reset_postdata();\n\n die();\n}\n</code></pre>\n\n<p>Hope it can help !</p>\n" } ]
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 their structured date testing tool: <a href=\"https://search.google.com/structured-data/testing-tool\" rel=\"nofollow noreferrer\">https://search.google.com/structured-data/testing-tool</a></p>\n" }, { "answer_id": 317438, "author": "unor", "author_id": 34147, "author_profile": "https://wordpress.stackexchange.com/users/34147", "pm_score": 1, "selected": false, "text": "<p>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.): </p>\n\n<p><strong>Give both <code>Product</code> items the same URI as ID.</strong> This conveys to consumers that both of the <code>Product</code> items are about the same product, not different products. Here is an <a href=\"https://webmasters.stackexchange.com/a/117586/17633\">example with all three syntaxes (JSON-LD, Microdata, RDFa)</a>.</p>\n\n<p>(Of course, the ideal solution would be to have only one <code>Product</code> item in the first place, but this is often impossible or hard to implement.)</p>\n" } ]
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 filepath is the path to your file.</p>\n" }, { "answer_id": 321301, "author": "Zsolti", "author_id": 39179, "author_profile": "https://wordpress.stackexchange.com/users/39179", "pm_score": 0, "selected": false, "text": "<p>This is kind of tricky to do, but it is possible. Write a class which will extend <code>PHPMailer</code>. Override the <code>addAttachment</code> method, so in a certain condition (ex. you make a Boolean class variable) it will call <code>addStringAttachment</code> from the original class and in every other cases the <code>addAttachment</code> class. All you have to do is to set </p>\n\n<p><code>$attachment = array(\"your content goes here\");</code></p>\n\n<p>When this is done, make sure that the global <code>$phpmailer</code> variable is an instance of your class and then create the specific condition. <code>wp_mail</code> will call the <code>addAttachment</code> from your class, and together with your special condition the attachment will be sent without saving the file.</p>\n" }, { "answer_id": 377515, "author": "Shaun Cockerill", "author_id": 124137, "author_profile": "https://wordpress.stackexchange.com/users/124137", "pm_score": 1, "selected": false, "text": "<p>It is possible to add an attachment using the standard 'wp_mail' function, however you would need to hook into the <code>phpmailer_init</code> action to do so.</p>\n<p>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 <code>use ( $attachments )</code> statement, store the attachment content as a global variable or property, or place the attachment generation code into the new function.</p>\n<p>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.</p>\n<pre><code> // Previous Code...\n \n // Use this action to generate and/or attach files.\n add_filter( 'phpmailer_init', array( $this, 'add_attachments' ) );\n // And/or store the attachments as a property.\n $this-&gt;set_attachments( $attachments );\n \n $sent = wp_mail( $to, $subject, $message, $this-&gt;get_headers() );\n\n // Log errors etc...\n if ( ! $sent ) {\n //...\n $this-&gt;log_error( $error_message );\n }\n}\n\n/**\n * Add attachments to the email.\n *\n * This method must be public in order to work as an action.\n * @param PHPMailer\\PHPMailer\\PHPMailer $phpmailer\n */\npublic function add_attachments( $phpmailer ) {\n // Remove filter to prevent attaching the files to subsequent emails.\n remove_action( 'phpmailer_init', array( $this, 'add_attachments' ) );\n // Get or generate the attachments somehow.\n foreach ( $this-&gt;get_attachments() as $filename, $file_contents ) {\n try {\n $phpmailer-&gt;addStringAttachment( $file_contents, $filename );\n } catch( \\Exception $ex ) {\n // An exception may thrown which would prevent the remaining files from being attached, so we'll catch these and log the errors.\n // 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.\n $this-&gt;log_error( $ex-&gt;getMessage() );\n }\n }\n}\n\n/**\n * Abstraction for the logging code to make it reusable.\n * @param string $log_message\n */\nprotected function log_error( $log_message ) {\n if ( ! $this-&gt;log_errors ) {\n return;\n }\n // Log errors here.\n}\n</code></pre>\n" } ]
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=\"pagination\"&gt;\n &lt;span&gt;Page {current} of {total pages}&lt;/span&gt;\n {links here}\n&lt;/div&gt;\n</code></pre>\n\n<p>And you attempted it like so:</p>\n\n<pre><code>'before_page_number' =&gt; '&lt;div class=\"pagination\"&gt;&lt;span&gt;Page '. // wrapped for clarity\n $paged .' of ' . $term-&gt;max_num_pages . '&lt;/span&gt;&lt;/div&gt;'\n</code></pre>\n\n<p>But that will actually add the markup before <em>each and every</em> page number in the generated links. (And the <code>$term-&gt;max_num_pages</code> is also a <code>null</code> because in that context, <code>$term</code> doesn't have a <code>max_num_pages</code> property.)</p>\n\n<p>So here's how you could achieve the expected output:</p>\n\n<pre><code>$big = 999999999; // need an unlikely integer\n$cur_page = max( 1, $paged );\n$num_pages = ceil( $number_of_terms / $per_page );\n$links = paginate_links(\n array(\n 'base' =&gt; str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' =&gt; '/page/%#%',\n 'current' =&gt; $cur_page,\n 'total' =&gt; $num_pages,\n 'prev_text' =&gt; __(''),\n 'next_text' =&gt; __('')\n )\n);\n\n// If there are links to paginate, display the pagination.\nif ( $links ) {\n $before = '&lt;span&gt;Page '. $cur_page .' of ' . $num_pages . '&lt;/span&gt;';\n echo '&lt;div class=\"pagination\"&gt;' . $before . ' ' . $links . '&lt;/div&gt;';\n}\n</code></pre>\n\n<p>See the <code>paginate_links()</code> <a href=\"https://developer.wordpress.org/reference/functions/paginate_links/\" rel=\"nofollow noreferrer\">reference</a> for more details on that function, such as the <code>mid_size</code> and <code>end_size</code> parameters that control the number of pages/links to be displayed.</p>\n" }, { "answer_id": 317605, "author": "Peter", "author_id": 151946, "author_profile": "https://wordpress.stackexchange.com/users/151946", "pm_score": 1, "selected": true, "text": "<p>The following will loop through a custom taxonomy and pull all the associated terms.</p>\n\n<pre><code>&lt;?php if ( get_query_var( 'paged' ) ) {\n $page = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;\n }\n\n $per_page = 9;\n $totalterms = wp_count_terms( 'series' ); \n $totalpages = ceil( $totalterms / $per_page );\n $paged_offset = ( $page &gt; 0 ) ? $per_page * ( $page - 1 ) : 1;\n\n $args = array(\n 'orderby' =&gt; 'ID', \n 'order' =&gt; 'DSC',\n 'hide_empty' =&gt; true, \n 'exclude' =&gt; array(), \n 'exclude_tree' =&gt; array(), \n 'include' =&gt; array(),\n 'number' =&gt; $per_page, \n 'fields' =&gt; 'all', \n 'slug' =&gt; '', \n 'parent' =&gt; '',\n 'hierarchical' =&gt; true, \n 'child_of' =&gt; 0, \n 'get' =&gt; '', \n 'name__like' =&gt; '',\n 'pad_counts' =&gt; false, \n 'offset' =&gt; $paged_offset, \n 'search' =&gt; '', \n 'cache_domain' =&gt; 'core'\n );\n\n $terms = get_terms('series', $args); \n\n foreach($terms as $term){ ?&gt;\n\n &lt;div class=\"block_item article\"&gt;\n &lt;div class=\"block_item_overlay\"&gt;&lt;/div&gt;\n &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;\n &lt;h4 class=\"section_label\"&gt;&lt;?php the_field('date', $term); ?&gt;&lt;/h4&gt;\n &lt;div class=\"block_item_content\"&gt;\n &lt;h3&gt;&lt;?php echo $term-&gt;name; ?&gt;&lt;/h3&gt;\n &lt;p&gt;&lt;?php echo $term-&gt;description; ?&gt;&lt;/p&gt;\n &lt;a href=\"&lt;?php echo get_term_link($term-&gt;slug, 'series'); ?&gt;\" class=\"button_styling\"&gt;\n Read More\n &lt;/a&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n\n &lt;?php } \n\n $big = 999999999; // need an unlikely integer\n printf( '&lt;div class=\"pagination\"&gt;&lt;span&gt;Page '.$page.' of '.$totalpages.'&lt;/span&gt;', \n custom_page_navi( $totalpages, $page, 3, 0 ) \n );\n\n echo paginate_links( \n array(\n 'base' =&gt; str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' =&gt; '/page/%#%',\n 'current' =&gt; max( 1, get_query_var('paged') ),\n 'total' =&gt; ceil( $totalterms / $per_page ),\n 'prev_next' =&gt; false\n ) \n ); ?&gt;\n &lt;/div&gt;\n</code></pre>\n" } ]
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=\"pagination\"&gt;\n &lt;span&gt;Page {current} of {total pages}&lt;/span&gt;\n {links here}\n&lt;/div&gt;\n</code></pre>\n\n<p>And you attempted it like so:</p>\n\n<pre><code>'before_page_number' =&gt; '&lt;div class=\"pagination\"&gt;&lt;span&gt;Page '. // wrapped for clarity\n $paged .' of ' . $term-&gt;max_num_pages . '&lt;/span&gt;&lt;/div&gt;'\n</code></pre>\n\n<p>But that will actually add the markup before <em>each and every</em> page number in the generated links. (And the <code>$term-&gt;max_num_pages</code> is also a <code>null</code> because in that context, <code>$term</code> doesn't have a <code>max_num_pages</code> property.)</p>\n\n<p>So here's how you could achieve the expected output:</p>\n\n<pre><code>$big = 999999999; // need an unlikely integer\n$cur_page = max( 1, $paged );\n$num_pages = ceil( $number_of_terms / $per_page );\n$links = paginate_links(\n array(\n 'base' =&gt; str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' =&gt; '/page/%#%',\n 'current' =&gt; $cur_page,\n 'total' =&gt; $num_pages,\n 'prev_text' =&gt; __(''),\n 'next_text' =&gt; __('')\n )\n);\n\n// If there are links to paginate, display the pagination.\nif ( $links ) {\n $before = '&lt;span&gt;Page '. $cur_page .' of ' . $num_pages . '&lt;/span&gt;';\n echo '&lt;div class=\"pagination\"&gt;' . $before . ' ' . $links . '&lt;/div&gt;';\n}\n</code></pre>\n\n<p>See the <code>paginate_links()</code> <a href=\"https://developer.wordpress.org/reference/functions/paginate_links/\" rel=\"nofollow noreferrer\">reference</a> for more details on that function, such as the <code>mid_size</code> and <code>end_size</code> parameters that control the number of pages/links to be displayed.</p>\n" }, { "answer_id": 317605, "author": "Peter", "author_id": 151946, "author_profile": "https://wordpress.stackexchange.com/users/151946", "pm_score": 1, "selected": true, "text": "<p>The following will loop through a custom taxonomy and pull all the associated terms.</p>\n\n<pre><code>&lt;?php if ( get_query_var( 'paged' ) ) {\n $page = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;\n }\n\n $per_page = 9;\n $totalterms = wp_count_terms( 'series' ); \n $totalpages = ceil( $totalterms / $per_page );\n $paged_offset = ( $page &gt; 0 ) ? $per_page * ( $page - 1 ) : 1;\n\n $args = array(\n 'orderby' =&gt; 'ID', \n 'order' =&gt; 'DSC',\n 'hide_empty' =&gt; true, \n 'exclude' =&gt; array(), \n 'exclude_tree' =&gt; array(), \n 'include' =&gt; array(),\n 'number' =&gt; $per_page, \n 'fields' =&gt; 'all', \n 'slug' =&gt; '', \n 'parent' =&gt; '',\n 'hierarchical' =&gt; true, \n 'child_of' =&gt; 0, \n 'get' =&gt; '', \n 'name__like' =&gt; '',\n 'pad_counts' =&gt; false, \n 'offset' =&gt; $paged_offset, \n 'search' =&gt; '', \n 'cache_domain' =&gt; 'core'\n );\n\n $terms = get_terms('series', $args); \n\n foreach($terms as $term){ ?&gt;\n\n &lt;div class=\"block_item article\"&gt;\n &lt;div class=\"block_item_overlay\"&gt;&lt;/div&gt;\n &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;\n &lt;h4 class=\"section_label\"&gt;&lt;?php the_field('date', $term); ?&gt;&lt;/h4&gt;\n &lt;div class=\"block_item_content\"&gt;\n &lt;h3&gt;&lt;?php echo $term-&gt;name; ?&gt;&lt;/h3&gt;\n &lt;p&gt;&lt;?php echo $term-&gt;description; ?&gt;&lt;/p&gt;\n &lt;a href=\"&lt;?php echo get_term_link($term-&gt;slug, 'series'); ?&gt;\" class=\"button_styling\"&gt;\n Read More\n &lt;/a&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n\n &lt;?php } \n\n $big = 999999999; // need an unlikely integer\n printf( '&lt;div class=\"pagination\"&gt;&lt;span&gt;Page '.$page.' of '.$totalpages.'&lt;/span&gt;', \n custom_page_navi( $totalpages, $page, 3, 0 ) \n );\n\n echo paginate_links( \n array(\n 'base' =&gt; str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' =&gt; '/page/%#%',\n 'current' =&gt; max( 1, get_query_var('paged') ),\n 'total' =&gt; ceil( $totalterms / $per_page ),\n 'prev_next' =&gt; false\n ) \n ); ?&gt;\n &lt;/div&gt;\n</code></pre>\n" } ]
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/\" rel=\"nofollow noreferrer\">rest_pre_dispatch</a> hook.</p>\n\n<p>This hook allows hijacking the request before dispatching by returning a non-empty. The returned value will be used to serve the request instead. </p>\n\n<p>From the docs: </p>\n\n<pre><code>$result\n\n(mixed) Response to replace the requested version with. Can be anything a normal endpoint can return, or null to not hijack the request.\n</code></pre>\n\n<p>Seems like to you have to modify the $request and return null in order to no hijack the default response.</p>\n" }, { "answer_id": 317830, "author": "Timothy Jacobs", "author_id": 152653, "author_profile": "https://wordpress.stackexchange.com/users/152653", "pm_score": 2, "selected": true, "text": "<p>Using the <code>rest_pre_dispatch</code> hook is probably the most straightforward way to go, but you need to be careful about putting your new request data back into the <code>WP_REST_Request</code> object properly.</p>\n\n<p>You were reassigning the <code>WP_REST_Request</code> 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 <code>WP_REST_Request</code> object. </p>\n\n<p>You can assign a parameter to the request object using array like syntax, or by using <code>WP_REST_Request::set_param( $param_name, $param_value )</code>.</p>\n\n<p>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.</p>\n\n<pre><code>function wpse281916_rest_check_referer( $result, $server, $request ) {\n\n if ( '/wp/v2/jobs' !== $request-&gt;get_route() || 'POST' !== $request-&gt;get_method()) {\n return $result;\n }\n\n $job_sector = $request['job_sector'];\n\n if ( null === $job_sector ) {\n return $result;\n }\n\n $term = get_term_by( 'name', $job_sector, 'job_sector' );\n\n if ( $term &amp;&amp; ! is_wp_error( $term ) ) {\n $request['job_sector'] = $term-&gt;term_id;\n } else {\n $request['job_sector'] = 0;\n }\n\n return $result;\n}\n\n// add the filter\nadd_filter( 'rest_pre_dispatch', 'wpse281916_rest_check_referer', 0, 3 );\n</code></pre>\n" } ]
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 remove the second definition of the same constant.\nIt may be that it's been defined somewhere else. So search all the files of WordPress using <code>grep</code>, <code>find</code> or some advanced text editor like Sublime Text</p>\n" }, { "answer_id": 317739, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>When defining any WordPress constants in wp-config.php you need to do it before this line: </p>\n\n<pre><code>require_once( ABSPATH . 'wp-settings.php' );\n</code></pre>\n\n<p>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. </p>\n" } ]
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, and it has a Content Checklist addon that allows you to choose a maximum and a minimum length of your WordPress content.</p>\n\n<p>Here's how PublishPress and the Content Checklist works ...</p>\n\n<ul>\n<li>Install the PublishPress plugin.</li>\n<li>Get the Content Checklist addon from PublishPress.com. Download the\nContent Checklist files.</li>\n<li>In your WordPress site, go to \"Plugins\", then \"Add New\" and install\nContent Checklist.</li>\n<li>Go to \"PublishPress\", then \"Checklist\" in your WordPress admin area.</li>\n<li>Look for the “Number of words” field. Here you can choose a minimum\nand maximum word count:</li>\n</ul>\n\n<p>More ideas at: <a href=\"https://www.ostraining.com/blog/wordpress/wordpress-word-count/\" rel=\"nofollow noreferrer\">https://www.ostraining.com/blog/wordpress/wordpress-word-count/</a></p>\n" }, { "answer_id": 317579, "author": "Quang Hoang", "author_id": 134874, "author_profile": "https://wordpress.stackexchange.com/users/134874", "pm_score": 0, "selected": false, "text": "<p>You can find the solutions for this <a href=\"https://wordpress.stackexchange.com/questions/52456/counting-words-in-a-post\">here</a>.</p>\n\n<p>Or please use Google to find another way, the keyword can be <em>\"count word of the post wp\"</em> or same it.</p>\n\n<p>Best regards,</p>\n" }, { "answer_id": 317587, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 1, "selected": false, "text": "<p>Here's a basic concept how I'd do the word counting and showing the count. Hopefully this serves as a starting point.</p>\n\n<p>I think it would be a good idea to store the word count in a <a href=\"https://codex.wordpress.org/Transients_API\" rel=\"nofollow noreferrer\">transient</a>, so it isn't calculated on each and every author archive page load.</p>\n\n<pre><code>function author_word_count() {\n // get current author\n $author_id = get_queried_object_id();\n // check if there's valid word count transient, show that if so\n $word_count = get_transient( $author_id . '_word_count' );\n if ( $word_count ) {\n echo $word_count;\n } else {\n // fallback to calculating word count, show it and save it as transient\n $word_count = calculate_author_posts_words( $author_id );\n echo $word_count;\n }\n}\n</code></pre>\n\n<p>Helper function for calculation</p>\n\n<pre><code>function calculate_author_posts_words( $author_id ) {\n $author_posts = get_author_posts( $author_id );\n $count = 0;\n if ( ! empty( $author_posts-&gt;posts ) ) {\n // If you have gazillion posts, then this might hit your server hard I guess. \n // There might be more performant ways to doing this, but I can't think of any right now\n foreach( $author_posts-&gt;posts as $p ) {\n $count = $count + prefix_wcount( $p-&gt;post_content );\n }\n }\n set_transient( $author_id . '_word_count', $count, $expiration ); // Save the count, set suitable expiration time\n return $count;\n}\n</code></pre>\n\n<p>Helper function to get authors posts</p>\n\n<pre><code>function get_author_posts( $id ) {\n // Do WP_Query with author's id and return it\n}\n</code></pre>\n\n<p>Helper function to count single post's word count. Modified from <a href=\"https://wordpress.stackexchange.com/questions/52456/counting-words-in-a-post\">Counting words in a post</a> </p>\n\n<pre><code>function prefix_wcount( $post_content ){\n return sizeof(explode(\" \", $post_content));\n}\n</code></pre>\n\n<p>You could also hook a custom update function to <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\"><code>save_post</code></a> to update the word count transient when a new post is made or and existing one is updated.</p>\n\n<pre><code>function update_word_count_transient( $post_id ) {\n // check that we're intentionally saving / updating post\n // get post content\n // get transient\n // calculate words and and it to transient count\n // save transient\n}\nadd_action( 'save_post', 'update_word_count_transient' );\n</code></pre>\n\n<p>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.</p>\n\n<p><em>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</em></p>\n" } ]
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 is not used. But here, I made it how you wanted. It takes either the path of the site or the first part of the subdomain, so it works with both types of multisite. It affects users created by users that are not super administrators.</p>\n\n<pre><code>add_filter( 'pre_user_login', 'sneakily_add_prefix_to_username' );\n\nfunction sneakily_add_prefix_to_username( $username ) {\n if ( ! current_user_can( 'manage_network' ) ) {\n $blog_id = get_current_blog_id();\n $blog_details = get_blog_details( $blog_id );\n $sanitized_path = sanitize_user( $blog_details-&gt;path, true );\n if ( $sanitized_path != '' ) {\n return $sanitized_path . '-' . $username;\n } else {\n $domain_parts = explode( '.', $blog_details-&gt;domain );\n if ( is_array( $domain_parts ) ) {\n $sanitized_subdomain = sanitize_user( $domain_parts[0], true );\n if ( $sanitized_subdomain != '' ) {\n return $sanitized_subdomain . '-' . $username;\n }\n }\n }\n }\n return $username;\n}\n</code></pre>\n" }, { "answer_id": 389002, "author": "Edgar Rodriguez", "author_id": 207202, "author_profile": "https://wordpress.stackexchange.com/users/207202", "pm_score": 1, "selected": false, "text": "<p>I have noticed that the code our friend shares has an error. Add the prefix twice.</p>\n<p>I share other code with this error resolved.</p>\n<pre><code>&lt;?php\n\n\nadd_filter( 'pre_user_login', 'sneakily_add_prefix_to_username' );\n\nfunction sneakily_add_prefix_to_username( $username ) {\n if ( ! current_user_can( 'manage_network' ) ) {\n $blog_id = get_current_blog_id();\n $blog_details = get_blog_details( $blog_id );\n $sanitized_path = str_replace( '/', '', get_blog_details()-&gt;path );\n //error_log($sanitized_path);\n if ( $sanitized_path != '') {\n if(false === stripos($username, $sanitized_path)) {\n return $sanitized_path . '-' . $username;\n } else {\n return $username;\n }\n } else {\n $domain_parts = explode( '.', $blog_details-&gt;domain );\n if ( is_array( $domain_parts ) ) {\n $sanitized_subdomain = sanitize_user( $domain_parts[0], true );\n //error_log($sanitized_subdomain);\n if ( $sanitized_subdomain != '' ) {\n if(false === stripos($username, $sanitized_subdomain)) {\n return $sanitized_subdomain . '-' . $username;\n } else {\n return $username;\n }\n }\n }\n }\n }\n return $username;\n}\n</code></pre>\n" } ]
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( '[email protected]', '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 hook your email sending after the user registration like this</p>\n\n<pre><code>global $uID; //to keep the value to reuse it later, null at this step\n\nfunction mailInscriptionSecteurRhone() {\nglobal $uID;\n$user_ID = $uID;\n $headers = array('Content-Type: text/html; charset=UTF-8');\n $candidat = get_userdata( $user_ID );\n $codePostalCandidat = get_field('code_postal', 'user_' . $user_ID );\n wp_mail( '[email protected]', 'Test', $codePostalCandidat, $headers );\n}\n\nfunction trigger_mailInscriptionSecteurRhone($user_ID)\n{\nglobal $uID;\n$uID = $user_ID;\n add_action( 'init', 'mailInscriptionSecteurRhone', 10 );\n}\nadd_action( 'user_register', 'trigger_mailInscriptionSecteurRhone', 10,1 );\n</code></pre>\n\n<p>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.\nI did not test this solution, it is a suggestion.</p>\n\n<p><strong>End edit</strong></p>\n\n<p>Ok maybe the user_register hook is triggered before acf is loaded (acc to your screenshot, you use acf)</p>\n\n<p>So, have you tried get_user_meta like this ?</p>\n\n<pre><code>$codePostalCandidat = get_user_meta($user_ID,'code_postal',true);\n</code></pre>\n" }, { "answer_id": 317628, "author": "djboris", "author_id": 152412, "author_profile": "https://wordpress.stackexchange.com/users/152412", "pm_score": 0, "selected": false, "text": "<p>I believe this action is triggered before the user meta has been saved. Try using <code>$_POST</code> variable to access the information you need, like this: <code>$first_name = $_POST['first_name'];</code> For the ACF custom fields, they are in array in <code>$_POST['acf']</code>, but indexed with their keys. You can find the key of the field by enabling it in the Field Group view in the Dashboard:</p>\n\n<p><a href=\"https://i.stack.imgur.com/RsI1H.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RsI1H.png\" alt=\"enter image description here\"></a></p>\n\n<p>And then call it like this: <code>$_POST['acf']['field_5bd2cb1f779bf']</code></p>\n\n<p>There is currently no easy way to get this key value dynamically, except to use some custom function like <a href=\"https://gist.github.com/mcguffin/81509c36a4a28d9c682e\" rel=\"nofollow noreferrer\">this one</a>.</p>\n" }, { "answer_id": 317812, "author": "Arthur", "author_id": 152992, "author_profile": "https://wordpress.stackexchange.com/users/152992", "pm_score": 0, "selected": false, "text": "<p>@dboris @Friss Thank you a lot for your answer and the time you spent for me.</p>\n\n<p>@dboris, you resolved my problem. The var_dump on the $_Post was a good idea. I found the concerned field with that method.</p>\n\n<p>Result of var_dump( $_Post ) :</p>\n\n<p><code>array(34) { [\"sexe\"]=&gt; string(5) \"Homme\" [\"user_login-115\"]=&gt; string(7) \"TestTwo\" [\"last_name-115\"]=&gt; string(7) \"TestTwo\" [\"first_name-115\"]=&gt; string(7) \"TestTwo\" [\"nationalite-115\"]=&gt; string(7) \"TestTwo\" [\"jour_naissance-115\"]=&gt; string(2) \"12\" [\"mois_naissance\"]=&gt; string(4) \"Juin\" [\"annee_naissance-115\"]=&gt; string(4) \"1993\" [\"travailler-entreprise-proprete\"]=&gt; string(24) \"Oui, je suis intéressé\" [\"annees_experience\"]=&gt; string(13) \"De 0 à 5 ans\" [\"adresse-115\"]=&gt; string(11) \"1 rue de la\" [\"code_postal-115\"]=&gt; string(5) \"69001\" [\"ville-115\"]=&gt; string(6) \"Lyon 1\" [\"user_email-115\"]=&gt; string(10) \"[email protected]\" [\"email_contact-115\"]=&gt; string(10) \"[email protected]\" [\"phone_number-115\"]=&gt; string(10) \"0627361762\" [\"permis_conduire\"]=&gt; string(3) \"Oui\" [\"vehicule\"]=&gt; string(3) \"Oui\" [\"type_emploi\"]=&gt; string(32) \"Gardien de résidence étudiante\" [\"date_inscription-115\"]=&gt; string(10) \"28/10/2018\" [\"situation-couple\"]=&gt; string(12) \"Célibataire\" [\"enfants-charge-115\"]=&gt; string(0) \"\" [\"animaux\"]=&gt; string(3) \"Oui\" [\"situation_actuelle\"]=&gt; string(0) \"\" [\"experiences_dans_profession\"]=&gt; string(0) \"\" [\"parcours_et_formation\"]=&gt; string(0) \"\" [\"user_password-115\"]=&gt; string(10) \"Ar12041997\" [\"confirm_user_password-115\"]=&gt; string(10) \"Ar12041997\" [\"fichier_cv-115\"]=&gt; string(0) \"\" [\"form_id\"]=&gt; string(3) \"115\" [\"timestamp\"]=&gt; string(10) \"1540740815\" [\"request\"]=&gt; string(0) \"\" [\"_wpnonce\"]=&gt; string(10) \"524409c715\" [\"_wp_http_referer\"]=&gt; string(37) \"/gardienrecrute/inscription-candidat/\" }</code></p>\n\n<p>You saved my life !</p>\n" } ]
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( '[email protected]', '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( '[email protected]', '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 hook your email sending after the user registration like this</p>\n\n<pre><code>global $uID; //to keep the value to reuse it later, null at this step\n\nfunction mailInscriptionSecteurRhone() {\nglobal $uID;\n$user_ID = $uID;\n $headers = array('Content-Type: text/html; charset=UTF-8');\n $candidat = get_userdata( $user_ID );\n $codePostalCandidat = get_field('code_postal', 'user_' . $user_ID );\n wp_mail( '[email protected]', 'Test', $codePostalCandidat, $headers );\n}\n\nfunction trigger_mailInscriptionSecteurRhone($user_ID)\n{\nglobal $uID;\n$uID = $user_ID;\n add_action( 'init', 'mailInscriptionSecteurRhone', 10 );\n}\nadd_action( 'user_register', 'trigger_mailInscriptionSecteurRhone', 10,1 );\n</code></pre>\n\n<p>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.\nI did not test this solution, it is a suggestion.</p>\n\n<p><strong>End edit</strong></p>\n\n<p>Ok maybe the user_register hook is triggered before acf is loaded (acc to your screenshot, you use acf)</p>\n\n<p>So, have you tried get_user_meta like this ?</p>\n\n<pre><code>$codePostalCandidat = get_user_meta($user_ID,'code_postal',true);\n</code></pre>\n" }, { "answer_id": 317628, "author": "djboris", "author_id": 152412, "author_profile": "https://wordpress.stackexchange.com/users/152412", "pm_score": 0, "selected": false, "text": "<p>I believe this action is triggered before the user meta has been saved. Try using <code>$_POST</code> variable to access the information you need, like this: <code>$first_name = $_POST['first_name'];</code> For the ACF custom fields, they are in array in <code>$_POST['acf']</code>, but indexed with their keys. You can find the key of the field by enabling it in the Field Group view in the Dashboard:</p>\n\n<p><a href=\"https://i.stack.imgur.com/RsI1H.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RsI1H.png\" alt=\"enter image description here\"></a></p>\n\n<p>And then call it like this: <code>$_POST['acf']['field_5bd2cb1f779bf']</code></p>\n\n<p>There is currently no easy way to get this key value dynamically, except to use some custom function like <a href=\"https://gist.github.com/mcguffin/81509c36a4a28d9c682e\" rel=\"nofollow noreferrer\">this one</a>.</p>\n" }, { "answer_id": 317812, "author": "Arthur", "author_id": 152992, "author_profile": "https://wordpress.stackexchange.com/users/152992", "pm_score": 0, "selected": false, "text": "<p>@dboris @Friss Thank you a lot for your answer and the time you spent for me.</p>\n\n<p>@dboris, you resolved my problem. The var_dump on the $_Post was a good idea. I found the concerned field with that method.</p>\n\n<p>Result of var_dump( $_Post ) :</p>\n\n<p><code>array(34) { [\"sexe\"]=&gt; string(5) \"Homme\" [\"user_login-115\"]=&gt; string(7) \"TestTwo\" [\"last_name-115\"]=&gt; string(7) \"TestTwo\" [\"first_name-115\"]=&gt; string(7) \"TestTwo\" [\"nationalite-115\"]=&gt; string(7) \"TestTwo\" [\"jour_naissance-115\"]=&gt; string(2) \"12\" [\"mois_naissance\"]=&gt; string(4) \"Juin\" [\"annee_naissance-115\"]=&gt; string(4) \"1993\" [\"travailler-entreprise-proprete\"]=&gt; string(24) \"Oui, je suis intéressé\" [\"annees_experience\"]=&gt; string(13) \"De 0 à 5 ans\" [\"adresse-115\"]=&gt; string(11) \"1 rue de la\" [\"code_postal-115\"]=&gt; string(5) \"69001\" [\"ville-115\"]=&gt; string(6) \"Lyon 1\" [\"user_email-115\"]=&gt; string(10) \"[email protected]\" [\"email_contact-115\"]=&gt; string(10) \"[email protected]\" [\"phone_number-115\"]=&gt; string(10) \"0627361762\" [\"permis_conduire\"]=&gt; string(3) \"Oui\" [\"vehicule\"]=&gt; string(3) \"Oui\" [\"type_emploi\"]=&gt; string(32) \"Gardien de résidence étudiante\" [\"date_inscription-115\"]=&gt; string(10) \"28/10/2018\" [\"situation-couple\"]=&gt; string(12) \"Célibataire\" [\"enfants-charge-115\"]=&gt; string(0) \"\" [\"animaux\"]=&gt; string(3) \"Oui\" [\"situation_actuelle\"]=&gt; string(0) \"\" [\"experiences_dans_profession\"]=&gt; string(0) \"\" [\"parcours_et_formation\"]=&gt; string(0) \"\" [\"user_password-115\"]=&gt; string(10) \"Ar12041997\" [\"confirm_user_password-115\"]=&gt; string(10) \"Ar12041997\" [\"fichier_cv-115\"]=&gt; string(0) \"\" [\"form_id\"]=&gt; string(3) \"115\" [\"timestamp\"]=&gt; string(10) \"1540740815\" [\"request\"]=&gt; string(0) \"\" [\"_wpnonce\"]=&gt; string(10) \"524409c715\" [\"_wp_http_referer\"]=&gt; string(37) \"/gardienrecrute/inscription-candidat/\" }</code></p>\n\n<p>You saved my life !</p>\n" } ]
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( '[email protected]', '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 the category. \nDo you have posts in the Dogs category?</p>\n" }, { "answer_id": 317755, "author": "JHoffmann", "author_id": 63847, "author_profile": "https://wordpress.stackexchange.com/users/63847", "pm_score": 0, "selected": false, "text": "<p>For special behavior for a category, you can add a template file for the specific category. Such files are called <a href=\"https://developer.wordpress.org/themes/template-files-section/taxonomy-templates/\" rel=\"nofollow noreferrer\">Taxonomy Templates</a>. Creating the file ´category-dogs.php´ in your theme's directory will make wordpress load this file when the category with the slug ´dogs´ is requestd. As model for the new file you can copy the original ´category.php´ in your theme or just redirect the user to another existing page.</p>\n" }, { "answer_id": 317799, "author": "JHoffmann", "author_id": 63847, "author_profile": "https://wordpress.stackexchange.com/users/63847", "pm_score": 2, "selected": true, "text": "<p>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.</p>\n\n<p>Using the filter <code>term_link</code> in the function <a href=\"https://developer.wordpress.org/reference/functions/get_term_link/\" rel=\"nofollow noreferrer\"><code>get_term_link()</code></a> you can change the link which is generated for a specific category.</p>\n\n<pre><code>function wpse_317747_filter_term_link( $termlink, $term, $taxonomy ) {\n if ( \"category\" !== $taxonomy || \"dogs\" !== $term-&gt;slug ) {\n return $termlink;\n }\n return get_permalink( $target_page_id );\n}\nadd_filter( \"term_link\", \"wpse_317747_filter_term_link\", 10, 3 );\n</code></pre>\n\n<p>This changes the generated link if working on <code>category</code> taxonomy and the current term slug is <code>dogs</code>. Just set <code>$target_page_id</code> to correspond to the page you want the link to point to.</p>\n" } ]
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>http://example.com/wp-json/wp/v2/posts?slug=table\n</code></pre>\n<p>Reference document URL are: <a href=\"https://developer.wordpress.org/rest-api/reference/pages/#arguments\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/rest-api/reference/pages/#arguments</a></p>\n" }, { "answer_id": 395773, "author": "Sean Michaud", "author_id": 43348, "author_profile": "https://wordpress.stackexchange.com/users/43348", "pm_score": 2, "selected": false, "text": "<p>Of course it's possible! You'll just need to add in a custom endpoint for the REST API.</p>\n<p>To do that, drop the code below into your functions.php (or better yet, a plugin so it's not tied to your theme).</p>\n<p>First, register the custom route and allow it to take a &quot;title&quot; parameter.</p>\n<pre><code>/**\n * Register the custom route\n *\n */\nfunction custom_register_your_post_route() {\n register_rest_route( 'custom-search/v1', '/posts/(?P&lt;title&gt;.+)', array(\n array(\n 'methods' =&gt; WP_REST_Server::READABLE,\n 'callback' =&gt; 'custom_get_post_sample'\n )\n ) );\n} \nadd_action( 'rest_api_init', 'custom_register_your_post_route' );\n</code></pre>\n<p>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.</p>\n<pre><code>/**\n * Grab all posts with a specific title\n *\n * @param WP_REST_Request $request Current request\n */\nfunction custom_get_post_sample( $request ) {\n global $wpdb;\n\n // params\n $post_title = $request-&gt;get_param( 'title' );\n $post_type = 'post';\n\n // get all of the post ids with a title that matches our parameter\n $id_results = $wpdb-&gt;get_results( $wpdb-&gt;prepare( &quot;SELECT ID FROM $wpdb-&gt;posts WHERE post_title = %s AND post_type= %s&quot;, urldecode( $post_title ), $post_type ) );\n if ( empty( $id_results ) ) {\n return rest_ensure_response( $request );\n }\n \n // format the ids into an array\n $post_ids = [];\n foreach( $id_results as $id ) {\n $post_ids[] = $id-&gt;ID;\n }\n\n // grab all of the post objects\n $args = array(\n 'post_type' =&gt; $post_type,\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; -1,\n 'post__in' =&gt; $post_ids\n );\n $posts = get_posts( $args );\n \n // prepare the API response\n $data = array(); \n $rest_posts_controller = new WP_REST_Posts_Controller( $post_type );\n foreach ( $posts as $post ) { \n $response = $rest_posts_controller-&gt;prepare_item_for_response( $post, $request );\n $data[] = $rest_posts_controller-&gt;prepare_response_for_collection( $response );\n }\n \n // Return all of our post response data\n return rest_ensure_response( $data );\n}\n</code></pre>\n<p>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).</p>\n<p>There's plenty of additional documentation under the <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/\" rel=\"nofollow noreferrer\">Extending the REST API</a> section at wordpress.org if you need more functionality.</p>\n<p>Hope this helps!</p>\n" }, { "answer_id": 405812, "author": "Amin Ghazi", "author_id": 159860, "author_profile": "https://wordpress.stackexchange.com/users/159860", "pm_score": 0, "selected": false, "text": "<p>You cannot do this through wp json, please copy the following code in the functions.php:</p>\n<pre><code>function __search_by_title_only( $search, &amp;$wp_query ) {\n global $wpdb;\n\n if ( empty( $search ) )\n return $search; // skip processing - no search term in query\n\n $q = $wp_query-&gt;query_vars; \n $n = ! empty( $q['exact'] ) ? '' : '%';\n\n $search =\n $searchand = '';\n\n foreach ( (array) $q['search_terms'] as $term ) {\n $term = esc_sql( like_escape( $term ) );\n $search .= &quot;{$searchand}($wpdb-&gt;posts.post_title LIKE '{$n}{$term}{$n}')&quot;;\n $searchand = ' AND ';\n }\n\n if ( ! empty( $search ) ) {\n $search = &quot; AND ({$search}) &quot;;\n if ( ! is_user_logged_in() )\n $search .= &quot; AND ($wpdb-&gt;posts.post_password = '') &quot;;\n }\n\n return $search;\n}\nadd_filter( 'posts_search', '__search_by_title_only', 500, 2 );\n</code></pre>\n" }, { "answer_id": 405845, "author": "crisam de gracia", "author_id": 222296, "author_profile": "https://wordpress.stackexchange.com/users/222296", "pm_score": 0, "selected": false, "text": "<pre><code>function my_website_datas(){\n wp_enqueue_style(YOUR CSS link -- you must know this)\n wp_enqueue_script('my-theme-js', get_theme_file_uri('/js/scripts-bundled.js'), NULL, 'v1' , TRUE );\n wp_localize_script('my-theme-js', 'websiteData', array(\n 'root_url' =&gt; get_site_url(),\n 'nonce' =&gt; wp_create_nonce('wp_rest') \n \n ))\n }\n add_action('wp_enqueue_scripts','my_website_datas');\n</code></pre>\n<p>create new API route</p>\n<pre><code> add_action('rest_api_init', 'my_new_search_api');\n function my_new_search_api(){\n\n //3 args - the 1st and 2nd is the API route you will hook\n // like search_route/v1/search?term= in your getJson\n register_rest_route('search_route/v1','search', array(\n 'methods' =&gt; WP_REST_SERVER::READABLE,\n 'callback' =&gt; 'customSearchResults' // this is your below function\n\n ));\n }\n</code></pre>\n<p>Create the callback function</p>\n<pre><code> function customSearchResults( $data ) {\n\n /* Create you new Query */\n $mainQuery = new WP_Query( array(\n 'post_type' =&gt; array('post','page','post_type1'),\n 's' =&gt; sanitize_text_field( $data['term']) // v1/search?term \n ));\n\n // create your array to append if the user attempt to search for kind of taxonomy\n $results = array( \n 'generalInfo' =&gt; array(),\n 'post_type1' =&gt; array()\n );\n\n while($mainQuery-&gt;have_posts()){\n $mainQuery-&gt;the_post();\n\n //here when the taxonomy matches it will append the data the in array above\n if( get_post_type() == 'posts' OR get_post_type() == 'page'){\n array_push($results['generalInfo'], array(\n 'title' =&gt; get_the_title(),\n 'permalink' =&gt; get_the_permalink(),\n 'postType' =&gt; get_post_type(),\n 'authorName' =&gt; get_the_author()\n ));\n \n } \n \n if( get_post_type() == 'post_type1'){\n \n array_push($results['post_type1'], array(\n 'title' =&gt; get_the_title(),\n 'permalink' =&gt; get_the_permalink(),\n 'postType' =&gt; get_post_type(),\n 'authorName' =&gt; get_the_author()\n ));\n \n } \n \n return $results;\n }\n}\n\n \n \n</code></pre>\n<p>Next in your JS file\nThe code is too long you must guess this this.searchField.val() part haha</p>\n<pre><code> $.getJSON(websiteData.root_url + '/wp-json/university/v1/search?term=' + \n this.searchField.val(), (results) =&gt; {\n \n // now you can append the result to wherever element you want. \n this.resultsDiv.html(`\n &lt;p&gt; ${results} &lt;/p&gt; `)\n\n }\n \n</code></pre>\n<p>This code will work if you know what you are doing.\nHope this helps!</p>\n" } ]
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 in any decently made theme. At the moment you can only rely on <code>wp_head</code> and <code>wp_footer</code>. A hook right after the <code>&lt;body&gt;</code> tag <a href=\"https://core.trac.wordpress.org/ticket/12563\" rel=\"nofollow noreferrer\">is under discussion</a>, 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.</p>\n\n<p>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.</p>\n\n<p>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).</p>\n\n<p>Hooking into <code>wp_head</code> add a jquery script file that adds a DOM-element right after the <code>&lt;body&gt;</code> tag and <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/\" rel=\"nofollow noreferrer\">use the rest api</a> to call the function that you would normally generate the code that you want in that place.</p>\n" }, { "answer_id": 317892, "author": "djboris", "author_id": 152412, "author_profile": "https://wordpress.stackexchange.com/users/152412", "pm_score": 1, "selected": false, "text": "<p>I am afraid this is not possible at the moment. This is completely on the Theme territory, and you would always depend on the Theme code. </p>\n\n<p><strong>BUT!!</strong> There is a simple hack you can use, for a not complicated code insertion. I say it is a hack, and you will see why.</p>\n\n<p>The only thing you can count on that will exist in 99.99% of the Themes is <code>&lt;body &lt;?php body_class(); ?&gt;&gt;</code>. So we can use a filter hook to add another 'class' to the body tag, except... it won't be a class. Look at this code:</p>\n\n<pre><code>add_filter( 'body_class', function ( $classes ) {\n return array_merge( \n $classes, \n array( '\"&gt;\n &lt;iframe src=\"//www.googletagmanager.com/ns.html?id=XXX-XXXXXX\" height=\"0\" width=\"0\" style=\"display:none;visibility:hidden\"&gt;&lt;/iframe&gt;\n &lt;input type=\"hidden' // Important to handle the closing of the body element\n ) \n );\n} );\n</code></pre>\n\n<p>What have we done here? We have first added <code>\"&gt;</code> to close the <code>body</code> element. Then you can insert whatever HTML you want. The last part is also mandatory, to handle the actual closing of the <code>body</code> element, we need to create something that won't break our template, so a hidden input field should work well. We add <code>&lt;input type=\"hidden</code>, but without closing with <code>\"&gt;</code> because the <code>body_class()</code> function will do it for us.</p>\n\n<p>Note that there is a possibility this would collide with some other filters on <code>body_class</code>, depending on the priority. To handle this, you could wrap this into another action hook that will fire after the theme is loaded, for instance <code>get_header</code>. In that case, the full code would be:</p>\n\n<pre><code>add_action( 'get_header', function() {\n add_filter( 'body_class', function ( $classes ) {\n return array_merge(\n $classes,\n array( '\"&gt;\n &lt;iframe src=\"//www.googletagmanager.com/ns.html?id=XXX-XXXXXX\" height=\"0\" width=\"0\" style=\"display:none;visibility:hidden\"&gt;&lt;/iframe&gt;\n &lt;input type=\"hidden' // Important to handle the closing of the body element\n ) );\n } );\n});\n</code></pre>\n\n<p>Even though this possibly does what you want, I can't really recommend this.</p>\n" }, { "answer_id": 382380, "author": "Chris Hayes", "author_id": 163768, "author_profile": "https://wordpress.stackexchange.com/users/163768", "pm_score": 2, "selected": false, "text": "<h2>As of WordPress 5.2 (May 2019) this is officially supported</h2>\n<p><strong>Compatibility:</strong>\nWordPress 5.2+ usage as of Jan 2021 is at 76% <a href=\"https://wordpress.org/about/stats/\" rel=\"nofollow noreferrer\">according to WordPress Stats</a>.</p>\n<p><strong>How to use:</strong>\nComprehensive WordPress blog post explaining <code>wp_body_open</code> functionality at <a href=\"https://make.wordpress.org/core/2019/04/24/miscellaneous-developer-updates-in-5-2/\" rel=\"nofollow noreferrer\">https://make.wordpress.org/core/2019/04/24/miscellaneous-developer-updates-in-5-2/</a></p>\n<h3>TL;DR</h3>\n<p><strong>Snippet Usage</strong></p>\n<pre><code>&lt;?php add_action( 'wp_body_open', function () { ?&gt;\n\n&lt;!-- Your HTML code here --&gt;\n\n&lt;?php } ); ?&gt;\n</code></pre>\n<p><strong>Theme Usage</strong></p>\n<pre><code>&lt;body &lt;?php body_class(); ?&gt;&gt;\n&lt;?php wp_body_open(); ?&gt;\n</code></pre>\n<p><strong>Theme Usage with Backwards-Compatibility</strong></p>\n<pre><code>&lt;body &lt;?php body_class(); ?&gt;&gt;\n&lt;?php \nif ( function_exists( 'wp_body_open' ) ) {\n wp_body_open();\n} else {\n do_action( 'wp_body_open' );\n}\n</code></pre>\n" } ]
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 command line through Terminal via SSH. If that assumption is in error, forgive me.)</p>\n\n<p>In a typical Wordpress install there are likely three users, similar to:</p>\n\n<pre><code>root:root \nwww-data:www-data (Apache)\nuser:user sudo lxd (WHERE \"user\" is some name given for SSH access)\n</code></pre>\n\n<p>*Those users can be found by using the command: ps aux | grep apache</p>\n\n<p>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).</p>\n\n<p>(All my commands are done as sudo user, because I'm SSH-ing in Terminal as my user) Here are some options.</p>\n\n<p>If you want to generically make Apache owner and set permissions on directories and files:</p>\n\n<pre><code>sudo chown www-data:www-data -R * \nsudo . -type d -exec chmod 755 {} \\; \nsudo . -type f -exec chmod 644 {} \\; \n</code></pre>\n\n<p>If you want to specifically make Apache owner on a directory, and set permissions:</p>\n\n<pre><code>sudo chown www-data:www-data -R /var/www/html/wp-content/\nsudo find /var/www/html/wp-content/ -type d -exec chmod 755 {} \\;\nsudo find /var/www/html/wp-content/ -type f -exec chmod 644 {} \\;\n</code></pre>\n\n<p>But if you set permissions on everything in the install directory to 777, you're going to want to fix that with something like:</p>\n\n<pre><code>sudo find /var/www/html/ -type d -exec -R chmod 755 {} \\;\nsudo find /var/www/html/ -type f -exec -R chmod 644 {} \\;\n</code></pre>\n\n<p>Then make sure wp-config is hardened with 660 or even 600 permissions.</p>\n\n<pre><code>cd html\nsudo chmod 660 wp-config.php\n</code></pre>\n" }, { "answer_id": 331282, "author": "Daniel", "author_id": 109760, "author_profile": "https://wordpress.stackexchange.com/users/109760", "pm_score": 0, "selected": false, "text": "<blockquote>\n<p>First of all i set all permissions for installation folder with chmod\n-R 777 .</p>\n</blockquote>\n<p>Mistakes happen, don't ever do the above again.</p>\n<p>Please carefully follow my instructions. From within an Ubuntu VPS and you are at:</p>\n<p><code>/var/www/mysite.com/public_html</code>, run the following commands:</p>\n<p><code>sudo chown -R yourName:www-data /var/www/mysite.com/</code></p>\n<p>Next, run:</p>\n<p><code>sudo find /var/www/mysite.com/ -type d -exec chmod 775 {} \\;</code></p>\n<p>That will give your directories the appropriate permissions and then do the same for your files like so:</p>\n<p><code>sudo find /var/www/mysite.com/ -type f -exec chmod 664 {} \\;</code></p>\n<p>Once you have executed these commands you are golden, you have now hardened your WordPress site in accordance with the Principles of Least Privilege, but don't take my word for it, learn more here:\n<a href=\"https://wordpress.org/support/article/hardening-wordpress\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/hardening-wordpress</a></p>\n" } ]
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 custom CSS to your theme.</p>\n" }, { "answer_id": 317958, "author": "Aculine", "author_id": 150879, "author_profile": "https://wordpress.stackexchange.com/users/150879", "pm_score": 1, "selected": false, "text": "<p>SOLVED:<br>\nas @milo suggests, I found solution disabling mod_security under cPanel. So I ask to my hoster (register.it) if there was some problem. They confirm me that servers are under updating security stuff and to disable and then re-able mod_security in CPanel. After that, post.php works properly.</p>\n\n<p>Thank you all.</p>\n" }, { "answer_id": 318025, "author": "Francesco Colombo", "author_id": 153289, "author_profile": "https://wordpress.stackexchange.com/users/153289", "pm_score": 2, "selected": true, "text": "<p>I've had the same issue recently. </p>\n\n<p>Inline styles, as well as <code>&lt;img&gt;</code> tags, would cause the <code>410 Gone</code> status and error message (<code>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> upon previewing or publishing the post.</p>\n\n<p>The problem was due to the hosting provider doing some maintenance on <code>mod_security</code> in cPanel.</p>\n\n<p>I found out when I asked them for the Apache logs so that I could look into it more.</p>\n\n<p>Contact your hosting provider to get this fixed.</p>\n" } ]
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 custom CSS to your theme.</p>\n" }, { "answer_id": 317958, "author": "Aculine", "author_id": 150879, "author_profile": "https://wordpress.stackexchange.com/users/150879", "pm_score": 1, "selected": false, "text": "<p>SOLVED:<br>\nas @milo suggests, I found solution disabling mod_security under cPanel. So I ask to my hoster (register.it) if there was some problem. They confirm me that servers are under updating security stuff and to disable and then re-able mod_security in CPanel. After that, post.php works properly.</p>\n\n<p>Thank you all.</p>\n" }, { "answer_id": 318025, "author": "Francesco Colombo", "author_id": 153289, "author_profile": "https://wordpress.stackexchange.com/users/153289", "pm_score": 2, "selected": true, "text": "<p>I've had the same issue recently. </p>\n\n<p>Inline styles, as well as <code>&lt;img&gt;</code> tags, would cause the <code>410 Gone</code> status and error message (<code>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> upon previewing or publishing the post.</p>\n\n<p>The problem was due to the hosting provider doing some maintenance on <code>mod_security</code> in cPanel.</p>\n\n<p>I found out when I asked them for the Apache logs so that I could look into it more.</p>\n\n<p>Contact your hosting provider to get this fixed.</p>\n" } ]
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.