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
245,405
<p>I have a post meta for image uploads which allows a maximum of 5 files.</p> <p>The data is stored in like this:</p> <pre><code>a:5:{i:0;s:3:"694";i:1;s:3:"694";i:2;s:3:"697";i:3;s:3:"695";i:4;s:3:"696";} </code></pre> <p>The problem is, I can't get the image URLs. My code:</p> <pre><code> &lt;?php $ppics = get_post_meta( get_the_ID(), 'shop_demosc', false ); $ppurl = wp_get_attachment_url($ppics); foreach ($ppics as $key =&gt; $ppurl){ echo '&lt;img src="'. print_r($ppurl) .'"&gt;'; } ?&gt; </code></pre> <p>This code returns:</p> <pre><code>Array ( [0] =&gt; 694 [1] =&gt; 694 [2] =&gt; 697 [3] =&gt; 695 [4] =&gt; 696 ) </code></pre> <p>whats wrong? How can I get the URLs to the 5 images?</p>
[ { "answer_id": 245408, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 1, "selected": false, "text": "<p>You need to move </p>\n\n<pre><code> $ppurl = wp_get_attachment_url($value); // $value of the foreach\n</code></pre>\n\n<p>In the foreach loop</p>\n\n<p>so your code might look like this</p>\n\n<pre><code> &lt;?php $ppics = get_post_meta( get_the_ID(), 'shop_demosc', true);// true to get the unserialize array directly\n\n foreach ($ppics as $key =&gt; $attachment_id){\n $ppurl = wp_get_attachment_url(attachment_id);\n echo '&lt;img src=\"'. $ppurl .'\"&gt;';\n } ?&gt;\n</code></pre>\n" }, { "answer_id": 245473, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": true, "text": "<p>Your <code>var_dump</code> looks like it's returning an array because you're passing <code>false</code> to <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\"><code>get_post_meta()</code></a>. Also you don't want to <code>print_r()</code> on an <code>echo</code> line.</p>\n\n<blockquote>\n <p>Retrieve post meta field for a post.</p>\n \n <ul>\n <li><strong>$post_id</strong> <em>(int) (Required)</em> Post ID.</li>\n <li><strong>$key</strong> <em>(string) (Optional)</em> The meta key to retrieve. By default, returns data for all keys. Default value: ''</li>\n <li><strong>$single</strong> <em>(bool) (Optional)</em> Whether to return a single value. Default value: false</li>\n </ul>\n</blockquote>\n\n<pre><code>&lt;?php \n\n$ppics = get_post_meta( get_the_ID(), 'shop_demosc', true );\n\n// if the value is an array of an array, just set to the first array\nif( is_array($ppics) &amp;&amp; count($ppics) === 1 &amp;&amp; is_array($ppics[0]) ){\n $ppics = $ppics[0];\n}\n\nforeach ( $ppics as $key =&gt; $attachment_id ) {\n $image_url = wp_get_attachment_url( $attachment_id );\n printf( '&lt;img src=\"%s\"&gt;', $image_url );\n} \n\n?&gt; \n</code></pre>\n" } ]
2016/11/07
[ "https://wordpress.stackexchange.com/questions/245405", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77768/" ]
I have a post meta for image uploads which allows a maximum of 5 files. The data is stored in like this: ``` a:5:{i:0;s:3:"694";i:1;s:3:"694";i:2;s:3:"697";i:3;s:3:"695";i:4;s:3:"696";} ``` The problem is, I can't get the image URLs. My code: ``` <?php $ppics = get_post_meta( get_the_ID(), 'shop_demosc', false ); $ppurl = wp_get_attachment_url($ppics); foreach ($ppics as $key => $ppurl){ echo '<img src="'. print_r($ppurl) .'">'; } ?> ``` This code returns: ``` Array ( [0] => 694 [1] => 694 [2] => 697 [3] => 695 [4] => 696 ) ``` whats wrong? How can I get the URLs to the 5 images?
Your `var_dump` looks like it's returning an array because you're passing `false` to [`get_post_meta()`](https://developer.wordpress.org/reference/functions/get_post_meta/). Also you don't want to `print_r()` on an `echo` line. > > Retrieve post meta field for a post. > > > * **$post\_id** *(int) (Required)* Post ID. > * **$key** *(string) (Optional)* The meta key to retrieve. By default, returns data for all keys. Default value: '' > * **$single** *(bool) (Optional)* Whether to return a single value. Default value: false > > > ``` <?php $ppics = get_post_meta( get_the_ID(), 'shop_demosc', true ); // if the value is an array of an array, just set to the first array if( is_array($ppics) && count($ppics) === 1 && is_array($ppics[0]) ){ $ppics = $ppics[0]; } foreach ( $ppics as $key => $attachment_id ) { $image_url = wp_get_attachment_url( $attachment_id ); printf( '<img src="%s">', $image_url ); } ?> ```
245,415
<p>Does anyone know what is considered the best way to install Wordpress. Manually or perhaps is using something like Softaculous or QuickInstall the better approach?</p>
[ { "answer_id": 245416, "author": "montrealist", "author_id": 8105, "author_profile": "https://wordpress.stackexchange.com/users/8105", "pm_score": 0, "selected": false, "text": "<p>If you have access to the server and enough permissions to install/run things on it, I'd recommend installing WordPress with the <a href=\"https://getcomposer.org/\" rel=\"nofollow noreferrer\">Composer package manager</a>. Then updating WordPress to a newer version or rolling it back for bug-fixing is a breeze (log in to the server, edit one file, run one command), plus you'll only need one file to keep track of in source control (composer.json).</p>\n\n<p>Another added benefit is that many free themes and plugins can be maintained with it as well, they're all listed on <a href=\"https://wpackagist.org/\" rel=\"nofollow noreferrer\">WordPress Packagist</a>.</p>\n\n<p><a href=\"https://roots.io/using-composer-with-wordpress/\" rel=\"nofollow noreferrer\">Here's a good article</a> walking through the steps necessary for this to happen. I should say it's not trivial to do that with an existing install; in that case, lots of care should be taken to avoid downtime.</p>\n" }, { "answer_id": 245427, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p>Use <a href=\"https://wp-cli.org/\" rel=\"nofollow noreferrer\">WP-CLI's</a> - <code>wp core install</code> - Runs the standard WordPress installation process.</p>\n\n<blockquote>\n <p>Creates the WordPress tables in the database using the URL, title, and default admin user details provided. Performs the famous 5 minute install in seconds or less.</p>\n</blockquote>\n\n<pre><code>$ wp core install --url=example.com --title=Example --admin_user=supervisor --admin_password=strongpassword [email protected]\nSuccess: WordPress installed successfully.\n</code></pre>\n" } ]
2016/11/08
[ "https://wordpress.stackexchange.com/questions/245415", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91629/" ]
Does anyone know what is considered the best way to install Wordpress. Manually or perhaps is using something like Softaculous or QuickInstall the better approach?
Use [WP-CLI's](https://wp-cli.org/) - `wp core install` - Runs the standard WordPress installation process. > > Creates the WordPress tables in the database using the URL, title, and default admin user details provided. Performs the famous 5 minute install in seconds or less. > > > ``` $ wp core install --url=example.com --title=Example --admin_user=supervisor --admin_password=strongpassword [email protected] Success: WordPress installed successfully. ```
245,445
<p>I'm trying to create add-ones of WC-Vendors where I have to create custom post type for Vendor user Only.</p> <p>Here is code snippet I used</p> <pre><code> register_post_type( 'acme_product', array( 'labels' =&gt; array( 'name' =&gt; __( 'Products' ), 'singular_name' =&gt; __( 'Product' ) ), 'public' =&gt; true, 'has_archive' =&gt; true, ) ); </code></pre> <p><strong>above code works well with admin user.</strong></p>
[ { "answer_id": 245453, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 0, "selected": false, "text": "<p>You need to add the <strong>capability</strong> and/or <strong>map_meta_cap</strong> to the argument array of the <code>register_post_type()</code></p>\n\n<p>The codex says : additional capabilities are only used in map_meta_cap(). Thus, they are only assigned by default if the post type is registered with the 'map_meta_cap' argument set to true (default is false).</p>\n\n<p>here is the add_role for the vendor</p>\n\n<pre><code>add_role( 'vendor', __('Vendor', 'wcvendors') , array(\n 'assign_product_terms' =&gt; true,\n 'edit_products' =&gt; true,\n 'edit_product' =&gt; true,\n 'edit_published_products' =&gt; false,\n 'manage_product' =&gt; true,\n 'publish_products' =&gt; false,\n 'read' =&gt; true,\n 'upload_files' =&gt; true,\n 'view_woocommerce_reports' =&gt; true,\n ) \n);\n</code></pre>\n\n<p>You will get all details on the codex page <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\">Here</a></p>\n" }, { "answer_id": 245549, "author": "Syed Fakhar Abbas", "author_id": 90591, "author_profile": "https://wordpress.stackexchange.com/users/90591", "pm_score": 1, "selected": false, "text": "<p>First you have to passed two additional arguments into the register_post_type() function.</p>\n\n<ol>\n<li>capability_type</li>\n<li>map_meta_cap</li>\n</ol>\n\n<p>Then, You can add capability using <a href=\"https://codex.wordpress.org/Function_Reference/add_cap\" rel=\"nofollow noreferrer\">add_cap();</a> function.</p>\n\n<pre><code>\nregister_post_type( 'acme_product',\n array(\n 'labels' => array(\n 'name' => __( 'Products' ),\n 'singular_name' => __( 'Product' )\n ),\n 'public' => true,\n 'has_archive' => true,\n 'capability_type' => array('acme_product','acme_products'),\n 'map_meta_cap' => true,\n )\n );\n\n add_action('admin_init','vendor_role_caps');\n\n function vendor_role_caps() {\n\n $role = get_role('vendor_user');\n $role->add_cap( 'read' );\n $role->add_cap( 'read_acme_product');\n $role->add_cap( 'read_private_acme_products' );\n $role->add_cap( 'edit_acme_product' );\n $role->add_cap( 'edit_acme_products' );\n $role->add_cap( 'edit_others_acme_products' );\n $role->add_cap( 'edit_published_acme_products' );\n $role->add_cap( 'publish_acme_products' );\n $role->add_cap( 'delete_others_acme_products' );\n $role->add_cap( 'delete_private_acme_products' );\n $role->add_cap( 'delete_published_acme_products' );\n\n }\n\n</code></pre>\n" } ]
2016/11/08
[ "https://wordpress.stackexchange.com/questions/245445", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/96426/" ]
I'm trying to create add-ones of WC-Vendors where I have to create custom post type for Vendor user Only. Here is code snippet I used ``` register_post_type( 'acme_product', array( 'labels' => array( 'name' => __( 'Products' ), 'singular_name' => __( 'Product' ) ), 'public' => true, 'has_archive' => true, ) ); ``` **above code works well with admin user.**
First you have to passed two additional arguments into the register\_post\_type() function. 1. capability\_type 2. map\_meta\_cap Then, You can add capability using [add\_cap();](https://codex.wordpress.org/Function_Reference/add_cap) function. ``` register_post_type( 'acme_product', array( 'labels' => array( 'name' => __( 'Products' ), 'singular_name' => __( 'Product' ) ), 'public' => true, 'has_archive' => true, 'capability_type' => array('acme_product','acme_products'), 'map_meta_cap' => true, ) ); add_action('admin_init','vendor_role_caps'); function vendor_role_caps() { $role = get_role('vendor_user'); $role->add_cap( 'read' ); $role->add_cap( 'read_acme_product'); $role->add_cap( 'read_private_acme_products' ); $role->add_cap( 'edit_acme_product' ); $role->add_cap( 'edit_acme_products' ); $role->add_cap( 'edit_others_acme_products' ); $role->add_cap( 'edit_published_acme_products' ); $role->add_cap( 'publish_acme_products' ); $role->add_cap( 'delete_others_acme_products' ); $role->add_cap( 'delete_private_acme_products' ); $role->add_cap( 'delete_published_acme_products' ); } ```
245,455
<p>My plugin has several php files that are included on the main plugin file. I am using some functions on the other files but they don't work there. They work when I use them on the main plugin file.</p> <p>For example,</p> <p><strong>On the main plugin file <em>"test-plugin.php"</em></strong></p> <pre><code>&lt;?php /* Plugin Name: Test Plugin Description: test Version: 1.0 */ include_once( plugin_dir_path( __FILE__ ) . 'test-file.php' ); </code></pre> <p><strong>On the other file <em>"test-file.php"</em> (same directory with test-plugin.php)</strong> </p> <pre><code>&lt;?php function enable_user_registration() { if(!get_option('users_can_register')) { update_option( 'users_can_register', '1' ); } } register_activation_hook( plugin_dir_path(__FILE__), 'enable_user_registration' ); </code></pre> <p>Regards..</p>
[ { "answer_id": 245453, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 0, "selected": false, "text": "<p>You need to add the <strong>capability</strong> and/or <strong>map_meta_cap</strong> to the argument array of the <code>register_post_type()</code></p>\n\n<p>The codex says : additional capabilities are only used in map_meta_cap(). Thus, they are only assigned by default if the post type is registered with the 'map_meta_cap' argument set to true (default is false).</p>\n\n<p>here is the add_role for the vendor</p>\n\n<pre><code>add_role( 'vendor', __('Vendor', 'wcvendors') , array(\n 'assign_product_terms' =&gt; true,\n 'edit_products' =&gt; true,\n 'edit_product' =&gt; true,\n 'edit_published_products' =&gt; false,\n 'manage_product' =&gt; true,\n 'publish_products' =&gt; false,\n 'read' =&gt; true,\n 'upload_files' =&gt; true,\n 'view_woocommerce_reports' =&gt; true,\n ) \n);\n</code></pre>\n\n<p>You will get all details on the codex page <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\">Here</a></p>\n" }, { "answer_id": 245549, "author": "Syed Fakhar Abbas", "author_id": 90591, "author_profile": "https://wordpress.stackexchange.com/users/90591", "pm_score": 1, "selected": false, "text": "<p>First you have to passed two additional arguments into the register_post_type() function.</p>\n\n<ol>\n<li>capability_type</li>\n<li>map_meta_cap</li>\n</ol>\n\n<p>Then, You can add capability using <a href=\"https://codex.wordpress.org/Function_Reference/add_cap\" rel=\"nofollow noreferrer\">add_cap();</a> function.</p>\n\n<pre><code>\nregister_post_type( 'acme_product',\n array(\n 'labels' => array(\n 'name' => __( 'Products' ),\n 'singular_name' => __( 'Product' )\n ),\n 'public' => true,\n 'has_archive' => true,\n 'capability_type' => array('acme_product','acme_products'),\n 'map_meta_cap' => true,\n )\n );\n\n add_action('admin_init','vendor_role_caps');\n\n function vendor_role_caps() {\n\n $role = get_role('vendor_user');\n $role->add_cap( 'read' );\n $role->add_cap( 'read_acme_product');\n $role->add_cap( 'read_private_acme_products' );\n $role->add_cap( 'edit_acme_product' );\n $role->add_cap( 'edit_acme_products' );\n $role->add_cap( 'edit_others_acme_products' );\n $role->add_cap( 'edit_published_acme_products' );\n $role->add_cap( 'publish_acme_products' );\n $role->add_cap( 'delete_others_acme_products' );\n $role->add_cap( 'delete_private_acme_products' );\n $role->add_cap( 'delete_published_acme_products' );\n\n }\n\n</code></pre>\n" } ]
2016/11/08
[ "https://wordpress.stackexchange.com/questions/245455", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/42650/" ]
My plugin has several php files that are included on the main plugin file. I am using some functions on the other files but they don't work there. They work when I use them on the main plugin file. For example, **On the main plugin file *"test-plugin.php"*** ``` <?php /* Plugin Name: Test Plugin Description: test Version: 1.0 */ include_once( plugin_dir_path( __FILE__ ) . 'test-file.php' ); ``` **On the other file *"test-file.php"* (same directory with test-plugin.php)** ``` <?php function enable_user_registration() { if(!get_option('users_can_register')) { update_option( 'users_can_register', '1' ); } } register_activation_hook( plugin_dir_path(__FILE__), 'enable_user_registration' ); ``` Regards..
First you have to passed two additional arguments into the register\_post\_type() function. 1. capability\_type 2. map\_meta\_cap Then, You can add capability using [add\_cap();](https://codex.wordpress.org/Function_Reference/add_cap) function. ``` register_post_type( 'acme_product', array( 'labels' => array( 'name' => __( 'Products' ), 'singular_name' => __( 'Product' ) ), 'public' => true, 'has_archive' => true, 'capability_type' => array('acme_product','acme_products'), 'map_meta_cap' => true, ) ); add_action('admin_init','vendor_role_caps'); function vendor_role_caps() { $role = get_role('vendor_user'); $role->add_cap( 'read' ); $role->add_cap( 'read_acme_product'); $role->add_cap( 'read_private_acme_products' ); $role->add_cap( 'edit_acme_product' ); $role->add_cap( 'edit_acme_products' ); $role->add_cap( 'edit_others_acme_products' ); $role->add_cap( 'edit_published_acme_products' ); $role->add_cap( 'publish_acme_products' ); $role->add_cap( 'delete_others_acme_products' ); $role->add_cap( 'delete_private_acme_products' ); $role->add_cap( 'delete_published_acme_products' ); } ```
245,462
<p>My code was checked and seems OK so maybe the problem lies in the <code>htaccess</code> file whose content on my online server is:</p> <pre><code>SetEnv PHP_VER 5_4 Options -Indexes ErrorDocument 404 /index.php RewriteEngine on RewriteCond %{HTTP_HOST} !^www.example.fr$ RewriteRule ^(.*) http://www.example.fr/$1 [QSA,L,R=301] </code></pre> <p>Any reason why this <code>htaccess</code> would prevent forms from submitting correctly on my site?</p> <p>Just in case here's my code:</p> <pre><code>&lt;form id='contact_form_mmt' action='&lt;?php echo bloginfo("wpurl"); ?&gt;/contact' method='post'&gt; &lt;input type='text' name='contact_nom' placeholder='Votre nom *' data-validation='length' data-validation-length='min3' data-validation-error-msg='&lt;?php echo $text_too_short_or_empty; ?&gt;'&gt; &lt;input type='text' name='contact_prenom' placeholder='Votre prénom *' data-validation='length' data-validation-length='min3' data-validation-error-msg='&lt;?php echo $text_too_short_or_empty; ?&gt;'&gt; &lt;input type='text' name='contact_mail' placeholder='Votre mail *' data-validation='email' data-validation-length='min3' data-validation-error-msg='&lt;?php echo $email_valid; ?&gt;'&gt; &lt;select name='contact_destinataire'&gt; &lt;option value="[email protected]|Information générales"&gt;Information générales&lt;/option&gt; &lt;option value="[email protected]|Problèmes liés au site"&gt;Problèmes liés au site&lt;/option&gt; &lt;/select&gt; &lt;textarea name='contact_message' placeholder='Message *'data-validation='length' data-validation-length='min3' data-validation-error-msg='&lt;?php echo $text_too_short_or_empty; ?&gt;'&gt;&lt;/textarea&gt; &lt;input type='hidden' name='sub' value='1'&gt; &lt;input type='submit' value='envoyer'&gt; &lt;/form&gt; </code></pre> <p>PHP (I know the syntax is ugly, I'll improve that):</p> <pre><code>if ( isset($_POST['sub']) ) $sub = $_POST['sub']; else $sub = ''; if ( isset($_POST['contact_nom']) ) $contact_nom = $_POST['contact_nom']; else $contact_nom = ''; if ( isset($_POST['contact_prenom']) ) $contact_prenom = $_POST['contact_prenom' ]; else $contact_prenom = ''; if ( isset($_POST['contact_mail']) ) $contact_mail = $_POST['contact_mail']; else $contact_mail = ''; if ( isset($_POST['contact_sujet']) ) $contact_sujet = $_POST['contact_sujet']; else $contact_sujet = ''; if ( isset($_POST['contact_destinataire']) ) $contact_destinataire = $_POST['contact_destinataire']; else $contact_destinataire = ''; if ( isset($_POST['contact_message']) ) $contact_message = $_POST['contact_message']; else $contact_message = ''; </code></pre>
[ { "answer_id": 245736, "author": "Michelle", "author_id": 16, "author_profile": "https://wordpress.stackexchange.com/users/16", "pm_score": 1, "selected": false, "text": "<p>You may need to use <code>bloginfo('url')</code> aka <a href=\"https://developer.wordpress.org/reference/functions/home_url/\" rel=\"nofollow noreferrer\"><code>home_url()</code></a> (displayed site) instead of <code>bloginfo('wpurl')</code> aka <a href=\"https://developer.wordpress.org/reference/functions/site_url/\" rel=\"nofollow noreferrer\"><code>site_url()</code></a> (wordpress files location) in your action, for instance:</p>\n\n<pre><code>action=\"&lt;?php echo home_url('/contact/'); ?&gt;\"\n</code></pre>\n" }, { "answer_id": 246049, "author": "sMyles", "author_id": 51201, "author_profile": "https://wordpress.stackexchange.com/users/51201", "pm_score": 2, "selected": false, "text": "<p>The problem is with your <code>htaccess</code> in that you are redirecting to another URL, causing the POST data to no longer be available.</p>\n\n<pre><code>RewriteRule ^(.*) http://www.example.fr/$1 [QSA,L,R=301] \n</code></pre>\n\n<p>Should be</p>\n\n<pre><code>RewriteRule ^(.*) /$1 [QSA,L,R]\n</code></pre>\n\n<p>You could also set it to not redirect on a POST as well:</p>\n\n<pre><code>RewriteCond %{REQUEST_METHOD} !POST [NC]\n</code></pre>\n\n<p>OR, use a 307 redirect, which will preserve the POST data\n<a href=\"https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection</a></p>\n\n<hr>\n\n<p>You can also use PHP shorthand IF statements, and recommend using <code>array_key_exists</code> over <code>isset</code> when you're checking an array</p>\n\n<pre><code>$sub = array_key_exists( 'sub', $_POST ) ? $_POST[ 'sub' ] : '';\n$contact_nom = array_key_exists( 'contact_nom', $_POST ) ? $_POST[ 'contact_nom' ] : '';\n$contact_prenom = array_key_exists( 'contact_prenom', $_POST ) ? $_POST[ 'contact_prenom' ] : '';\n$contact_mail = array_key_exists( 'contact_mail', $_POST ) ? $_POST[ 'contact_mail' ] : '';\n$contact_sujet = array_key_exists( 'contact_sujet', $_POST ) ? $_POST[ 'contact_sujet' ] : '';\n$contact_destinataire = array_key_exists( 'contact_destinataire', $_POST ) ? $_POST[ 'contact_destinataire' ] : '';\n$contact_message = array_key_exists( 'contact_message', $_POST ) ? $_POST[ 'contact_message' ] : '';\n</code></pre>\n\n<p><a href=\"https://davidwalsh.name/php-ternary-examples\" rel=\"nofollow noreferrer\">https://davidwalsh.name/php-ternary-examples</a></p>\n\n<p>You should also be sanitizing the data that is coming in from frontend facing forms, to prevent any possible security vulnerabilities.<br>\nWordPress has plenty of these built in that you can use:\n<a href=\"https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data</a></p>\n\n<hr>\n\n<p>And why not just use something like Caldera Forms which will handle all of this for you?\n<a href=\"https://wordpress.org/plugins/caldera-forms/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/caldera-forms/</a></p>\n" }, { "answer_id": 246199, "author": "haz", "author_id": 99009, "author_profile": "https://wordpress.stackexchange.com/users/99009", "pm_score": 3, "selected": true, "text": "<p>The best way to deal with Form Posts in Wordpress is to use a special endpoint, <strong>/wp-admin/admin-post.php</strong>.</p>\n\n<p>POST data can be messed up, both by the WP Query call, and by any redirects that happen.</p>\n\n<p>So you set up your form with this action: </p>\n\n<pre><code>&lt;form action=\"&lt;?= admin_url('admin-post.php') ?&gt;\" method=\"post\"&gt;\n&lt;input type=\"hidden\" name=\"action\" value=\"special_action\"&gt;\n&lt;?php wp_nonce_field('special_action_nonce', 'special_action_nonce'); ?&gt;\n</code></pre>\n\n<p>Then you can handle the form by adding an action to your theme or plugin:</p>\n\n<pre><code>add_action('admin_post_nopriv_special_action', ['My\\Plugins\\FormController', 'specialAction']);\nadd_action('admin_post_special_action', ['My\\Plugins\\FormController', 'specialAction']);\n</code></pre>\n\n<p>Note that Wordpress constructs a special action, based on the <strong>action</strong> value in the form, <strong>admin_post_no_priv_<em>special_action</em></strong> (if you're logged out) and <strong>admin_post_<em>special_action</em></strong> (if you're logged in). You can point these in different locations.</p>\n\n<p>These action endpoints will always have access to POST, and will never trigger a redirect (which is often what Wordpress does for pretty routes... it often routes: <em>site.com/about</em> to <em>site.com/?pageName=about</em>).</p>\n\n<p>Once you've handled the form as you want, you can do a <strong>wp_redirect()</strong> to get to where you need it to be. This is also helpful because an accidental page refresh will not re-send the form.</p>\n\n<p>Much lengthier doco can be found here:\n<a href=\"https://www.sitepoint.com/handling-post-requests-the-wordpress-way/\" rel=\"nofollow noreferrer\">https://www.sitepoint.com/handling-post-requests-the-wordpress-way/</a></p>\n" } ]
2016/11/08
[ "https://wordpress.stackexchange.com/questions/245462", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/11634/" ]
My code was checked and seems OK so maybe the problem lies in the `htaccess` file whose content on my online server is: ``` SetEnv PHP_VER 5_4 Options -Indexes ErrorDocument 404 /index.php RewriteEngine on RewriteCond %{HTTP_HOST} !^www.example.fr$ RewriteRule ^(.*) http://www.example.fr/$1 [QSA,L,R=301] ``` Any reason why this `htaccess` would prevent forms from submitting correctly on my site? Just in case here's my code: ``` <form id='contact_form_mmt' action='<?php echo bloginfo("wpurl"); ?>/contact' method='post'> <input type='text' name='contact_nom' placeholder='Votre nom *' data-validation='length' data-validation-length='min3' data-validation-error-msg='<?php echo $text_too_short_or_empty; ?>'> <input type='text' name='contact_prenom' placeholder='Votre prénom *' data-validation='length' data-validation-length='min3' data-validation-error-msg='<?php echo $text_too_short_or_empty; ?>'> <input type='text' name='contact_mail' placeholder='Votre mail *' data-validation='email' data-validation-length='min3' data-validation-error-msg='<?php echo $email_valid; ?>'> <select name='contact_destinataire'> <option value="[email protected]|Information générales">Information générales</option> <option value="[email protected]|Problèmes liés au site">Problèmes liés au site</option> </select> <textarea name='contact_message' placeholder='Message *'data-validation='length' data-validation-length='min3' data-validation-error-msg='<?php echo $text_too_short_or_empty; ?>'></textarea> <input type='hidden' name='sub' value='1'> <input type='submit' value='envoyer'> </form> ``` PHP (I know the syntax is ugly, I'll improve that): ``` if ( isset($_POST['sub']) ) $sub = $_POST['sub']; else $sub = ''; if ( isset($_POST['contact_nom']) ) $contact_nom = $_POST['contact_nom']; else $contact_nom = ''; if ( isset($_POST['contact_prenom']) ) $contact_prenom = $_POST['contact_prenom' ]; else $contact_prenom = ''; if ( isset($_POST['contact_mail']) ) $contact_mail = $_POST['contact_mail']; else $contact_mail = ''; if ( isset($_POST['contact_sujet']) ) $contact_sujet = $_POST['contact_sujet']; else $contact_sujet = ''; if ( isset($_POST['contact_destinataire']) ) $contact_destinataire = $_POST['contact_destinataire']; else $contact_destinataire = ''; if ( isset($_POST['contact_message']) ) $contact_message = $_POST['contact_message']; else $contact_message = ''; ```
The best way to deal with Form Posts in Wordpress is to use a special endpoint, **/wp-admin/admin-post.php**. POST data can be messed up, both by the WP Query call, and by any redirects that happen. So you set up your form with this action: ``` <form action="<?= admin_url('admin-post.php') ?>" method="post"> <input type="hidden" name="action" value="special_action"> <?php wp_nonce_field('special_action_nonce', 'special_action_nonce'); ?> ``` Then you can handle the form by adding an action to your theme or plugin: ``` add_action('admin_post_nopriv_special_action', ['My\Plugins\FormController', 'specialAction']); add_action('admin_post_special_action', ['My\Plugins\FormController', 'specialAction']); ``` Note that Wordpress constructs a special action, based on the **action** value in the form, **admin\_post\_no\_priv\_*special\_action*** (if you're logged out) and **admin\_post\_*special\_action*** (if you're logged in). You can point these in different locations. These action endpoints will always have access to POST, and will never trigger a redirect (which is often what Wordpress does for pretty routes... it often routes: *site.com/about* to *site.com/?pageName=about*). Once you've handled the form as you want, you can do a **wp\_redirect()** to get to where you need it to be. This is also helpful because an accidental page refresh will not re-send the form. Much lengthier doco can be found here: <https://www.sitepoint.com/handling-post-requests-the-wordpress-way/>
245,465
<p>I wanted to filter the blog title displayed in the header to apply different CSS styles to different title parts/words, so I added the below function to my (WP 4.7) Twenty Seventeen child theme's <em>functions.php</em> and this worked very well. The problem is that this function added the CSS code also to the meta title displayed in the title bar. How to repair this?</p> <pre><code>/** Format the site title parts **/ add_filter( 'bloginfo', 'format_site_title_parts', 10, 2 ); function format_site_title_parts( $text, $show ){ if ('name' == $show) { $text = "&lt;span class='info-style'&gt;Info&lt;/span&gt;" . "&lt;span class='psi-style'&gt;Psi&lt;/span&gt;" . "&lt;span class='md-style'&gt;.md&lt;/span&gt;"; } return $text; } </code></pre> <p><a href="https://i.stack.imgur.com/k0XvH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/k0XvH.png" alt="title bar"></a></p>
[ { "answer_id": 245736, "author": "Michelle", "author_id": 16, "author_profile": "https://wordpress.stackexchange.com/users/16", "pm_score": 1, "selected": false, "text": "<p>You may need to use <code>bloginfo('url')</code> aka <a href=\"https://developer.wordpress.org/reference/functions/home_url/\" rel=\"nofollow noreferrer\"><code>home_url()</code></a> (displayed site) instead of <code>bloginfo('wpurl')</code> aka <a href=\"https://developer.wordpress.org/reference/functions/site_url/\" rel=\"nofollow noreferrer\"><code>site_url()</code></a> (wordpress files location) in your action, for instance:</p>\n\n<pre><code>action=\"&lt;?php echo home_url('/contact/'); ?&gt;\"\n</code></pre>\n" }, { "answer_id": 246049, "author": "sMyles", "author_id": 51201, "author_profile": "https://wordpress.stackexchange.com/users/51201", "pm_score": 2, "selected": false, "text": "<p>The problem is with your <code>htaccess</code> in that you are redirecting to another URL, causing the POST data to no longer be available.</p>\n\n<pre><code>RewriteRule ^(.*) http://www.example.fr/$1 [QSA,L,R=301] \n</code></pre>\n\n<p>Should be</p>\n\n<pre><code>RewriteRule ^(.*) /$1 [QSA,L,R]\n</code></pre>\n\n<p>You could also set it to not redirect on a POST as well:</p>\n\n<pre><code>RewriteCond %{REQUEST_METHOD} !POST [NC]\n</code></pre>\n\n<p>OR, use a 307 redirect, which will preserve the POST data\n<a href=\"https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection</a></p>\n\n<hr>\n\n<p>You can also use PHP shorthand IF statements, and recommend using <code>array_key_exists</code> over <code>isset</code> when you're checking an array</p>\n\n<pre><code>$sub = array_key_exists( 'sub', $_POST ) ? $_POST[ 'sub' ] : '';\n$contact_nom = array_key_exists( 'contact_nom', $_POST ) ? $_POST[ 'contact_nom' ] : '';\n$contact_prenom = array_key_exists( 'contact_prenom', $_POST ) ? $_POST[ 'contact_prenom' ] : '';\n$contact_mail = array_key_exists( 'contact_mail', $_POST ) ? $_POST[ 'contact_mail' ] : '';\n$contact_sujet = array_key_exists( 'contact_sujet', $_POST ) ? $_POST[ 'contact_sujet' ] : '';\n$contact_destinataire = array_key_exists( 'contact_destinataire', $_POST ) ? $_POST[ 'contact_destinataire' ] : '';\n$contact_message = array_key_exists( 'contact_message', $_POST ) ? $_POST[ 'contact_message' ] : '';\n</code></pre>\n\n<p><a href=\"https://davidwalsh.name/php-ternary-examples\" rel=\"nofollow noreferrer\">https://davidwalsh.name/php-ternary-examples</a></p>\n\n<p>You should also be sanitizing the data that is coming in from frontend facing forms, to prevent any possible security vulnerabilities.<br>\nWordPress has plenty of these built in that you can use:\n<a href=\"https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data</a></p>\n\n<hr>\n\n<p>And why not just use something like Caldera Forms which will handle all of this for you?\n<a href=\"https://wordpress.org/plugins/caldera-forms/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/caldera-forms/</a></p>\n" }, { "answer_id": 246199, "author": "haz", "author_id": 99009, "author_profile": "https://wordpress.stackexchange.com/users/99009", "pm_score": 3, "selected": true, "text": "<p>The best way to deal with Form Posts in Wordpress is to use a special endpoint, <strong>/wp-admin/admin-post.php</strong>.</p>\n\n<p>POST data can be messed up, both by the WP Query call, and by any redirects that happen.</p>\n\n<p>So you set up your form with this action: </p>\n\n<pre><code>&lt;form action=\"&lt;?= admin_url('admin-post.php') ?&gt;\" method=\"post\"&gt;\n&lt;input type=\"hidden\" name=\"action\" value=\"special_action\"&gt;\n&lt;?php wp_nonce_field('special_action_nonce', 'special_action_nonce'); ?&gt;\n</code></pre>\n\n<p>Then you can handle the form by adding an action to your theme or plugin:</p>\n\n<pre><code>add_action('admin_post_nopriv_special_action', ['My\\Plugins\\FormController', 'specialAction']);\nadd_action('admin_post_special_action', ['My\\Plugins\\FormController', 'specialAction']);\n</code></pre>\n\n<p>Note that Wordpress constructs a special action, based on the <strong>action</strong> value in the form, <strong>admin_post_no_priv_<em>special_action</em></strong> (if you're logged out) and <strong>admin_post_<em>special_action</em></strong> (if you're logged in). You can point these in different locations.</p>\n\n<p>These action endpoints will always have access to POST, and will never trigger a redirect (which is often what Wordpress does for pretty routes... it often routes: <em>site.com/about</em> to <em>site.com/?pageName=about</em>).</p>\n\n<p>Once you've handled the form as you want, you can do a <strong>wp_redirect()</strong> to get to where you need it to be. This is also helpful because an accidental page refresh will not re-send the form.</p>\n\n<p>Much lengthier doco can be found here:\n<a href=\"https://www.sitepoint.com/handling-post-requests-the-wordpress-way/\" rel=\"nofollow noreferrer\">https://www.sitepoint.com/handling-post-requests-the-wordpress-way/</a></p>\n" } ]
2016/11/08
[ "https://wordpress.stackexchange.com/questions/245465", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25187/" ]
I wanted to filter the blog title displayed in the header to apply different CSS styles to different title parts/words, so I added the below function to my (WP 4.7) Twenty Seventeen child theme's *functions.php* and this worked very well. The problem is that this function added the CSS code also to the meta title displayed in the title bar. How to repair this? ``` /** Format the site title parts **/ add_filter( 'bloginfo', 'format_site_title_parts', 10, 2 ); function format_site_title_parts( $text, $show ){ if ('name' == $show) { $text = "<span class='info-style'>Info</span>" . "<span class='psi-style'>Psi</span>" . "<span class='md-style'>.md</span>"; } return $text; } ``` [![title bar](https://i.stack.imgur.com/k0XvH.png)](https://i.stack.imgur.com/k0XvH.png)
The best way to deal with Form Posts in Wordpress is to use a special endpoint, **/wp-admin/admin-post.php**. POST data can be messed up, both by the WP Query call, and by any redirects that happen. So you set up your form with this action: ``` <form action="<?= admin_url('admin-post.php') ?>" method="post"> <input type="hidden" name="action" value="special_action"> <?php wp_nonce_field('special_action_nonce', 'special_action_nonce'); ?> ``` Then you can handle the form by adding an action to your theme or plugin: ``` add_action('admin_post_nopriv_special_action', ['My\Plugins\FormController', 'specialAction']); add_action('admin_post_special_action', ['My\Plugins\FormController', 'specialAction']); ``` Note that Wordpress constructs a special action, based on the **action** value in the form, **admin\_post\_no\_priv\_*special\_action*** (if you're logged out) and **admin\_post\_*special\_action*** (if you're logged in). You can point these in different locations. These action endpoints will always have access to POST, and will never trigger a redirect (which is often what Wordpress does for pretty routes... it often routes: *site.com/about* to *site.com/?pageName=about*). Once you've handled the form as you want, you can do a **wp\_redirect()** to get to where you need it to be. This is also helpful because an accidental page refresh will not re-send the form. Much lengthier doco can be found here: <https://www.sitepoint.com/handling-post-requests-the-wordpress-way/>
245,478
<p>Looking at <a href="https://developer.wordpress.org/reference/functions/get_post_meta/" rel="noreferrer"><code>get_post_meta()</code></a> I always have to remember to set the <code>$single</code> param to <code>true</code>. I generally assume I'm setting a value and I expect to get that value back.</p> <blockquote> <p>Retrieve post meta field for a post.</p> <ul> <li><strong>$post_id</strong> <em>(int) (Required)</em> Post ID.</li> <li><strong>$key</strong> <em>(string) (Optional)</em> The meta key to retrieve. By default, returns data for all keys. Default value: ''</li> <li><strong>$single</strong> <em>(bool) (Optional)</em> Whether to return a single value. Default value: false</li> </ul> </blockquote> <p>I know this should exist as an option for a reason but I don't personally know why that is. Can someone explain why this returns an <code>array</code> of values by default? It makes sense from a backwards compatibility standpoint but have things evolved? Or are there Core features that require it to be this way for an efficiency that I am unaware of.</p> <p>Does adding <code>$prev_value</code> to <a href="https://codex.wordpress.org/Function_Reference/update_post_meta" rel="noreferrer"><code>update_post_meta()</code></a> create a history as array elements?</p> <p>I would appreciate a <strong>working</strong> example of when this, being set to <code>false</code>, makes sense. That means code I can test. In addition to, a genuinely well thought out and researched answer. That means I want comments like TLC wants scrubs. </p>
[ { "answer_id": 245480, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": -1, "selected": false, "text": "<p>If you have a serialize value in the meta, you can set it to true and get the unserialize array. </p>\n\n<p>So it could make sense if you need to pass it through a form to set it to false, the value will be ready to be send.</p>\n\n<p>Note that <code>get_post_meta()</code> is a simple function that return the result of <code>get_metadata</code>. This function uses: <code>maybe_unserialize()</code> to unserialize the metadata before it is returned.</p>\n\n<p>From the codex (<a href=\"https://codex.wordpress.org/fr:Fonction_get_post_meta\" rel=\"nofollow noreferrer\">translated from french from this page</a>):</p>\n\n<blockquote>\n <p>This may not be very explicit in the case of serialized string. If you\n retrieve a serialized array with this method, you need to set $single\n to \"true\" to actually get a de-serialized array. If you go to \"false\",\n or if you leave it blank, you will have a picture of one, and the\n value at index 0 is the serialized string.</p>\n</blockquote>\n" }, { "answer_id": 245481, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": -1, "selected": false, "text": "<p>It is not so much <code>get_post_meta</code> as <code>add_post_meta</code> that is important here.</p>\n\n<p>In the naive implementation os meta fields, as exposed by the custome fields UI, you can have multiple values assigned to one meta key. </p>\n\n<p>It was probably a lapse of judgment by someone that envisioned that arrays of data will be stored by adding and removing rows to the meta table, instead of realizing that for 95% of the applications serialization is a much better option at least from the POV of readable code. A simple better alternative could have been to reverse the default of that parameter.</p>\n\n<p>There are still 5% (ok, maybe 1%) usages for which this is actually an helpful way to store meta data - when you need to perform a query on it. Easiest example is probably a site which hold the movies at the local theaters and you want to know what is on tonight (8pm - 9pm start time). If you store start times, each in its own db meta row, it is trivial to write a wp_query to return all the relevant movies, while almost impossible if the data is serialized.</p>\n" }, { "answer_id": 245494, "author": "Aamer Shahzad", "author_id": 42772, "author_profile": "https://wordpress.stackexchange.com/users/42772", "pm_score": -1, "selected": false, "text": "<pre><code>$meta = get_post_meta( get_the_ID(), 'meta_key', true );\n</code></pre>\n\n<p><code>'meta_key'</code> is an example meta key.</p>\n\n<p>if you use <code>'false'</code> in the third parameter you will get result in <code>$meta</code> in the form of an <code>array()</code>. you can not <code>echo</code> like this e.g <code>echo $meta;</code> you will use <code>echo $meta[0];</code></p>\n\n<p>if you use <code>'true'</code> in the third parameter you will get the result stored in the <code>$meta</code> variable as <code>string</code>. you can <code>echo</code> the result e.g <code>echo $meta;</code></p>\n\n<p>if you leave the third <em>(Boolean)</em> parameter it is set to <code>'false'</code> by default so it prints the results as an <code>array();</code></p>\n\n<p>to understand this, use the following code inside the loop and you will see the results.</p>\n\n<pre><code>$meta = get_post_meta( get_the_ID(), 'meta_key', true );\necho '&lt;pre&gt;';\nprint_r($meta);\necho '&lt;/pre&gt;';\n</code></pre>\n\n<p>change true to false and see the results. also change <code>'meta_key'</code> to your meta key.</p>\n" }, { "answer_id": 245505, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 5, "selected": true, "text": "<p>In general, <strong>storing PHP serialized data in database in a bad idea</strong>. It can be easily understood if you use multple key-value pairs of data in one field row, that is, you use an array or a object with one meta key.</p>\n\n<p>Imaging a car as the object. You can set multiple meta values to describe the car, for example <code>color</code> and <code>fuel</code>. You can serialize the data and store it in one meta field (only one meta key):</p>\n\n<pre><code>$metadata = array(\n 'color' =&gt; 'white',\n 'fuel' =&gt; 'diesel'\n);\n// as it is an array, $metadata will be serialized automatically by WordPRess\nupdate_post_meta( 458, 'car_meta', $metadata );\n</code></pre>\n\n<p>In this example, you can use <code>get_post_meta()</code> with the third parameter set to <code>false</code>;</p>\n\n<pre><code>$carmeta = get_post_meta( 458, 'car_meta', false );\n// Serialized meta is unserialized automatically by WordPress\necho $carmeta[0]['color'];\necho $carmeta[0]['fuel'];\n</code></pre>\n\n<p>Or you can use it with <code>true</code>, it is not a big difference:</p>\n\n<pre><code>$carmeta = get_post_meta( 458, 'car_meta', true );\necho $carmeta['color'];\necho $carmeta['fuel'];\n</code></pre>\n\n<p>Now imaging you want to get only red cars thar run diesel. You would need to get <strong>all cars</strong> and their meta data from database, and loop over all cars, unserialize the meta data and search the white cars that run diesel. This is <strong>really bad</strong>.</p>\n\n<p>On the other hand, if you use a meta key for each meta data, for example:</p>\n\n<pre><code>$metadata = array(\n 'car_color' =&gt; 'white',\n 'car_fuel' =&gt; 'diesel'\n);\nforeach( $metadata as $key =&gt; $value ) {\n update_post_meta( 458, $key, $value );\n}\n</code></pre>\n\n<p>then you can get what you are looking for directly from database:</p>\n\n<pre><code>$args = array(\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'AND',\n array(\n 'key' =&gt; 'car_color',\n 'value' =&gt; 'red'\n ),\n array(\n 'key' =&gt; 'car_fuel',\n 'value' =&gt; 'diesel'\n )\n )\n);\n\n$query = new WP_Query( $args );\n</code></pre>\n\n<p>Now imaging that a car can be <strong>available in multiple colors</strong>, you could do this:</p>\n\n<pre><code>$metadata = array(\n 'car_colors' =&gt; array( 'red', 'white' ),\n 'car_fuel' =&gt; 'diesel'\n);\nforeach( $metadata as $key =&gt; $value ) {\n update_post_meta( 458, $key, $value );\n}\n</code></pre>\n\n<p>Now we have <code>car_colors</code> meta key with a serialized array. We face the same problems described before if we want to query only for cars available in one color. So, it is better to store colors as repeater meta field:</p>\n\n<pre><code>$metadata = array(\n 'car_colors' =&gt; array( 'red', 'white' ),\n 'car_fuel' =&gt; 'diesel'\n);\nforeach( $metadata as $key =&gt; $value ) {\n if( is_array( $value ) ) {\n foreach( $value as $val ) {\n // We add multiiple meta fields with the same meta key\n add_post_meta( 458, $key, $val );\n }\n } else {\n update_post_meta( 458, $key, $value );\n }\n}\n</code></pre>\n\n<p>Now, if you want to get all available colors of a car, you need the <strong>third parameter of <code>get_post_meta()</code> set to <code>false</code></strong>, if you set it to <code>true</code> you will get only the first available color found in database for that car.</p>\n\n<pre><code>// This gets only the first car_colors entry found in database for car 458\n$available_colors = get_post_meta( 458, 'car_colors', true );\n// This gets all the car_colors entries for car 458\n$available_colors = get_post_meta( 458, 'car_colors', false );\n</code></pre>\n\n<p>It is very basic example but I think it illustrates a <strong>use case where third parameter of <code>get_post_meta()</code> makes sense</strong>, so I hope this answers your question.</p>\n\n<p>Another example could be the one exposed in other answer about shows that are performed several times within a day, for example a movie in a cinema. You want \"starting times\" to be a repeater field, not one field with all the starting times stored as serialized data.</p>\n\n<p>About the other quesiotn: Does adding <code>$prev_value</code> to <code>update_post_meta()</code> create a history as array elements? No. If you pass <code>$prev_value</code> to <code>update_post_meta()</code>, only the existent row in database with that value will be updated; if <code>$pre_value</code> is not set, all rows for the meta key will be updated.</p>\n\n<p>Finally, if you want to delete all available colors of a car:</p>\n\n<pre><code>delete_post_meta( 458, 'car_colors' );\n</code></pre>\n\n<p>And if you want to delete only one entry with a specific value:</p>\n\n<pre><code>delete_post_meta( 458, 'car_colors', 'white' );\n</code></pre>\n" } ]
2016/11/08
[ "https://wordpress.stackexchange.com/questions/245478", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84219/" ]
Looking at [`get_post_meta()`](https://developer.wordpress.org/reference/functions/get_post_meta/) I always have to remember to set the `$single` param to `true`. I generally assume I'm setting a value and I expect to get that value back. > > Retrieve post meta field for a post. > > > * **$post\_id** *(int) (Required)* Post ID. > * **$key** *(string) (Optional)* The meta key to retrieve. By default, returns data for all keys. Default value: '' > * **$single** *(bool) (Optional)* Whether to return a single value. Default value: false > > > I know this should exist as an option for a reason but I don't personally know why that is. Can someone explain why this returns an `array` of values by default? It makes sense from a backwards compatibility standpoint but have things evolved? Or are there Core features that require it to be this way for an efficiency that I am unaware of. Does adding `$prev_value` to [`update_post_meta()`](https://codex.wordpress.org/Function_Reference/update_post_meta) create a history as array elements? I would appreciate a **working** example of when this, being set to `false`, makes sense. That means code I can test. In addition to, a genuinely well thought out and researched answer. That means I want comments like TLC wants scrubs.
In general, **storing PHP serialized data in database in a bad idea**. It can be easily understood if you use multple key-value pairs of data in one field row, that is, you use an array or a object with one meta key. Imaging a car as the object. You can set multiple meta values to describe the car, for example `color` and `fuel`. You can serialize the data and store it in one meta field (only one meta key): ``` $metadata = array( 'color' => 'white', 'fuel' => 'diesel' ); // as it is an array, $metadata will be serialized automatically by WordPRess update_post_meta( 458, 'car_meta', $metadata ); ``` In this example, you can use `get_post_meta()` with the third parameter set to `false`; ``` $carmeta = get_post_meta( 458, 'car_meta', false ); // Serialized meta is unserialized automatically by WordPress echo $carmeta[0]['color']; echo $carmeta[0]['fuel']; ``` Or you can use it with `true`, it is not a big difference: ``` $carmeta = get_post_meta( 458, 'car_meta', true ); echo $carmeta['color']; echo $carmeta['fuel']; ``` Now imaging you want to get only red cars thar run diesel. You would need to get **all cars** and their meta data from database, and loop over all cars, unserialize the meta data and search the white cars that run diesel. This is **really bad**. On the other hand, if you use a meta key for each meta data, for example: ``` $metadata = array( 'car_color' => 'white', 'car_fuel' => 'diesel' ); foreach( $metadata as $key => $value ) { update_post_meta( 458, $key, $value ); } ``` then you can get what you are looking for directly from database: ``` $args = array( 'meta_query' => array( 'relation' => 'AND', array( 'key' => 'car_color', 'value' => 'red' ), array( 'key' => 'car_fuel', 'value' => 'diesel' ) ) ); $query = new WP_Query( $args ); ``` Now imaging that a car can be **available in multiple colors**, you could do this: ``` $metadata = array( 'car_colors' => array( 'red', 'white' ), 'car_fuel' => 'diesel' ); foreach( $metadata as $key => $value ) { update_post_meta( 458, $key, $value ); } ``` Now we have `car_colors` meta key with a serialized array. We face the same problems described before if we want to query only for cars available in one color. So, it is better to store colors as repeater meta field: ``` $metadata = array( 'car_colors' => array( 'red', 'white' ), 'car_fuel' => 'diesel' ); foreach( $metadata as $key => $value ) { if( is_array( $value ) ) { foreach( $value as $val ) { // We add multiiple meta fields with the same meta key add_post_meta( 458, $key, $val ); } } else { update_post_meta( 458, $key, $value ); } } ``` Now, if you want to get all available colors of a car, you need the **third parameter of `get_post_meta()` set to `false`**, if you set it to `true` you will get only the first available color found in database for that car. ``` // This gets only the first car_colors entry found in database for car 458 $available_colors = get_post_meta( 458, 'car_colors', true ); // This gets all the car_colors entries for car 458 $available_colors = get_post_meta( 458, 'car_colors', false ); ``` It is very basic example but I think it illustrates a **use case where third parameter of `get_post_meta()` makes sense**, so I hope this answers your question. Another example could be the one exposed in other answer about shows that are performed several times within a day, for example a movie in a cinema. You want "starting times" to be a repeater field, not one field with all the starting times stored as serialized data. About the other quesiotn: Does adding `$prev_value` to `update_post_meta()` create a history as array elements? No. If you pass `$prev_value` to `update_post_meta()`, only the existent row in database with that value will be updated; if `$pre_value` is not set, all rows for the meta key will be updated. Finally, if you want to delete all available colors of a car: ``` delete_post_meta( 458, 'car_colors' ); ``` And if you want to delete only one entry with a specific value: ``` delete_post_meta( 458, 'car_colors', 'white' ); ```
245,479
<p>I'm using <a href="https://wordpress.org/plugins/ajax-load-more/" rel="nofollow noreferrer">Ajax Load more</a> plugin. <br> I have made it to load X posts on button click, but on the page load there are no posts loaded initially (obviously). <br> What should I do to have (let's say) 10 posts loaded automatically and then next ones loading only on button click. <br> The code right now for that is : <br></p> <pre><code> echo do_shortcode(' [ajax_load_more category="'.$category-&gt;slug.'" posts_per_page="10" pause="true" scroll="false" button_label="Load articles" button_loading_label="Loading..."]' ); </code></pre> <p>Do I have to code that functionality on my own or there is some way to achieve that just with the shortcode change?!</p>
[ { "answer_id": 245483, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 3, "selected": true, "text": "<p>You need to set the <code>offset</code> in the query.</p>\n\n<p>To get the right offset value, you will need to store and send back the offset value to your ajax script (<code>data-offset</code> in the input or an hidden field).</p>\n\n<pre><code>$args = array(\n 'posts_per_page'=&gt; 10,\n 'post_status'=&gt; 'publish',\n 'offset'=&gt; $_POST['offset']\n);\n</code></pre>\n\n<p><code>$_POST['offset']</code> is coming from your button with a js script.</p>\n" }, { "answer_id": 250605, "author": "kundan prasad", "author_id": 109542, "author_profile": "https://wordpress.stackexchange.com/users/109542", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://youtu.be/6U92B_MHfqU\" rel=\"nofollow noreferrer\">https://youtu.be/6U92B_MHfqU</a></p>\n\n<p>copy and paste the code as mension in comment of this video.\nThis simplest way to create custom ajax load more in wordpress.\nFollow the step by step and finally you generate custom ajax load more.</p>\n\n<p><strong>step1:</strong>\npost type code:</p>\n\n<pre><code>//start video post\n$labels2 = array(\n 'name' =&gt; _x('video', 'post type general name', 'robin'),\n 'singular_name' =&gt; _x('video', 'post type singular name', 'robin'),\n 'add_new' =&gt; _x('Add New', 'video', 'robin'),\n 'add_new_item' =&gt; __('Add New video', 'robin'),\n 'edit_item' =&gt; __('Edit video', 'robin'),\n 'new_item' =&gt; __('New video', 'robin'),\n 'all_items' =&gt; __('All video', 'robin'),\n 'view_item' =&gt; __('View video', 'robin'),\n 'search_items' =&gt; __('Search video', 'robin'),\n 'not_found' =&gt; __('No video found', 'robin'),\n 'not_found_in_trash' =&gt; __('No video found in Trash', 'robin'),\n 'parent_item_colon' =&gt; '',\n 'menu_name' =&gt; 'video'\n);\n$args2 = array(\n 'labels' =&gt; $labels2,\n 'public' =&gt; true,\n 'publicly_queryable' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'query_var' =&gt; true,\n 'rewrite' =&gt; true,\n 'capability_type' =&gt; 'post',\n 'has_archive' =&gt; true,\n 'hierarchical' =&gt; false,\n 'menu_position' =&gt; null,\n 'taxonomies' =&gt; array( 'category','post_tag'),\n 'supports' =&gt; array('title','editor','thumbnail')\n);\nregister_post_type('video',$args2);\n//end video post\n</code></pre>\n\n<p><strong>step2:</strong>\nfunction hook:</p>\n\n<pre><code>//load more ajax\n/* ===============================================*/\nfunction my_wfsubmit_callback() {\n $id = $_POST['hide'];\n $current=$id;\n $prev=2;\n $prev=$prev+$current;\n $i=0;\n $the_query = new WP_Query(array( 'post_type' =&gt; 'video', 'posts_per_page' =&gt;'-1','order'=&gt;'ASC','orderby'=&gt;'date' ));\n if($the_query-&gt;have_posts()):\n while($the_query-&gt;have_posts()):$the_query-&gt;the_post();?&gt;\n &lt;?php if($i&gt;=$current &amp;&amp; $i&lt;$prev){?&gt;\n\n &lt;img alt=\"\" src=\"&lt;?php\n $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($query-&gt;ID),'full');\n echo $thumb[0];?&gt;\"&gt;\n &lt;?php the_title();?&gt;\n &lt;?php the_content();?&gt;\n &lt;?php }$i++;?&gt;\n &lt;?php endwhile;\n wp_reset_postdata();\n endif;\n die();\n}\nadd_action( 'wp_ajax_wfsubmit_action', 'my_wfsubmit_callback' ); //wfsubmit_action = ajax action with wordpress hook wp_ajax_wfsubmit_action\nadd_action( 'wp_ajax_nopriv_wfsubmit_action', 'my_wfsubmit_callback' ); //wfsubmit_action = ajax action with wordpress hook wp_ajax_nopriv_wfsubmit_action\n/* ================= end ajax submit ===============*/\n</code></pre>\n\n<p><strong>step3:</strong>\nphpcode:</p>\n\n<pre><code>&lt;?php $args = array( 'post_type' =&gt; 'video', 'posts_per_page' =&gt;'4','order'=&gt;'ASC','orderby'=&gt;'date' );\n$query=new WP_Query($args);\n\nwhile ( $query-&gt;have_posts() ) : $query-&gt;the_post();\n ?&gt;\n\n &lt;img alt=\"\" src=\"&lt;?php\n $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($query-&gt;ID),'full');\n echo $thumb[0];?&gt;\"&gt;\n &lt;?php the_title();?&gt;\n&lt;?php endwhile;?&gt;\n&lt;div id=\"sendtxt\"&gt;&lt;/div&gt;\n\n&lt;?php $args1 = array( 'post_type' =&gt; 'video', 'posts_per_page' =&gt;'-1','order'=&gt;'ASC','orderby'=&gt;'date' );\n$query1=new WP_Query($args1);\n$c=0;\nwhile ( $query1-&gt;have_posts() ) : $query1-&gt;the_post();\n $c++;\nendwhile;\nwp_reset_postdata();\n$max=$c;\n?&gt;\n\n&lt;form id=\"webform\" role=\"form\" class=\"webform\" &gt;\n &lt;textarea name=\"hide\" style=\"display:none;\" class=\"CUR\" id=\"output\"&gt;4\n &lt;/textarea&gt;\n &lt;a href=\"javascript:void(0)\" id=\"webformsubmit\" class=\"read-btn blck\"&gt;Load More&lt;/a&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p><strong>step4:</strong>\nscript code:</p>\n\n<pre><code>&lt;script type=\"text/javascript\" src=\"/wordpress/js/jquery-3.1.1.min.js\"&gt;&lt;/script&gt;\n&lt;script type=\"text/javascript\"&gt;\n $('#webformsubmit').click(function(event){\n event.preventDefault();\n var priBox = \"extra\"; //extra data,field,tag\n var ajaxurlsb = \"&lt;?php echo admin_url( 'admin-ajax.php' );?&gt;\"\n\n $.ajax({\n type: \"POST\",\n url: ajaxurlsb+'?action=wfsubmit_action',\n data: $(\"#webform\").serialize()+'&amp;txtp='+priBox,\n success: function(data) { // Get the result and asign to each cases\n//$('#sendtxt').html(data); //output div ID (sendtxt)\n $('#sendtxt').append(data);\n }\n });\n\n });\n // counter\n $('#webformsubmit').click(function() {\n $('#output').html(function(i, val) { return val*1+2 });\n });\n\n // button display\n\n\n $('#webformsubmit').click(function() {\n var curr_val = $('#output').val();\n if(curr_val &gt;&lt;?php echo $max;?&gt;){\n $(\"#webformsubmit\").css(\"display\", \"none\");\n }\n });\n\n&lt;/script&gt;\n&lt;script type=\"text/javascript\" src=\"/wordpress/js/jquery-3.1.1.min.js\"&gt;&lt;/script&gt;\n</code></pre>\n\n<p><strong>step5:</strong> jquery download link:</p>\n\n<p><a href=\"https://jquery.com/download/\" rel=\"nofollow noreferrer\">https://jquery.com/download/</a></p>\n" } ]
2016/11/08
[ "https://wordpress.stackexchange.com/questions/245479", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106555/" ]
I'm using [Ajax Load more](https://wordpress.org/plugins/ajax-load-more/) plugin. I have made it to load X posts on button click, but on the page load there are no posts loaded initially (obviously). What should I do to have (let's say) 10 posts loaded automatically and then next ones loading only on button click. The code right now for that is : ``` echo do_shortcode(' [ajax_load_more category="'.$category->slug.'" posts_per_page="10" pause="true" scroll="false" button_label="Load articles" button_loading_label="Loading..."]' ); ``` Do I have to code that functionality on my own or there is some way to achieve that just with the shortcode change?!
You need to set the `offset` in the query. To get the right offset value, you will need to store and send back the offset value to your ajax script (`data-offset` in the input or an hidden field). ``` $args = array( 'posts_per_page'=> 10, 'post_status'=> 'publish', 'offset'=> $_POST['offset'] ); ``` `$_POST['offset']` is coming from your button with a js script.
245,482
<p>My visual editor isn't working on a site after just launching it to a new server. I assumed a permissions issue, but the file itself is set to 644. I tried 755 on it as well and still no go. The directories all the way up are 755. </p> <p>I can access other files in the directory, but not this one file. Any ideas? </p>
[ { "answer_id": 245483, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 3, "selected": true, "text": "<p>You need to set the <code>offset</code> in the query.</p>\n\n<p>To get the right offset value, you will need to store and send back the offset value to your ajax script (<code>data-offset</code> in the input or an hidden field).</p>\n\n<pre><code>$args = array(\n 'posts_per_page'=&gt; 10,\n 'post_status'=&gt; 'publish',\n 'offset'=&gt; $_POST['offset']\n);\n</code></pre>\n\n<p><code>$_POST['offset']</code> is coming from your button with a js script.</p>\n" }, { "answer_id": 250605, "author": "kundan prasad", "author_id": 109542, "author_profile": "https://wordpress.stackexchange.com/users/109542", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://youtu.be/6U92B_MHfqU\" rel=\"nofollow noreferrer\">https://youtu.be/6U92B_MHfqU</a></p>\n\n<p>copy and paste the code as mension in comment of this video.\nThis simplest way to create custom ajax load more in wordpress.\nFollow the step by step and finally you generate custom ajax load more.</p>\n\n<p><strong>step1:</strong>\npost type code:</p>\n\n<pre><code>//start video post\n$labels2 = array(\n 'name' =&gt; _x('video', 'post type general name', 'robin'),\n 'singular_name' =&gt; _x('video', 'post type singular name', 'robin'),\n 'add_new' =&gt; _x('Add New', 'video', 'robin'),\n 'add_new_item' =&gt; __('Add New video', 'robin'),\n 'edit_item' =&gt; __('Edit video', 'robin'),\n 'new_item' =&gt; __('New video', 'robin'),\n 'all_items' =&gt; __('All video', 'robin'),\n 'view_item' =&gt; __('View video', 'robin'),\n 'search_items' =&gt; __('Search video', 'robin'),\n 'not_found' =&gt; __('No video found', 'robin'),\n 'not_found_in_trash' =&gt; __('No video found in Trash', 'robin'),\n 'parent_item_colon' =&gt; '',\n 'menu_name' =&gt; 'video'\n);\n$args2 = array(\n 'labels' =&gt; $labels2,\n 'public' =&gt; true,\n 'publicly_queryable' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'query_var' =&gt; true,\n 'rewrite' =&gt; true,\n 'capability_type' =&gt; 'post',\n 'has_archive' =&gt; true,\n 'hierarchical' =&gt; false,\n 'menu_position' =&gt; null,\n 'taxonomies' =&gt; array( 'category','post_tag'),\n 'supports' =&gt; array('title','editor','thumbnail')\n);\nregister_post_type('video',$args2);\n//end video post\n</code></pre>\n\n<p><strong>step2:</strong>\nfunction hook:</p>\n\n<pre><code>//load more ajax\n/* ===============================================*/\nfunction my_wfsubmit_callback() {\n $id = $_POST['hide'];\n $current=$id;\n $prev=2;\n $prev=$prev+$current;\n $i=0;\n $the_query = new WP_Query(array( 'post_type' =&gt; 'video', 'posts_per_page' =&gt;'-1','order'=&gt;'ASC','orderby'=&gt;'date' ));\n if($the_query-&gt;have_posts()):\n while($the_query-&gt;have_posts()):$the_query-&gt;the_post();?&gt;\n &lt;?php if($i&gt;=$current &amp;&amp; $i&lt;$prev){?&gt;\n\n &lt;img alt=\"\" src=\"&lt;?php\n $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($query-&gt;ID),'full');\n echo $thumb[0];?&gt;\"&gt;\n &lt;?php the_title();?&gt;\n &lt;?php the_content();?&gt;\n &lt;?php }$i++;?&gt;\n &lt;?php endwhile;\n wp_reset_postdata();\n endif;\n die();\n}\nadd_action( 'wp_ajax_wfsubmit_action', 'my_wfsubmit_callback' ); //wfsubmit_action = ajax action with wordpress hook wp_ajax_wfsubmit_action\nadd_action( 'wp_ajax_nopriv_wfsubmit_action', 'my_wfsubmit_callback' ); //wfsubmit_action = ajax action with wordpress hook wp_ajax_nopriv_wfsubmit_action\n/* ================= end ajax submit ===============*/\n</code></pre>\n\n<p><strong>step3:</strong>\nphpcode:</p>\n\n<pre><code>&lt;?php $args = array( 'post_type' =&gt; 'video', 'posts_per_page' =&gt;'4','order'=&gt;'ASC','orderby'=&gt;'date' );\n$query=new WP_Query($args);\n\nwhile ( $query-&gt;have_posts() ) : $query-&gt;the_post();\n ?&gt;\n\n &lt;img alt=\"\" src=\"&lt;?php\n $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($query-&gt;ID),'full');\n echo $thumb[0];?&gt;\"&gt;\n &lt;?php the_title();?&gt;\n&lt;?php endwhile;?&gt;\n&lt;div id=\"sendtxt\"&gt;&lt;/div&gt;\n\n&lt;?php $args1 = array( 'post_type' =&gt; 'video', 'posts_per_page' =&gt;'-1','order'=&gt;'ASC','orderby'=&gt;'date' );\n$query1=new WP_Query($args1);\n$c=0;\nwhile ( $query1-&gt;have_posts() ) : $query1-&gt;the_post();\n $c++;\nendwhile;\nwp_reset_postdata();\n$max=$c;\n?&gt;\n\n&lt;form id=\"webform\" role=\"form\" class=\"webform\" &gt;\n &lt;textarea name=\"hide\" style=\"display:none;\" class=\"CUR\" id=\"output\"&gt;4\n &lt;/textarea&gt;\n &lt;a href=\"javascript:void(0)\" id=\"webformsubmit\" class=\"read-btn blck\"&gt;Load More&lt;/a&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p><strong>step4:</strong>\nscript code:</p>\n\n<pre><code>&lt;script type=\"text/javascript\" src=\"/wordpress/js/jquery-3.1.1.min.js\"&gt;&lt;/script&gt;\n&lt;script type=\"text/javascript\"&gt;\n $('#webformsubmit').click(function(event){\n event.preventDefault();\n var priBox = \"extra\"; //extra data,field,tag\n var ajaxurlsb = \"&lt;?php echo admin_url( 'admin-ajax.php' );?&gt;\"\n\n $.ajax({\n type: \"POST\",\n url: ajaxurlsb+'?action=wfsubmit_action',\n data: $(\"#webform\").serialize()+'&amp;txtp='+priBox,\n success: function(data) { // Get the result and asign to each cases\n//$('#sendtxt').html(data); //output div ID (sendtxt)\n $('#sendtxt').append(data);\n }\n });\n\n });\n // counter\n $('#webformsubmit').click(function() {\n $('#output').html(function(i, val) { return val*1+2 });\n });\n\n // button display\n\n\n $('#webformsubmit').click(function() {\n var curr_val = $('#output').val();\n if(curr_val &gt;&lt;?php echo $max;?&gt;){\n $(\"#webformsubmit\").css(\"display\", \"none\");\n }\n });\n\n&lt;/script&gt;\n&lt;script type=\"text/javascript\" src=\"/wordpress/js/jquery-3.1.1.min.js\"&gt;&lt;/script&gt;\n</code></pre>\n\n<p><strong>step5:</strong> jquery download link:</p>\n\n<p><a href=\"https://jquery.com/download/\" rel=\"nofollow noreferrer\">https://jquery.com/download/</a></p>\n" } ]
2016/11/08
[ "https://wordpress.stackexchange.com/questions/245482", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24054/" ]
My visual editor isn't working on a site after just launching it to a new server. I assumed a permissions issue, but the file itself is set to 644. I tried 755 on it as well and still no go. The directories all the way up are 755. I can access other files in the directory, but not this one file. Any ideas?
You need to set the `offset` in the query. To get the right offset value, you will need to store and send back the offset value to your ajax script (`data-offset` in the input or an hidden field). ``` $args = array( 'posts_per_page'=> 10, 'post_status'=> 'publish', 'offset'=> $_POST['offset'] ); ``` `$_POST['offset']` is coming from your button with a js script.
245,512
<p>I was developing a new WordPress website so i added this function at the end of the "functions.php" file to redirect all users to a /maintenance-mode page in my website except me(My IP-Address):</p> <pre><code>function wp_maintenance_mode() { if ( !is_page( 2075 ) &amp;&amp; $_SERVER['REMOTE_ADDR'] != "111.222.33.44" ) { wp_redirect( home_url( 'maintenance-mode' ) ); exit; } } add_action( 'template_redirect', 'wp_maintenance_mode' ); </code></pre> <p>After finishing the website development and i wanted to put it alive i have commented this function by putting it inside comments /* */ .. When i now access the website strangely the maintenance-mode still appears when i access any page. I tried to remove the comments but it still goes to the maintenance-mode page!</p> <p>It is getting me crazy and i can't find why this happens. I searched everywhere, in the database, in my files for an access to the maintenance-mode page but i can't see any.</p> <p><strong>Do you have any idea what may be causing this?</strong></p>
[ { "answer_id": 245521, "author": "mpickett", "author_id": 106046, "author_profile": "https://wordpress.stackexchange.com/users/106046", "pm_score": 0, "selected": false, "text": "<p>Have you tried to take the function out of functions.php file altogether? I had a similar issue, not with a maintenance function but a function I had in my code that wouldn't go away, I tried to comment it out as well. </p>\n\n<p>I had to remove the function from the file, clear my cache, and upload the fresh file. </p>\n\n<p>Once that was done - I added the function back into the file, commented it out and all is well!</p>\n" }, { "answer_id": 245556, "author": "Brad", "author_id": 97480, "author_profile": "https://wordpress.stackexchange.com/users/97480", "pm_score": 1, "selected": false, "text": "<p>I was able to fix it finally! .. All i did is deactivating all WordPress plugins then reactivating them again, and all worked fine .. Just that!!! </p>\n" } ]
2016/11/08
[ "https://wordpress.stackexchange.com/questions/245512", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97480/" ]
I was developing a new WordPress website so i added this function at the end of the "functions.php" file to redirect all users to a /maintenance-mode page in my website except me(My IP-Address): ``` function wp_maintenance_mode() { if ( !is_page( 2075 ) && $_SERVER['REMOTE_ADDR'] != "111.222.33.44" ) { wp_redirect( home_url( 'maintenance-mode' ) ); exit; } } add_action( 'template_redirect', 'wp_maintenance_mode' ); ``` After finishing the website development and i wanted to put it alive i have commented this function by putting it inside comments /\* \*/ .. When i now access the website strangely the maintenance-mode still appears when i access any page. I tried to remove the comments but it still goes to the maintenance-mode page! It is getting me crazy and i can't find why this happens. I searched everywhere, in the database, in my files for an access to the maintenance-mode page but i can't see any. **Do you have any idea what may be causing this?**
I was able to fix it finally! .. All i did is deactivating all WordPress plugins then reactivating them again, and all worked fine .. Just that!!!
245,513
<p>I want to know, how to get i.e. $post ID, TITLE and etc.. in metabox?</p> <p>is other solution available, instead of <code>$GLOBALS['post']</code> ?</p>
[ { "answer_id": 245514, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 1, "selected": false, "text": "<p>Just go with what the API provides (the global <code>$post</code> object refers to the post that is set up via the main query loop <code>setup_postdata()</code> function):</p>\n\n<pre><code>$post = get_post( get_the_ID() );\n</code></pre>\n\n<p>All other API functions also refer to the <code>$_GLOBALS['post']</code> variable and the <code>global $wp_query</code> (and respectively the <code>global $wp_the_query</code>) vars. Just call <code>get_the_title()</code>, etc. and you are good. Sidenote: All this is cached per default, so repetitive calls do not hurt.</p>\n\n<p><strong>Edit:</strong> Drop what this answer provides and go with what @toscho wrote in his answer, which was correctly chosen as solution.</p>\n" }, { "answer_id": 245516, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 3, "selected": true, "text": "<p>Do not rely on globals like <code>get_the_ID()</code> or <code>get_post()</code> do. Use the parameters for your callbacks.</p>\n\n<p>You get the current post object <strong>twice</strong>:</p>\n\n<ol>\n<li>When you register the metabox, you get the post object as a second parameter.</li>\n<li>When your output callback is called, you get it as the first parameter.</li>\n</ol>\n\n<p>Here is an example showing both cases:</p>\n\n<pre><code>add_action( 'add_meta_boxes', function( $post_type, \\WP_Post $post ) {\n add_meta_box(\n 'test', // handle\n 'Box title', // title\n function( \\WP_Post $post ) { // output\n print get_the_title( $post );\n });\n});\n</code></pre>\n" } ]
2016/11/08
[ "https://wordpress.stackexchange.com/questions/245513", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33667/" ]
I want to know, how to get i.e. $post ID, TITLE and etc.. in metabox? is other solution available, instead of `$GLOBALS['post']` ?
Do not rely on globals like `get_the_ID()` or `get_post()` do. Use the parameters for your callbacks. You get the current post object **twice**: 1. When you register the metabox, you get the post object as a second parameter. 2. When your output callback is called, you get it as the first parameter. Here is an example showing both cases: ``` add_action( 'add_meta_boxes', function( $post_type, \WP_Post $post ) { add_meta_box( 'test', // handle 'Box title', // title function( \WP_Post $post ) { // output print get_the_title( $post ); }); }); ```
245,520
<p>If someone opens any post at the front-end, does it matter how many times I call <code>get_post_meta</code> function? I thought it could increase performance if I won't call that function 2-3 times instead of 20 calls on single post page.</p>
[ { "answer_id": 245524, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 3, "selected": true, "text": "<p>One call to <code>get_post_meta()</code> fetches all met keys and values for that post. All these values are then stored in the cache. The next call will just fetch the data from the cache. So you can safely call that function multiple times.</p>\n\n<p>In details:</p>\n\n<ol>\n<li><code>get_post_meta()</code> calls <code>get_metadata('post', $post_id, $key, $single);</code></li>\n<li><code>get_metadata()</code> checks the cache and calls <code>update_meta_cache()</code> if it doesn't find an existing cache.</li>\n<li><p><code>update_meta_cache()</code> fetches all entries with:</p>\n\n<pre><code>\"SELECT $column, meta_key, meta_value \n FROM $table \n WHERE $column IN ($id_list) \n ORDER BY $id_column ASC\"\n</code></pre></li>\n</ol>\n\n<p>The same is true for user meta values.</p>\n" }, { "answer_id": 250272, "author": "prosti", "author_id": 88606, "author_profile": "https://wordpress.stackexchange.com/users/88606", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>...I thought it could increase performance if I won't call that function 2-3 times instead of 20 calls on single post page</p>\n</blockquote>\n\n<p>Together with the excellent answer from @toscho, I will just add one additional thing, based on my latest <a href=\"https://wordpress.stackexchange.com/questions/226960/why-query-posts-isnt-marked-as-deprecated/248955#248955\">digging</a>.</p>\n\n<p>If you don't set it otherwise WordPress queries will prefetch post meta values for all the posts <strong>the query</strong> returns.</p>\n\n<p>This means even before you call <code>get_post_meta();</code> the meta values are already in the WordPress cache.</p>\n\n<p>Nacin, explained <a href=\"http://wordpress.tv/2012/06/15/andrew-nacin-wp_query/\" rel=\"nofollow noreferrer\">this</a> and you can refer the slide 34 in this <a href=\"http://www.slideshare.net/andrewnacin/you-dont-know-query-wordcamp-portland-2011\" rel=\"nofollow noreferrer\">presentation</a>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/zmRZn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zmRZn.png\" alt=\"enter image description here\"></a></p>\n\n<p>From this image, you may understand that typically WordPress prefetches the information for the metadata and also for the terms.</p>\n\n<p>The conclusion is the same as from @toscho. You may call <code>get_post_meta();</code> whenever you need.</p>\n\n<hr>\n\n<p>To get the basic details on how the caching looks, you also may check <a href=\"https://wordpress.stackexchange.com/questions/74676/how-does-object-caching-work/249358#249358\">this post</a>.</p>\n" } ]
2016/11/08
[ "https://wordpress.stackexchange.com/questions/245520", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33667/" ]
If someone opens any post at the front-end, does it matter how many times I call `get_post_meta` function? I thought it could increase performance if I won't call that function 2-3 times instead of 20 calls on single post page.
One call to `get_post_meta()` fetches all met keys and values for that post. All these values are then stored in the cache. The next call will just fetch the data from the cache. So you can safely call that function multiple times. In details: 1. `get_post_meta()` calls `get_metadata('post', $post_id, $key, $single);` 2. `get_metadata()` checks the cache and calls `update_meta_cache()` if it doesn't find an existing cache. 3. `update_meta_cache()` fetches all entries with: ``` "SELECT $column, meta_key, meta_value FROM $table WHERE $column IN ($id_list) ORDER BY $id_column ASC" ``` The same is true for user meta values.
245,523
<p>I am using child theme of rehub theme to create a website. Just like many other themes it has option of "static homepage" and "recent posts" homepage. As my theme is a deal based theme I have to use "recent posts" options.</p> <p>But, due to this the home page is missing H1 tag because there is no tag by default in the theme. I have no experience of php coding, so please help me in adding H1 tag on the homepage. The site link is - www.top20deals.com</p> <p>Code of header.php from main rehub theme is as follows -</p> <pre><code> &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;meta name="viewport" content="width=device-width" /&gt; &lt;!-- feeds &amp; pingback --&gt; &lt;link rel="profile" href="http://gmpg.org/xfn/11" /&gt; &lt;link rel="pingback" href="&lt;?php bloginfo( 'pingback_url' ); ?&gt;" /&gt; &lt;!--[if lt IE 9]&gt;&lt;script src="&lt;?php echo get_template_directory_uri(); ?&gt;/js/html5shiv.js"&gt;&lt;/script&gt;&lt;![endif]--&gt; &lt;?php wp_head(); ?&gt; &lt;?php if(rehub_option('rehub_custom_css')) : ?&gt;&lt;style&gt;&lt;?php echo rehub_option('rehub_custom_css'); ?&gt;&lt;/style&gt;&lt;?php endif; ?&gt; &lt;/head&gt; </code></pre>
[ { "answer_id": 245524, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 3, "selected": true, "text": "<p>One call to <code>get_post_meta()</code> fetches all met keys and values for that post. All these values are then stored in the cache. The next call will just fetch the data from the cache. So you can safely call that function multiple times.</p>\n\n<p>In details:</p>\n\n<ol>\n<li><code>get_post_meta()</code> calls <code>get_metadata('post', $post_id, $key, $single);</code></li>\n<li><code>get_metadata()</code> checks the cache and calls <code>update_meta_cache()</code> if it doesn't find an existing cache.</li>\n<li><p><code>update_meta_cache()</code> fetches all entries with:</p>\n\n<pre><code>\"SELECT $column, meta_key, meta_value \n FROM $table \n WHERE $column IN ($id_list) \n ORDER BY $id_column ASC\"\n</code></pre></li>\n</ol>\n\n<p>The same is true for user meta values.</p>\n" }, { "answer_id": 250272, "author": "prosti", "author_id": 88606, "author_profile": "https://wordpress.stackexchange.com/users/88606", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>...I thought it could increase performance if I won't call that function 2-3 times instead of 20 calls on single post page</p>\n</blockquote>\n\n<p>Together with the excellent answer from @toscho, I will just add one additional thing, based on my latest <a href=\"https://wordpress.stackexchange.com/questions/226960/why-query-posts-isnt-marked-as-deprecated/248955#248955\">digging</a>.</p>\n\n<p>If you don't set it otherwise WordPress queries will prefetch post meta values for all the posts <strong>the query</strong> returns.</p>\n\n<p>This means even before you call <code>get_post_meta();</code> the meta values are already in the WordPress cache.</p>\n\n<p>Nacin, explained <a href=\"http://wordpress.tv/2012/06/15/andrew-nacin-wp_query/\" rel=\"nofollow noreferrer\">this</a> and you can refer the slide 34 in this <a href=\"http://www.slideshare.net/andrewnacin/you-dont-know-query-wordcamp-portland-2011\" rel=\"nofollow noreferrer\">presentation</a>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/zmRZn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zmRZn.png\" alt=\"enter image description here\"></a></p>\n\n<p>From this image, you may understand that typically WordPress prefetches the information for the metadata and also for the terms.</p>\n\n<p>The conclusion is the same as from @toscho. You may call <code>get_post_meta();</code> whenever you need.</p>\n\n<hr>\n\n<p>To get the basic details on how the caching looks, you also may check <a href=\"https://wordpress.stackexchange.com/questions/74676/how-does-object-caching-work/249358#249358\">this post</a>.</p>\n" } ]
2016/11/08
[ "https://wordpress.stackexchange.com/questions/245523", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106576/" ]
I am using child theme of rehub theme to create a website. Just like many other themes it has option of "static homepage" and "recent posts" homepage. As my theme is a deal based theme I have to use "recent posts" options. But, due to this the home page is missing H1 tag because there is no tag by default in the theme. I have no experience of php coding, so please help me in adding H1 tag on the homepage. The site link is - www.top20deals.com Code of header.php from main rehub theme is as follows - ``` <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <!-- feeds & pingback --> <link rel="profile" href="http://gmpg.org/xfn/11" /> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" /> <!--[if lt IE 9]><script src="<?php echo get_template_directory_uri(); ?>/js/html5shiv.js"></script><![endif]--> <?php wp_head(); ?> <?php if(rehub_option('rehub_custom_css')) : ?><style><?php echo rehub_option('rehub_custom_css'); ?></style><?php endif; ?> </head> ```
One call to `get_post_meta()` fetches all met keys and values for that post. All these values are then stored in the cache. The next call will just fetch the data from the cache. So you can safely call that function multiple times. In details: 1. `get_post_meta()` calls `get_metadata('post', $post_id, $key, $single);` 2. `get_metadata()` checks the cache and calls `update_meta_cache()` if it doesn't find an existing cache. 3. `update_meta_cache()` fetches all entries with: ``` "SELECT $column, meta_key, meta_value FROM $table WHERE $column IN ($id_list) ORDER BY $id_column ASC" ``` The same is true for user meta values.
245,535
<p>Usually, you would use <code>esc_url()</code> to escape a URL before displaying it. If that 'URL' is a data URI (eg. <code>'data:image/svg+xml;base64,...'</code>), it will be trimmed blank by <code>esc_url()</code>.</p> <p>The Codex page on Data Validation <a href="https://codex.wordpress.org/Data_Validation#URLs" rel="nofollow noreferrer">has this to say</a> about escaping URLs:</p> <blockquote> <p>Always use esc_url when sanitizing URLs (in text nodes, attribute nodes or anywhere else). Rejects URLs that do not have one of the provided whitelisted protocols (defaulting to http, https, ftp, ftps, mailto, news, irc, gopher, nntp, feed, and telnet), eliminates invalid characters, and removes dangerous characters. Replaces clean_url() which was deprecated in 3.0.</p> </blockquote> <p>Data URIs aren't covered by this function and don't appear to be covered by any of the other standard WP escaping functions.</p> <p>Is there an established best practice in WordPress for escaping data URIs?</p>
[ { "answer_id": 245539, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>A data UR<strong>I</strong> isn't quite a ur<strong>l</strong>, but it <strong>is</strong> an attribute. Use <code>esc_attr</code> to escape it in attributes, and <code>esc_html</code> elsewhere. The key being that escaping indicates what you're expecting. If you're expecting a url, use <code>esc_url</code>, if it's an attribute use <code>esc_attr</code>, if it's text with no html, use <code>esc_html</code>, etc etc</p>\n\n<p><code>esc_url</code> will do the same but with some additional rules, such as enforcing a protocol at the beginning etc</p>\n" }, { "answer_id": 245540, "author": "JHoffmann", "author_id": 63847, "author_profile": "https://wordpress.stackexchange.com/users/63847", "pm_score": 3, "selected": true, "text": "<p>It is possible to pass an array with allowed protocols to the <a href=\"https://developer.wordpress.org/reference/functions/esc_url/\" rel=\"nofollow noreferrer\">esc_url()</a> function. For data-URLs this has to contain the <code>data</code> scheme, as this is not whitelisted by <a href=\"https://developer.wordpress.org/reference/functions/wp_allowed_protocols/\" rel=\"nofollow noreferrer\">wp_allowed_protocols()</a> as default.</p>\n\n<pre><code>esc_url( $data_url, array( 'data' ) );\n</code></pre>\n" } ]
2016/11/08
[ "https://wordpress.stackexchange.com/questions/245535", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/46066/" ]
Usually, you would use `esc_url()` to escape a URL before displaying it. If that 'URL' is a data URI (eg. `'data:image/svg+xml;base64,...'`), it will be trimmed blank by `esc_url()`. The Codex page on Data Validation [has this to say](https://codex.wordpress.org/Data_Validation#URLs) about escaping URLs: > > Always use esc\_url when sanitizing URLs (in text nodes, attribute nodes or anywhere else). Rejects URLs that do not have one of the provided whitelisted protocols (defaulting to http, https, ftp, ftps, mailto, news, irc, gopher, nntp, feed, and telnet), eliminates invalid characters, and removes dangerous characters. Replaces clean\_url() which was deprecated in 3.0. > > > Data URIs aren't covered by this function and don't appear to be covered by any of the other standard WP escaping functions. Is there an established best practice in WordPress for escaping data URIs?
It is possible to pass an array with allowed protocols to the [esc\_url()](https://developer.wordpress.org/reference/functions/esc_url/) function. For data-URLs this has to contain the `data` scheme, as this is not whitelisted by [wp\_allowed\_protocols()](https://developer.wordpress.org/reference/functions/wp_allowed_protocols/) as default. ``` esc_url( $data_url, array( 'data' ) ); ```
245,544
<p>Forgive me if this is discussed elsewhere on the forums but I can't seem to find it anywhere. How can we display the current time from the blog (or from New York, for instance) within a block of text? It would be even better if it continues changing each second after loading but not necessary.</p> <p>This would be difference from displaying a post date, <a href="https://wordpress.stackexchange.com/questions/223988/how-to-display-date-time-author-in-pages">for instance</a>.</p>
[ { "answer_id": 245545, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": false, "text": "<p>Take a look at <a href=\"https://codex.wordpress.org/Function_Reference/current_time\" rel=\"nofollow noreferrer\"><code>current_time()</code></a>.</p>\n<blockquote>\n<p>Returns the blog's current local time in the specified format. There are two named formats: 'mysql' for MySQL/MariaDB's timestamp data type format (i.e. YYYY-MM-DD HH:MM:SS), and 'timestamp' for the Unix timestamp format (i.e. epoch). Other strings will be interpreted as PHP date formats (e.g. 'Y-m-d') since 3.9.0. The optional secondary parameter can be used to retrieve GMT time instead of the blog's local time.</p>\n<p>The local time returned is based on the timezone set on the blog's General Settings page, which is UTC by default.</p>\n<p><code>current_time( 'timestamp' )</code> should be used in lieu of <code>time()</code> to return the blog's local time. In WordPress, PHP's <code>time()</code> will always return <strong>UTC</strong> and is the same as calling <code>current_time( 'timestamp', true )</code>.</p>\n</blockquote>\n<p>You can also modify the <a href=\"http://php.net/manual/en/class.datetimezone.php\" rel=\"nofollow noreferrer\"><code>TimeZone</code></a> of a <a href=\"http://php.net/manual/en/function.date.php\" rel=\"nofollow noreferrer\"><code>date</code></a>.</p>\n<pre><code>$d = date( 'c', time() );\n\necho $d; // 2016-06-12T16:35:39+00:00\n\n$t = new DateTime($d);\n$t-&gt;setTimezone(new DateTimeZone( 'America/Los_Angeles' ));\n\necho &quot;\\tLOS\\t&quot; . $t-&gt;format( 'g:i:s A' ); // 9:35:39 AM\n\n$t-&gt;setTimezone(new DateTimeZone( 'America/New_York' ));\n\necho &quot;\\tNYC\\t&quot; . $t-&gt;format( 'g:i:s A' ); // 12:35:39 PM\n\necho ( $t-&gt;format('G') &lt; 9) ? ' Before 9AM' : ' After 9AM';\n</code></pre>\n" }, { "answer_id": 245546, "author": "Carter Steinhoff", "author_id": 102397, "author_profile": "https://wordpress.stackexchange.com/users/102397", "pm_score": 2, "selected": false, "text": "<p>If you are familiar with short codes and your functions.php, I have a solution for you. However, this will only display as static.</p>\n\n<p>Add the following code to the bottom of your functions.php file.<br>\n <code>&lt;?php function displaydate(){\n return date('g i: A');\n}\nadd_shortcode( 'date', 'displaydate' );\n</code></p>\n\n<p>For me, right now in Arizona, this would output 5:07 PM</p>\n\n<p>This code includes a function which checks the current time and then returns it when the shortcode is inserted in a post or page. </p>\n\n<p>Now all you need to do to display the time is write your shortcode into one of your posts or pages. In this example, the shortcode is [date].</p>\n\n<p>Take note of the characters after \"return date\", these are what control what is outputted. </p>\n\n<p>You can adjust what is outputted in the shortcode by using different characters.</p>\n\n<p>This link will give you a table of date format characters you can use. <a href=\"https://codex.wordpress.org/Formatting_Date_and_Time\" rel=\"nofollow\">https://codex.wordpress.org/Formatting_Date_and_Time</a></p>\n" }, { "answer_id": 245559, "author": "Third Essential Designer", "author_id": 103698, "author_profile": "https://wordpress.stackexchange.com/users/103698", "pm_score": 1, "selected": false, "text": "<p>WordPress deals with time in the <a href=\"https://en.wikipedia.org/wiki/Unix_time\" rel=\"nofollow noreferrer\">UNIX format</a>. You can display date and time as follows.</p>\n\n<ol>\n<li>If you are a beginner (developer) you can use <code>&lt;?php echo date('l jS F Y'); ?&gt;</code> to display at the place. It will change every time the page loads. To change it every second you will need to use an <a href=\"http://en.wikipedia.org/wiki/Ajax_%28programming%29\" rel=\"nofollow noreferrer\">Ajax</a> thing and some custom code.</li>\n<li>You can use a <a href=\"https://wordpress.org/plugins/local-time-clock/faq/\" rel=\"nofollow noreferrer\">Local Time Clock</a> plugin and use it as a widget and customize it as per your needs.</li>\n</ol>\n" } ]
2016/11/08
[ "https://wordpress.stackexchange.com/questions/245544", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/96983/" ]
Forgive me if this is discussed elsewhere on the forums but I can't seem to find it anywhere. How can we display the current time from the blog (or from New York, for instance) within a block of text? It would be even better if it continues changing each second after loading but not necessary. This would be difference from displaying a post date, [for instance](https://wordpress.stackexchange.com/questions/223988/how-to-display-date-time-author-in-pages).
Take a look at [`current_time()`](https://codex.wordpress.org/Function_Reference/current_time). > > Returns the blog's current local time in the specified format. There are two named formats: 'mysql' for MySQL/MariaDB's timestamp data type format (i.e. YYYY-MM-DD HH:MM:SS), and 'timestamp' for the Unix timestamp format (i.e. epoch). Other strings will be interpreted as PHP date formats (e.g. 'Y-m-d') since 3.9.0. The optional secondary parameter can be used to retrieve GMT time instead of the blog's local time. > > > The local time returned is based on the timezone set on the blog's General Settings page, which is UTC by default. > > > `current_time( 'timestamp' )` should be used in lieu of `time()` to return the blog's local time. In WordPress, PHP's `time()` will always return **UTC** and is the same as calling `current_time( 'timestamp', true )`. > > > You can also modify the [`TimeZone`](http://php.net/manual/en/class.datetimezone.php) of a [`date`](http://php.net/manual/en/function.date.php). ``` $d = date( 'c', time() ); echo $d; // 2016-06-12T16:35:39+00:00 $t = new DateTime($d); $t->setTimezone(new DateTimeZone( 'America/Los_Angeles' )); echo "\tLOS\t" . $t->format( 'g:i:s A' ); // 9:35:39 AM $t->setTimezone(new DateTimeZone( 'America/New_York' )); echo "\tNYC\t" . $t->format( 'g:i:s A' ); // 12:35:39 PM echo ( $t->format('G') < 9) ? ' Before 9AM' : ' After 9AM'; ```
245,589
<p>The solution <code>&lt;?php query_posts('posts_per_page=9'); ?&gt;</code> to limit author related posts show the entire website post :( </p> <pre><code> &lt;?php $curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author)); ?&gt; &lt;h2&gt;About: &lt;?php echo $curauth-&gt;nickname; ?&gt;&lt;/h2&gt; &lt;dl&gt; &lt;dt&gt;Website&lt;/dt&gt; &lt;dd&gt;&lt;a href="&lt;?php echo $curauth-&gt;user_url; ?&gt;"&gt;&lt;?php echo $curauth-&gt;user_url; ?&gt;&lt;/a&gt;&lt;/dd&gt; &lt;dt&gt;Profile&lt;/dt&gt; &lt;dd&gt; &lt;?php echo $curauth-&gt;user_description; ?&gt; &lt;/dd&gt; &lt;/dl&gt; &lt;h2&gt;Posts by &lt;?php echo $curauth-&gt;nickname; ?&gt;:&lt;/h2&gt; &lt;ul&gt; &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt; &lt;li&gt; &lt;a href="&lt;?php the_permalink() ?&gt;" rel="bookmark" title="Permanent Link: &lt;?php the_title(); ?&gt;"&gt; &lt;?php the_title(); ?&gt; &lt;/a&gt;, &lt;?php the_time('d M Y'); ?&gt; in &lt;?php the_category('&amp;');?&gt; &lt;/li&gt; &lt;?php endwhile; else: ?&gt; &lt;p&gt; &lt;?php _e('No posts by this author.'); ?&gt; &lt;/p&gt; &lt;?php endif; ?&gt; &lt;/ul&gt; </code></pre>
[ { "answer_id": 245590, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 2, "selected": true, "text": "<p>Never, <strong>never</strong> re-query a native archive - use the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\"><code>pre_get_posts</code> hook</a> to <em>alter</em> the main query:</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $wp_query ) {\n if ( $wp_query-&gt;is_main_query() &amp;&amp; $wp_query-&gt;is_author() ) {\n $paged = max( 1, ( int ) $wp_query-&gt;get( 'paged' ) );\n\n if ( $paged === 1 ) {\n $wp_query-&gt;set( 'posts_per_page', 10 );\n } else {\n $wp_query-&gt;set( 'posts_per_page', 9 );\n $wp_query-&gt;set( 'offset', ( ( $paged - 1 ) * 9 ) + 1 );\n }\n }\n});\n</code></pre>\n\n<p>Add the above to your <code>functions.php</code> and remove <code>query_posts( ... )</code> line.</p>\n" }, { "answer_id": 245591, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 0, "selected": false, "text": "<p>To create secondary listings (for example, a list of related posts at the bottom of the page, or a list of links in a sidebar widget), try making a new instance of WP_Query or use get_posts().</p>\n\n<p>Why ? query_posts() is meant for altering the main loop. It does so by replacing the query used to generate the main loop content.</p>\n\n<p>Infos from <a href=\"https://developer.wordpress.org/reference/functions/query_posts/#alters-main-loop\" rel=\"nofollow noreferrer\">developer.wordpress.org query_posts()</a></p>\n\n<p>SO in your code, you'll need to create a new query,</p>\n\n<pre><code>$related_query = get_posts(array(\n 'post_type'=&gt; 'post',\n 'post_status'=&gt; 'publish',\n 'post_author'=&gt; $curauth,// must be the id\n 'posts_er_page'=&gt; 9, \n )\n);\nif ( $related_query ) {\nforeach ( $related_query as $post ) :\n setup_postdata( $post ); ?&gt;\n &lt;h2&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt;\n &lt;?php the_content(); ?&gt;\n &lt;?php\n endforeach; \n wp_reset_postdata();\n} \n</code></pre>\n" } ]
2016/11/09
[ "https://wordpress.stackexchange.com/questions/245589", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24058/" ]
The solution `<?php query_posts('posts_per_page=9'); ?>` to limit author related posts show the entire website post :( ``` <?php $curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author)); ?> <h2>About: <?php echo $curauth->nickname; ?></h2> <dl> <dt>Website</dt> <dd><a href="<?php echo $curauth->user_url; ?>"><?php echo $curauth->user_url; ?></a></dd> <dt>Profile</dt> <dd> <?php echo $curauth->user_description; ?> </dd> </dl> <h2>Posts by <?php echo $curauth->nickname; ?>:</h2> <ul> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <li> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>"> <?php the_title(); ?> </a>, <?php the_time('d M Y'); ?> in <?php the_category('&');?> </li> <?php endwhile; else: ?> <p> <?php _e('No posts by this author.'); ?> </p> <?php endif; ?> </ul> ```
Never, **never** re-query a native archive - use the [`pre_get_posts` hook](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) to *alter* the main query: ``` add_action( 'pre_get_posts', function ( $wp_query ) { if ( $wp_query->is_main_query() && $wp_query->is_author() ) { $paged = max( 1, ( int ) $wp_query->get( 'paged' ) ); if ( $paged === 1 ) { $wp_query->set( 'posts_per_page', 10 ); } else { $wp_query->set( 'posts_per_page', 9 ); $wp_query->set( 'offset', ( ( $paged - 1 ) * 9 ) + 1 ); } } }); ``` Add the above to your `functions.php` and remove `query_posts( ... )` line.
245,622
<p>When I enqueue Bootstrap with <code>wp_enqueue_style()</code>, Bootstrap is loaded after the child theme's <code>style.css</code> and will override <code>style.css</code>. One way to load <code>style.css</code> after Bootstrap is to enqueue <code>style.css</code> as well, but this will cause it to be loaded twice. Any idea how to enqueue <code>style.css</code> once AND after Bootstrap? Thanks!</p>
[ { "answer_id": 245623, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 2, "selected": false, "text": "<p>Good news. This is an easy fix. WordPress allows you to declare dependencies when registering scripts and stylesheets. Simply list the assets you wish to load earlier as dependencies for the later assets.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_register_style\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_register_style</a></p>\n\n<p>This works for both scripts and styles and is the recommended way to control load order.</p>\n" }, { "answer_id": 245625, "author": "bravokeyl", "author_id": 43098, "author_profile": "https://wordpress.stackexchange.com/users/43098", "pm_score": 4, "selected": true, "text": "<p>Mostly the parent theme might be enqueing the child theme's <code>style.css</code>, if so you can dequeue it by using handle and then enqueue with proper dependency.</p>\n\n<p>If the child theme's handle is <code>child-theme-style</code>, then dequeue it using</p>\n\n<p><code>wp_dequeue_style('child-theme-style')</code></p>\n\n<p>then enqueue it as needed like so.</p>\n\n<pre><code>wp_enqueue_style('child-theme-dep',get_stylesheet_uri(),array('bootstrap-handle-here'))\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/JCwUa.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/JCwUa.png\" alt=\"enter image description here\"></a></p>\n\n<p>We can easily know the child theme stylesheet url by looking at the link output in the head, for example in the attached image.</p>\n\n<pre><code>&lt;link rel='stylesheet' id='hybrid-style-css' href='https://wptavern.com/wp-content/themes/stargazer-child-dev/style.css?ver=4.6.1' type='text/css' media='all' /&gt;\n</code></pre>\n\n<p>Tells us that the child theme's enqueue handle is <code>hybrid-style</code> which is the <em><code>id</code></em> without <code>-css</code>.</p>\n" } ]
2016/11/09
[ "https://wordpress.stackexchange.com/questions/245622", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105416/" ]
When I enqueue Bootstrap with `wp_enqueue_style()`, Bootstrap is loaded after the child theme's `style.css` and will override `style.css`. One way to load `style.css` after Bootstrap is to enqueue `style.css` as well, but this will cause it to be loaded twice. Any idea how to enqueue `style.css` once AND after Bootstrap? Thanks!
Mostly the parent theme might be enqueing the child theme's `style.css`, if so you can dequeue it by using handle and then enqueue with proper dependency. If the child theme's handle is `child-theme-style`, then dequeue it using `wp_dequeue_style('child-theme-style')` then enqueue it as needed like so. ``` wp_enqueue_style('child-theme-dep',get_stylesheet_uri(),array('bootstrap-handle-here')) ``` [![enter image description here](https://i.stack.imgur.com/JCwUa.png)](https://i.stack.imgur.com/JCwUa.png) We can easily know the child theme stylesheet url by looking at the link output in the head, for example in the attached image. ``` <link rel='stylesheet' id='hybrid-style-css' href='https://wptavern.com/wp-content/themes/stargazer-child-dev/style.css?ver=4.6.1' type='text/css' media='all' /> ``` Tells us that the child theme's enqueue handle is `hybrid-style` which is the *`id`* without `-css`.
245,636
<p>I have a custom field with the key <code>colour</code> and the value can either be <code>red</code> or <code>blue</code> for individual posts.</p> <p>I know the code to return posts that are either red or blue i.e. <code>?colour=red</code>, but I don't know the code to return posts that are either red or blue i.e. <code>?colour=red&amp;colour=blue</code>.</p> <p>I have received help with the code from a user, but still not working...any assistance is gratefully received...thanks</p> <pre><code>&lt;form action ="" method="get"&gt; &lt;INPUT TYPE="checkbox" NAME="colour" VALUE="red"&gt; Red&lt;BR&gt; &lt;INPUT TYPE="checkbox" NAME="colour" VALUE="blue"&gt; Blue&lt;BR&gt; &lt;button type="submit" name=""&gt;Search&lt;/button&gt; &lt;/form&gt; &lt;?php if($_GET['colour'] &amp;&amp; !empty ($_GET['colour'])) { $colours= $_GET['colour']; } $meta_query = array('relation' =&gt; 'OR'); foreach ($colours as $colour) { $meta_query[] = array( 'key' =&gt; 'colour', 'value' =&gt; $colour, 'compare' =&gt; 'like', ); } $query = new WP_Query($args); while($query -&gt; have_posts()) : $query -&gt; the_post(); ?&gt; </code></pre>
[ { "answer_id": 245623, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 2, "selected": false, "text": "<p>Good news. This is an easy fix. WordPress allows you to declare dependencies when registering scripts and stylesheets. Simply list the assets you wish to load earlier as dependencies for the later assets.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_register_style\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_register_style</a></p>\n\n<p>This works for both scripts and styles and is the recommended way to control load order.</p>\n" }, { "answer_id": 245625, "author": "bravokeyl", "author_id": 43098, "author_profile": "https://wordpress.stackexchange.com/users/43098", "pm_score": 4, "selected": true, "text": "<p>Mostly the parent theme might be enqueing the child theme's <code>style.css</code>, if so you can dequeue it by using handle and then enqueue with proper dependency.</p>\n\n<p>If the child theme's handle is <code>child-theme-style</code>, then dequeue it using</p>\n\n<p><code>wp_dequeue_style('child-theme-style')</code></p>\n\n<p>then enqueue it as needed like so.</p>\n\n<pre><code>wp_enqueue_style('child-theme-dep',get_stylesheet_uri(),array('bootstrap-handle-here'))\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/JCwUa.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/JCwUa.png\" alt=\"enter image description here\"></a></p>\n\n<p>We can easily know the child theme stylesheet url by looking at the link output in the head, for example in the attached image.</p>\n\n<pre><code>&lt;link rel='stylesheet' id='hybrid-style-css' href='https://wptavern.com/wp-content/themes/stargazer-child-dev/style.css?ver=4.6.1' type='text/css' media='all' /&gt;\n</code></pre>\n\n<p>Tells us that the child theme's enqueue handle is <code>hybrid-style</code> which is the <em><code>id</code></em> without <code>-css</code>.</p>\n" } ]
2016/11/09
[ "https://wordpress.stackexchange.com/questions/245636", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106177/" ]
I have a custom field with the key `colour` and the value can either be `red` or `blue` for individual posts. I know the code to return posts that are either red or blue i.e. `?colour=red`, but I don't know the code to return posts that are either red or blue i.e. `?colour=red&colour=blue`. I have received help with the code from a user, but still not working...any assistance is gratefully received...thanks ``` <form action ="" method="get"> <INPUT TYPE="checkbox" NAME="colour" VALUE="red"> Red<BR> <INPUT TYPE="checkbox" NAME="colour" VALUE="blue"> Blue<BR> <button type="submit" name="">Search</button> </form> <?php if($_GET['colour'] && !empty ($_GET['colour'])) { $colours= $_GET['colour']; } $meta_query = array('relation' => 'OR'); foreach ($colours as $colour) { $meta_query[] = array( 'key' => 'colour', 'value' => $colour, 'compare' => 'like', ); } $query = new WP_Query($args); while($query -> have_posts()) : $query -> the_post(); ?> ```
Mostly the parent theme might be enqueing the child theme's `style.css`, if so you can dequeue it by using handle and then enqueue with proper dependency. If the child theme's handle is `child-theme-style`, then dequeue it using `wp_dequeue_style('child-theme-style')` then enqueue it as needed like so. ``` wp_enqueue_style('child-theme-dep',get_stylesheet_uri(),array('bootstrap-handle-here')) ``` [![enter image description here](https://i.stack.imgur.com/JCwUa.png)](https://i.stack.imgur.com/JCwUa.png) We can easily know the child theme stylesheet url by looking at the link output in the head, for example in the attached image. ``` <link rel='stylesheet' id='hybrid-style-css' href='https://wptavern.com/wp-content/themes/stargazer-child-dev/style.css?ver=4.6.1' type='text/css' media='all' /> ``` Tells us that the child theme's enqueue handle is `hybrid-style` which is the *`id`* without `-css`.
245,653
<p>I am using this code:</p> <pre><code>function the_alt_title($title= '') { $page = get_page_by_title($title); if ($p = get_post_meta($page-&gt;ID, "_x_entry_alternate_index_title", true)) { $title = $p; } return $title; } add_filter('the_title', 'the_alt_title', 10, 1); </code></pre> <p>In debug.log i get</p> <pre><code>PHP Notice: Trying to get property of non-object in /var/www/html/wp-content/themes/my-child/functions.php on this line: if ($p = get_post_meta($page-&gt;ID, "_x_entry_alternate_index_title", true)) { </code></pre> <p>How could I fix this?</p>
[ { "answer_id": 245654, "author": "ngearing", "author_id": 50184, "author_profile": "https://wordpress.stackexchange.com/users/50184", "pm_score": 3, "selected": true, "text": "<p><code>$page = get_page_by_title($title)</code> - this line is failing somewhere, so you should do a check on this to make sure it exists.</p>\n\n<p>Like so:</p>\n\n<pre><code>function the_alt_title($title= '') {\n $page = get_page_by_title($title);\n if (!$page) {\n return $title;\n }\n\n if ($p = get_post_meta($page-&gt;ID, \"_x_entry_alternate_index_title\", true)) {\n $title = $p;\n }\n\n return $title;\n}\nadd_filter('the_title', 'the_alt_title', 10, 1);\n</code></pre>\n" }, { "answer_id": 245655, "author": "Dhul Wells", "author_id": 109750, "author_profile": "https://wordpress.stackexchange.com/users/109750", "pm_score": 0, "selected": false, "text": "<p>Have to globalize page to access it. </p>\n\n<pre><code> function the_alt_title($title= '') {\n global $page; //here\n $page = get_page_by_title($title);\n if ($p = get_post_meta($page-&gt;ID, \"_x_entry_alternate_index_title\", true)) {\n $title = $p;\n }\n\n return $title;\n}\nadd_filter('the_title', 'the_alt_title', 10, 1);\n</code></pre>\n" } ]
2016/11/09
[ "https://wordpress.stackexchange.com/questions/245653", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40727/" ]
I am using this code: ``` function the_alt_title($title= '') { $page = get_page_by_title($title); if ($p = get_post_meta($page->ID, "_x_entry_alternate_index_title", true)) { $title = $p; } return $title; } add_filter('the_title', 'the_alt_title', 10, 1); ``` In debug.log i get ``` PHP Notice: Trying to get property of non-object in /var/www/html/wp-content/themes/my-child/functions.php on this line: if ($p = get_post_meta($page->ID, "_x_entry_alternate_index_title", true)) { ``` How could I fix this?
`$page = get_page_by_title($title)` - this line is failing somewhere, so you should do a check on this to make sure it exists. Like so: ``` function the_alt_title($title= '') { $page = get_page_by_title($title); if (!$page) { return $title; } if ($p = get_post_meta($page->ID, "_x_entry_alternate_index_title", true)) { $title = $p; } return $title; } add_filter('the_title', 'the_alt_title', 10, 1); ```
245,682
<p>I have a simple WP_Query to get a list of posts of co-author (taxonomy <em>author</em>) order by date, this is the query :</p> <pre class="lang-php prettyprint-override"><code>$username = get_the_author_meta( 'login', $author_id ); $args = array( 'post_type' =&gt; 'any', 'orderby' =&gt; 'date', //'orderby' =&gt; 'post_date', 'order' =&gt; 'DESC', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'author', 'field' =&gt; 'name', 'terms' =&gt; $username ) ) ); $query = new WP_Query( $args ); </code></pre> <p>The result is always a list of posts ordering by date ASC... I have already search solution over internet without success... Any idea ?</p> <p>Thanks a lot</p>
[ { "answer_id": 273835, "author": "Pravin Work", "author_id": 120969, "author_profile": "https://wordpress.stackexchange.com/users/120969", "pm_score": 5, "selected": true, "text": "<p>This will definitely work....It worked for me...</p>\n<pre class=\"lang-php prettyprint-override\"><code>$username = get_the_author_meta( 'login', $author_id );\n$args = array(\n 'post_type' =&gt; 'any',\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'DESC',\n 'suppress_filters' =&gt; true,\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'author',\n 'field' =&gt; 'name',\n 'terms' =&gt; $username\n )\n )\n);\n \n$query = new WP_Query( $args );\n</code></pre>\n" }, { "answer_id": 294234, "author": "Vital Rulinski", "author_id": 136943, "author_profile": "https://wordpress.stackexchange.com/users/136943", "pm_score": 2, "selected": false, "text": "<p>Adding</p>\n\n<pre><code>'suppress_filters' =&gt; true\n</code></pre>\n\n<p>into the <code>$args</code> array did sorting in the order I needed.</p>\n" }, { "answer_id": 385443, "author": "FlavioEscobar", "author_id": 75878, "author_profile": "https://wordpress.stackexchange.com/users/75878", "pm_score": 1, "selected": false, "text": "<p>If you're using the Post Types Order plugin, you may need to add the following to your query args:</p>\n<pre><code>'ignore_custom_sort' =&gt; true,\n</code></pre>\n" } ]
2016/11/10
[ "https://wordpress.stackexchange.com/questions/245682", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100533/" ]
I have a simple WP\_Query to get a list of posts of co-author (taxonomy *author*) order by date, this is the query : ```php $username = get_the_author_meta( 'login', $author_id ); $args = array( 'post_type' => 'any', 'orderby' => 'date', //'orderby' => 'post_date', 'order' => 'DESC', 'tax_query' => array( array( 'taxonomy' => 'author', 'field' => 'name', 'terms' => $username ) ) ); $query = new WP_Query( $args ); ``` The result is always a list of posts ordering by date ASC... I have already search solution over internet without success... Any idea ? Thanks a lot
This will definitely work....It worked for me... ```php $username = get_the_author_meta( 'login', $author_id ); $args = array( 'post_type' => 'any', 'orderby' => 'date', 'order' => 'DESC', 'suppress_filters' => true, 'tax_query' => array( array( 'taxonomy' => 'author', 'field' => 'name', 'terms' => $username ) ) ); $query = new WP_Query( $args ); ```
245,688
<p>I have a strange issue that i don't really understand, I explain : In my <code>tag.php</code>, i have an infinite scroll with custom post types thanks to the active tag and ajax.</p> <pre><code>$posts = get_posts( array( 'post_type' =&gt; 'video', 'posts_per_page' =&gt; 6, 'paged' =&gt; 1, 'post_status' =&gt; 'publish', 'post__not_in' =&gt; $posts_not_in, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'post_tag', 'field' =&gt; 'id', 'terms' =&gt; $theme-&gt;term_id, 'operator' =&gt; 'IN' ) ) )) ; </code></pre> <p>I do the same get_posts in <code>functions.php</code> in my ajax function</p> <pre><code>add_action( 'wp_ajax_get_posts_theme', 'get_posts_theme' ); add_action( 'wp_ajax_nopriv_get_posts_theme', 'get_posts_theme' ); function get_posts_theme() { ... } </code></pre> <p>and it displays differents posts results. Why ? Any ideas ? Thanks for help me.</p>
[ { "answer_id": 273835, "author": "Pravin Work", "author_id": 120969, "author_profile": "https://wordpress.stackexchange.com/users/120969", "pm_score": 5, "selected": true, "text": "<p>This will definitely work....It worked for me...</p>\n<pre class=\"lang-php prettyprint-override\"><code>$username = get_the_author_meta( 'login', $author_id );\n$args = array(\n 'post_type' =&gt; 'any',\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'DESC',\n 'suppress_filters' =&gt; true,\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'author',\n 'field' =&gt; 'name',\n 'terms' =&gt; $username\n )\n )\n);\n \n$query = new WP_Query( $args );\n</code></pre>\n" }, { "answer_id": 294234, "author": "Vital Rulinski", "author_id": 136943, "author_profile": "https://wordpress.stackexchange.com/users/136943", "pm_score": 2, "selected": false, "text": "<p>Adding</p>\n\n<pre><code>'suppress_filters' =&gt; true\n</code></pre>\n\n<p>into the <code>$args</code> array did sorting in the order I needed.</p>\n" }, { "answer_id": 385443, "author": "FlavioEscobar", "author_id": 75878, "author_profile": "https://wordpress.stackexchange.com/users/75878", "pm_score": 1, "selected": false, "text": "<p>If you're using the Post Types Order plugin, you may need to add the following to your query args:</p>\n<pre><code>'ignore_custom_sort' =&gt; true,\n</code></pre>\n" } ]
2016/11/10
[ "https://wordpress.stackexchange.com/questions/245688", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106689/" ]
I have a strange issue that i don't really understand, I explain : In my `tag.php`, i have an infinite scroll with custom post types thanks to the active tag and ajax. ``` $posts = get_posts( array( 'post_type' => 'video', 'posts_per_page' => 6, 'paged' => 1, 'post_status' => 'publish', 'post__not_in' => $posts_not_in, 'tax_query' => array( array( 'taxonomy' => 'post_tag', 'field' => 'id', 'terms' => $theme->term_id, 'operator' => 'IN' ) ) )) ; ``` I do the same get\_posts in `functions.php` in my ajax function ``` add_action( 'wp_ajax_get_posts_theme', 'get_posts_theme' ); add_action( 'wp_ajax_nopriv_get_posts_theme', 'get_posts_theme' ); function get_posts_theme() { ... } ``` and it displays differents posts results. Why ? Any ideas ? Thanks for help me.
This will definitely work....It worked for me... ```php $username = get_the_author_meta( 'login', $author_id ); $args = array( 'post_type' => 'any', 'orderby' => 'date', 'order' => 'DESC', 'suppress_filters' => true, 'tax_query' => array( array( 'taxonomy' => 'author', 'field' => 'name', 'terms' => $username ) ) ); $query = new WP_Query( $args ); ```
245,702
<p>I have <code>current_time</code> in theme and it displays date like: <code>THURSDAY, NOVEMBER 10, 2016</code>. But I need to translate it to Persian. How can I do this?</p>
[ { "answer_id": 245705, "author": "Demyd Ganenko", "author_id": 88455, "author_profile": "https://wordpress.stackexchange.com/users/88455", "pm_score": 3, "selected": true, "text": "<p>Used <code>date_i18n</code> instead of <code>current_time</code>. For example:</p>\n\n<pre><code>echo date_i18n( 'Y. F j.', strtotime( get_the_time( \"Y-m-d\" ) ) );\n</code></pre>\n" }, { "answer_id": 245706, "author": "chrismou", "author_id": 8960, "author_profile": "https://wordpress.stackexchange.com/users/8960", "pm_score": 1, "selected": false, "text": "<p>It may be worth looking at using something like <code>date_i18n</code>, which returns the date/time in a localised format</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/date_i18n\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/date_i18n</a></p>\n\n<p>To recreate the current_time format you showed in your example, you could use something like <code>date_i18n('l, F j, Y');</code></p>\n" } ]
2016/11/10
[ "https://wordpress.stackexchange.com/questions/245702", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88455/" ]
I have `current_time` in theme and it displays date like: `THURSDAY, NOVEMBER 10, 2016`. But I need to translate it to Persian. How can I do this?
Used `date_i18n` instead of `current_time`. For example: ``` echo date_i18n( 'Y. F j.', strtotime( get_the_time( "Y-m-d" ) ) ); ```
245,724
<p>Im using the following code on my WordPress custom theme home page to display the latest three portfolio posts:</p> <pre><code>&lt;?php query_posts('post_type=portfolio&amp;showposts=3'); ?&gt; &lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;div class="col-lg-4 col-md-4 col-sm-12 col-xs-12" &lt;?php post_class() ?&gt; id="post-&lt;?php the_ID(); ?&gt;"&gt; &lt;a href="&lt;?php the_permalink() ?&gt;" class="portfolio-box"&gt; &lt;?php if ( has_post_thumbnail() ) { $image_src = wp_get_attachment_image_src( get_post_thumbnail_id(),’thumbnail’ ); echo '&lt;img width="100%" src="'.$image_src[0].'" alt="'.$image_alt.'" title="'.$image_title.'"&gt;'; } else { ?&gt; &lt;img src="&lt;?php bloginfo('template_directory'); ?&gt;/img/fallback.jpg" class="img-responsive" /&gt; &lt;?php } ?&gt; &lt;div class="portfolio-box-caption portfolio-box-caption-blue"&gt; &lt;div class="portfolio-box-caption-content"&gt; &lt;div class="project-category text-faded"&gt; &lt;!-- &lt;?php the_category( ', ' ); ?&gt; --&gt; &lt;/div&gt; &lt;div class="project-name-work"&gt; &lt;?php the_title(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;?php endwhile; endif; ?&gt; </code></pre> <p>However the image alt text isn't appearing the in the final page source. Could someone be kind enough to show me where I've gone wrong?</p> <p>Thanks</p>
[ { "answer_id": 245705, "author": "Demyd Ganenko", "author_id": 88455, "author_profile": "https://wordpress.stackexchange.com/users/88455", "pm_score": 3, "selected": true, "text": "<p>Used <code>date_i18n</code> instead of <code>current_time</code>. For example:</p>\n\n<pre><code>echo date_i18n( 'Y. F j.', strtotime( get_the_time( \"Y-m-d\" ) ) );\n</code></pre>\n" }, { "answer_id": 245706, "author": "chrismou", "author_id": 8960, "author_profile": "https://wordpress.stackexchange.com/users/8960", "pm_score": 1, "selected": false, "text": "<p>It may be worth looking at using something like <code>date_i18n</code>, which returns the date/time in a localised format</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/date_i18n\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/date_i18n</a></p>\n\n<p>To recreate the current_time format you showed in your example, you could use something like <code>date_i18n('l, F j, Y');</code></p>\n" } ]
2016/11/10
[ "https://wordpress.stackexchange.com/questions/245724", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106714/" ]
Im using the following code on my WordPress custom theme home page to display the latest three portfolio posts: ``` <?php query_posts('post_type=portfolio&showposts=3'); ?> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="col-lg-4 col-md-4 col-sm-12 col-xs-12" <?php post_class() ?> id="post-<?php the_ID(); ?>"> <a href="<?php the_permalink() ?>" class="portfolio-box"> <?php if ( has_post_thumbnail() ) { $image_src = wp_get_attachment_image_src( get_post_thumbnail_id(),’thumbnail’ ); echo '<img width="100%" src="'.$image_src[0].'" alt="'.$image_alt.'" title="'.$image_title.'">'; } else { ?> <img src="<?php bloginfo('template_directory'); ?>/img/fallback.jpg" class="img-responsive" /> <?php } ?> <div class="portfolio-box-caption portfolio-box-caption-blue"> <div class="portfolio-box-caption-content"> <div class="project-category text-faded"> <!-- <?php the_category( ', ' ); ?> --> </div> <div class="project-name-work"> <?php the_title(); ?> </div> </div> </div> </a> </div> <?php endwhile; endif; ?> ``` However the image alt text isn't appearing the in the final page source. Could someone be kind enough to show me where I've gone wrong? Thanks
Used `date_i18n` instead of `current_time`. For example: ``` echo date_i18n( 'Y. F j.', strtotime( get_the_time( "Y-m-d" ) ) ); ```
245,728
<p>I have installed a compressing plugin (<a href="https://wordpress.org/plugins/tiny-compress-images/" rel="nofollow noreferrer">https://wordpress.org/plugins/tiny-compress-images/</a>) in Wordpress to minimize the file size of all the images that I upload. Works really well, the only problem is the following:</p> <p>If I create a new page, insert a picture and resize it manually in the editor Wordpress seems to create a new version of the picture with exactly the resolution that I have chosen. For instance I have a newly created file called airline-768x447.png in my uploads folder that was apparently created by Wordpress when I resized the original image in the editor to this size.</p> <p>The problem is that this newly created file doesn't get compressed by the plugin and therefore its file size is way bigger than it should be.</p> <p>Why isn't wordpress just using the original file and just resizes it using css or the width and height attributes? Is there any option to turn off this behavior where Wordpress seems to create images with individual size?</p> <p>I have searched for quite a while but couldn't find any solutions. Thanks :)</p>
[ { "answer_id": 245705, "author": "Demyd Ganenko", "author_id": 88455, "author_profile": "https://wordpress.stackexchange.com/users/88455", "pm_score": 3, "selected": true, "text": "<p>Used <code>date_i18n</code> instead of <code>current_time</code>. For example:</p>\n\n<pre><code>echo date_i18n( 'Y. F j.', strtotime( get_the_time( \"Y-m-d\" ) ) );\n</code></pre>\n" }, { "answer_id": 245706, "author": "chrismou", "author_id": 8960, "author_profile": "https://wordpress.stackexchange.com/users/8960", "pm_score": 1, "selected": false, "text": "<p>It may be worth looking at using something like <code>date_i18n</code>, which returns the date/time in a localised format</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/date_i18n\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/date_i18n</a></p>\n\n<p>To recreate the current_time format you showed in your example, you could use something like <code>date_i18n('l, F j, Y');</code></p>\n" } ]
2016/11/10
[ "https://wordpress.stackexchange.com/questions/245728", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106713/" ]
I have installed a compressing plugin (<https://wordpress.org/plugins/tiny-compress-images/>) in Wordpress to minimize the file size of all the images that I upload. Works really well, the only problem is the following: If I create a new page, insert a picture and resize it manually in the editor Wordpress seems to create a new version of the picture with exactly the resolution that I have chosen. For instance I have a newly created file called airline-768x447.png in my uploads folder that was apparently created by Wordpress when I resized the original image in the editor to this size. The problem is that this newly created file doesn't get compressed by the plugin and therefore its file size is way bigger than it should be. Why isn't wordpress just using the original file and just resizes it using css or the width and height attributes? Is there any option to turn off this behavior where Wordpress seems to create images with individual size? I have searched for quite a while but couldn't find any solutions. Thanks :)
Used `date_i18n` instead of `current_time`. For example: ``` echo date_i18n( 'Y. F j.', strtotime( get_the_time( "Y-m-d" ) ) ); ```
245,730
<p>I'm getting this error when I imported the dummy data through WP importer.can any tell me what is the problem. </p> <p><a href="https://i.stack.imgur.com/D9V1v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D9V1v.png" alt="enter image description here"></a></p>
[ { "answer_id": 245732, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>The screenshot states the problem clearly:</p>\n\n<pre><code>Maximum execution time of 60 seconds exceeded\n</code></pre>\n\n<p>Pages have a time limit inside which they need to do their work, otherwise a badly written PHP script could run forever.</p>\n\n<p>This is why importing huge data sets runs into this problem. The bigger the import, the longer it takes, but your server only allows 60 seconds to do this in. You could bump up the limit but that will cause other issues and this might not be possible with your host. Some of the largest imports I've seen can take days</p>\n\n<p>Instead, for anything but the smallest imports:</p>\n\n<ul>\n<li>Split your export into chunks, multiple files at 5MB each, use the WP CLI exporter to do this</li>\n<li>Import via WP CLI, there is no time limit for terminal commands</li>\n</ul>\n\n<p>However for a hosting company, unless you can get access to WP CLI, doing what you're doing now will not work and there are no workarounds to make the browser importer screen work with medium to large imports. You may even struggle with small imports if it's shared hosting, and the results will be unreliable. What might work now may fail in a minutes time as the server gets busier and pages load slower</p>\n" }, { "answer_id": 245735, "author": "Ranuka", "author_id": 106350, "author_profile": "https://wordpress.stackexchange.com/users/106350", "pm_score": 0, "selected": false, "text": "<p>The error is \"Maximum execution time of 60 seconds exceeded\". \nYou can increase the maximum execution time using php.ini file.</p>\n\n<p>Then change <code>max_execution_time</code> = 60 line to max_execution_time = 180 or something.</p>\n\n<p><a href=\"https://i.stack.imgur.com/dBmSk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dBmSk.png\" alt=\"enter image description here\"></a></p>\n" } ]
2016/11/10
[ "https://wordpress.stackexchange.com/questions/245730", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105528/" ]
I'm getting this error when I imported the dummy data through WP importer.can any tell me what is the problem. [![enter image description here](https://i.stack.imgur.com/D9V1v.png)](https://i.stack.imgur.com/D9V1v.png)
The screenshot states the problem clearly: ``` Maximum execution time of 60 seconds exceeded ``` Pages have a time limit inside which they need to do their work, otherwise a badly written PHP script could run forever. This is why importing huge data sets runs into this problem. The bigger the import, the longer it takes, but your server only allows 60 seconds to do this in. You could bump up the limit but that will cause other issues and this might not be possible with your host. Some of the largest imports I've seen can take days Instead, for anything but the smallest imports: * Split your export into chunks, multiple files at 5MB each, use the WP CLI exporter to do this * Import via WP CLI, there is no time limit for terminal commands However for a hosting company, unless you can get access to WP CLI, doing what you're doing now will not work and there are no workarounds to make the browser importer screen work with medium to large imports. You may even struggle with small imports if it's shared hosting, and the results will be unreliable. What might work now may fail in a minutes time as the server gets busier and pages load slower
245,751
<p>I have an existing for loop, which is necessary for the design and layout. Inside this for loop I need show post by post.</p> <p>This is my code.</p> <pre><code>&lt;?php for($i=$val;$i&lt;=$cdn;$i++) { ?&gt; &lt;div class="desc dsc&lt;?php echo $dsc++; ?&gt;" style="display: none"&gt; &lt;div class="team-details"&gt; &lt;div class="name"&gt; &lt;?php echo get_the_title();?&gt;&lt;span&gt;&lt;?php the_field('designation'); ?&gt;&lt;/span&gt; &lt;/div&gt; &lt;?php get_template_part( 'post', 'content'); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p>I need to get each post inside this for loop without affecting the structure. Please help</p> <p>This is my full page code</p> <pre><code>&lt;?php //Template Name: File get_header(); get_template_part( 'weblizar', 'breadcrumbs'); ?&gt; &lt;div class="container"&gt; &lt;h2 class="title wow fadeIn" data-wow-duration="1s" data-wow-delay="0.5s"&gt;Meet our Team&lt;/h2&gt; &lt;div class="content team-content wow fadeIn" data-wow-duration="1s" data-wow-delay="0.6s"&gt; &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt; &lt;?php get_template_part( 'post', 'content'); endwhile; else : get_template_part( 'nocontent'); endif; get_template_part( 'post-author'); ?&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;?php //comments_template( '',true); ?&gt; &lt;div class="clearfix mar_top2"&gt;&lt;/div&gt; &lt;/div&gt; &lt;section&gt; &lt;div class="team-list-wrapper clearfix wow fadeInUp" data-wow-duration="1s" data-wow-delay="0.5s"&gt; &lt;?php wp_reset_query(); ?&gt; &lt;!-- Set Category Name to Portfolio-Item --&gt; &lt;?php query_posts( array ( 'post_type'=&gt;'our-team', 'posts_per_page' =&gt; -1 ) ); ?&gt; &lt;!-- Start WordPress Loop --&gt; &lt;?php $count=0; $dsc=0 ; $ids=0 ; ?&gt; &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt; &lt;?php if ($count==0) : ?&gt; &lt;ul id="co-team"&gt; &lt;?php endif; ?&gt; &lt;?php if ($ids==3) : $val=0 ; $cdn=3 ; endif; ?&gt; &lt;?php if ($ids==7) : $val=3 ; $cdn=6 ; endif; ?&gt; &lt;?php if ($ids==11) : $val=7 ; $cdn=10; endif; ?&gt; &lt;?php if ($ids&gt;11) : $val = 11; $cdn =14; endif; ?&gt; &lt;li class="nav team-list"&gt; &lt;img src="&lt;?php echo wp_get_attachment_url( get_post_thumbnail_id());?&gt;" title="&lt;?php echo get_the_title();?&gt;" alt="&lt;?php echo get_the_title();?&gt;"&gt; &lt;div class="hover-item ids&lt;?php echo $ids++; ?&gt;"&gt; &lt;div class="actv-desc"&gt; &lt;div class="team-details"&gt; &lt;div class="name"&gt; &lt;?php echo get_the_title();?&gt;&lt;span&gt;&lt;?php the_field('designation'); ?&gt;&lt;/span&gt; &lt;/div&gt; &lt;?php get_template_part( 'post', 'content'); ?&gt; &lt;/div&gt; &lt;?php $id=g et_field( 'facebook'); $id1=g et_field( 'twitter'); $id2=g et_field( 'linkedin'); $id3=g et_field( 'gplus'); $id4=g et_field( 'youtube'); if(!empty($id) || !empty($id1) || !empty($id2) || !empty($id3) || !empty($id4) ) { ?&gt; &lt;div class="social-medias-holder"&gt; &lt;ul class="social-medias"&gt; &lt;?php if( get_field( 'facebook') ): ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_field('facebook'); ?&gt;"&gt;&lt;i class="fa fa-facebook" aria-hidden="true"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/li&gt; &lt;?php endif; ?&gt; &lt;?php if( get_field( 'twitter') ): ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_field('twitter'); ?&gt;"&gt;&lt;i class="fa fa-twitter" aria-hidden="true"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/li&gt; &lt;?php endif; ?&gt; &lt;?php if( get_field( 'linkedin') ): ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_field('linkedin'); ?&gt;"&gt;&lt;i class="fa fa-linkedin" aria-hidden="true"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/li&gt; &lt;?php endif; ?&gt; &lt;?php if( get_field( 'gplus') ): ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_field('gplus'); ?&gt;"&gt;&lt;i class="fa fa-google-plus" aria-hidden="true"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/li&gt; &lt;?php endif; ?&gt; &lt;?php if( get_field( 'youtube') ): ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_field('youtube'); ?&gt;"&gt;&lt;i class="fa fa-youtube" aria-hidden="true"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/li&gt; &lt;?php endif; ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/li&gt; &lt;?php $count++; ?&gt; &lt;?php if ($count==4 ||$wp_query-&gt;found_posts==0) : ?&gt; &lt;?php $count=0; ?&gt; &lt;/ul&gt; &lt;style&gt; .desc{ background: #000; } &lt;/style&gt; &lt;?php echo $cdn; for($i=$val;$i&lt;=$cdn;$i++) { ?&gt; &lt;div class="desc dsc&lt;?php echo $dsc++; ?&gt;" style="display: none"&gt; &lt;?php echo $post_id; ?&gt; &lt;div class="team-details"&gt; &lt;div class="name"&gt; &lt;?php echo get_the_title($post_id);?&gt;&lt;span&gt;&lt;?php the_field('designation',$post_id); ?&gt;&lt;/span&gt; &lt;/div&gt; &lt;?php get_template_part( 'post', 'content'); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;?php endif; ?&gt; &lt;?php endwhile; ?&gt; &lt;?php endif; ?&gt; &lt;?php wp_reset_query(); ?&gt; &lt;/div&gt; &lt;!-- Tab panes --&gt; &lt;/section&gt; &lt;/div&gt; &lt;div id="foot-btn"&gt; &lt;div class="container"&gt; &lt;div class="hi-icon-wrap hi-icon-effect-6 " title="Join FIFI"&gt; &lt;a href="http://www.studiofifi.com/careers/" id="open-event" class="hi-icon hi-icon-contract "&gt;Contract&lt;/a&gt; &lt;/div&gt; &lt;div class="arrow_box"&gt; &lt;a href="http://www.studiofifi.com/careers/" class="up-arrow"&gt; Join FIFI&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script&gt; $(document).ready(function() { $('.tooltip').tooltipster({ animation: 'grow', delay: 200, theme: 'tooltipster-punk', trigger: 'hover' }); $('.ids0').click(function() { $('.dsc0').toggle( "slow" ); }); $('.ids1').click(function() { $('.dsc1').toggle( "slow" ); }); $('.ids2').click(function() { $('.dsc2').toggle( "slow" ); }); $('.ids3').click(function() { $('.dsc3').toggle( "slow" ); }); $('.ids4').click(function() { $('.dsc4').toggle( "slow" ); }); $('.ids5').click(function() { $('.dsc5').toggle( "slow" ); }); $('.ids6').click(function() { $('.dsc6').toggle( "slow" ); }); $('.ids7').click(function() { $('.dsc7').toggle( "slow" ); }); $('.ids8').click(function() { $('.dsc8').toggle( "slow" ); }); $('.ids9').click(function() { $('.dsc9').toggle( "slow" ); }); $('.ids10').click(function() { $('.dsc10').toggle( "slow" ); }); $('.ids11').click(function() { $('.dsc11').toggle( "slow" ); }); $('.ids12').click(function() { $('.dsc12').toggle( "slow" ); }); $('.ids13').click(function() { $('.dsc13').toggle( "slow" ); }); $('.ids14').click(function() { $('.dsc14').toggle( "slow" ); }); $('.ids15').click(function() { $('.dsc15').toggle( "slow" ); }); // }); &lt;/script&gt; &lt;?php get_footer(); ?&gt; </code></pre>
[ { "answer_id": 245754, "author": "elicohenator", "author_id": 98507, "author_profile": "https://wordpress.stackexchange.com/users/98507", "pm_score": 0, "selected": false, "text": "<p>You should seperate the number you're 'echoing' from the loop. here's an example from a recent site I've built: </p>\n\n<pre><code>&lt;?php $startnum = 1;\n$the_query = new WP_Query( array( 'cat' =&gt; 2 ) );\nwhile ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); ?&gt;\n&lt;div class=\"section-number-&lt;?php echo $startnum; ?&gt;\"&gt;\n\n &lt;h1&gt;the_title()&lt;/h1&gt;\n &lt;div&gt;the_content()&lt;/div&gt;\n\n&lt;/div&gt;\n&lt;?php \n$startnum++;\nendwhile;\nwp_reset_postdata(); ?&gt;\n</code></pre>\n" }, { "answer_id": 245757, "author": "MW247", "author_id": 64246, "author_profile": "https://wordpress.stackexchange.com/users/64246", "pm_score": 2, "selected": false, "text": "<p>If you're looking to get the post id to say add it to a div use the_ID()</p>\n\n<pre><code>&lt;div id=\"post-&lt;?php the_ID(); ?&gt;\"&gt;\n</code></pre>\n" }, { "answer_id": 245760, "author": "Jen", "author_id": 13810, "author_profile": "https://wordpress.stackexchange.com/users/13810", "pm_score": 1, "selected": false, "text": "<p>Move the toggle-able code inside the main loop; put it inside the <code>hover-item</code> div. Get rid of all of the counting variables - $dsc, $ids, $cdn. Something like this:</p>\n\n<pre><code>&lt;li class=\"nav team-list\"&gt;\n &lt;img src=\"&lt;?php echo wp_get_attachment_url( get_post_thumbnail_id());?&gt;\" title=\"&lt;?php echo get_the_title();?&gt;\" alt=\"&lt;?php echo get_the_title();?&gt;\"&gt;\n &lt;div class=\"hover-item ids\"&gt;\n &lt;div class=\"actv-desc\"&gt;\n &lt;div class=\"team-details\"&gt;\n &lt;div class=\"name\"&gt;\n &lt;?php echo get_the_title();?&gt;&lt;span&gt;&lt;?php the_field('designation'); ?&gt;&lt;/span&gt;\n &lt;/div&gt;\n &lt;?php get_template_part( 'post', 'content'); ?&gt;\n &lt;/div&gt;\n &lt;div class=\"social-medias-holder\"&gt;\n &lt;!-- this stuff --&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n\n &lt;div class=\"desc\" style=\"display: none\"&gt;\n &lt;div class=\"team-details\"&gt;\n &lt;div class=\"name\"&gt;\n &lt;?php echo get_the_title();?&gt;&lt;span&gt;&lt;?php the_field('designation'); ?&gt;&lt;/span&gt;\n &lt;/div&gt;\n &lt;?php get_template_part( 'post', 'content'); ?&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/li&gt;\n</code></pre>\n\n<p>Change the class for the .hover-item.ids1 (ect) to not have a number on it, just:</p>\n\n<pre><code>&lt;div class=\"hover-item ids\"&gt;\n</code></pre>\n\n<p>Update the script at the bottom to get rid of all the repeated stuff, and rewrite it like this:</p>\n\n<pre><code>$('.ids').click(function() { \n var $toggleable = $(this).find('.desc');\n $toggleable.toggle( \"slow\" );\n});\n</code></pre>\n\n<p>You'll probably need to change how your css styles work because of how the html structure is changing.</p>\n" } ]
2016/11/10
[ "https://wordpress.stackexchange.com/questions/245751", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77627/" ]
I have an existing for loop, which is necessary for the design and layout. Inside this for loop I need show post by post. This is my code. ``` <?php for($i=$val;$i<=$cdn;$i++) { ?> <div class="desc dsc<?php echo $dsc++; ?>" style="display: none"> <div class="team-details"> <div class="name"> <?php echo get_the_title();?><span><?php the_field('designation'); ?></span> </div> <?php get_template_part( 'post', 'content'); ?> </div> </div> <?php } ?> ``` I need to get each post inside this for loop without affecting the structure. Please help This is my full page code ``` <?php //Template Name: File get_header(); get_template_part( 'weblizar', 'breadcrumbs'); ?> <div class="container"> <h2 class="title wow fadeIn" data-wow-duration="1s" data-wow-delay="0.5s">Meet our Team</h2> <div class="content team-content wow fadeIn" data-wow-duration="1s" data-wow-delay="0.6s"> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'post', 'content'); endwhile; else : get_template_part( 'nocontent'); endif; get_template_part( 'post-author'); ?> <div class="clearfix"></div> <?php //comments_template( '',true); ?> <div class="clearfix mar_top2"></div> </div> <section> <div class="team-list-wrapper clearfix wow fadeInUp" data-wow-duration="1s" data-wow-delay="0.5s"> <?php wp_reset_query(); ?> <!-- Set Category Name to Portfolio-Item --> <?php query_posts( array ( 'post_type'=>'our-team', 'posts_per_page' => -1 ) ); ?> <!-- Start WordPress Loop --> <?php $count=0; $dsc=0 ; $ids=0 ; ?> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php if ($count==0) : ?> <ul id="co-team"> <?php endif; ?> <?php if ($ids==3) : $val=0 ; $cdn=3 ; endif; ?> <?php if ($ids==7) : $val=3 ; $cdn=6 ; endif; ?> <?php if ($ids==11) : $val=7 ; $cdn=10; endif; ?> <?php if ($ids>11) : $val = 11; $cdn =14; endif; ?> <li class="nav team-list"> <img src="<?php echo wp_get_attachment_url( get_post_thumbnail_id());?>" title="<?php echo get_the_title();?>" alt="<?php echo get_the_title();?>"> <div class="hover-item ids<?php echo $ids++; ?>"> <div class="actv-desc"> <div class="team-details"> <div class="name"> <?php echo get_the_title();?><span><?php the_field('designation'); ?></span> </div> <?php get_template_part( 'post', 'content'); ?> </div> <?php $id=g et_field( 'facebook'); $id1=g et_field( 'twitter'); $id2=g et_field( 'linkedin'); $id3=g et_field( 'gplus'); $id4=g et_field( 'youtube'); if(!empty($id) || !empty($id1) || !empty($id2) || !empty($id3) || !empty($id4) ) { ?> <div class="social-medias-holder"> <ul class="social-medias"> <?php if( get_field( 'facebook') ): ?> <li><a href="<?php the_field('facebook'); ?>"><i class="fa fa-facebook" aria-hidden="true"></i></a> </li> <?php endif; ?> <?php if( get_field( 'twitter') ): ?> <li><a href="<?php the_field('twitter'); ?>"><i class="fa fa-twitter" aria-hidden="true"></i></a> </li> <?php endif; ?> <?php if( get_field( 'linkedin') ): ?> <li><a href="<?php the_field('linkedin'); ?>"><i class="fa fa-linkedin" aria-hidden="true"></i></a> </li> <?php endif; ?> <?php if( get_field( 'gplus') ): ?> <li><a href="<?php the_field('gplus'); ?>"><i class="fa fa-google-plus" aria-hidden="true"></i></a> </li> <?php endif; ?> <?php if( get_field( 'youtube') ): ?> <li><a href="<?php the_field('youtube'); ?>"><i class="fa fa-youtube" aria-hidden="true"></i></a> </li> <?php endif; ?> </ul> </div> <?php } ?> </div> </div> </li> <?php $count++; ?> <?php if ($count==4 ||$wp_query->found_posts==0) : ?> <?php $count=0; ?> </ul> <style> .desc{ background: #000; } </style> <?php echo $cdn; for($i=$val;$i<=$cdn;$i++) { ?> <div class="desc dsc<?php echo $dsc++; ?>" style="display: none"> <?php echo $post_id; ?> <div class="team-details"> <div class="name"> <?php echo get_the_title($post_id);?><span><?php the_field('designation',$post_id); ?></span> </div> <?php get_template_part( 'post', 'content'); ?> </div> </div> <?php } ?> <?php endif; ?> <?php endwhile; ?> <?php endif; ?> <?php wp_reset_query(); ?> </div> <!-- Tab panes --> </section> </div> <div id="foot-btn"> <div class="container"> <div class="hi-icon-wrap hi-icon-effect-6 " title="Join FIFI"> <a href="http://www.studiofifi.com/careers/" id="open-event" class="hi-icon hi-icon-contract ">Contract</a> </div> <div class="arrow_box"> <a href="http://www.studiofifi.com/careers/" class="up-arrow"> Join FIFI</a> </div> </div> </div> <script> $(document).ready(function() { $('.tooltip').tooltipster({ animation: 'grow', delay: 200, theme: 'tooltipster-punk', trigger: 'hover' }); $('.ids0').click(function() { $('.dsc0').toggle( "slow" ); }); $('.ids1').click(function() { $('.dsc1').toggle( "slow" ); }); $('.ids2').click(function() { $('.dsc2').toggle( "slow" ); }); $('.ids3').click(function() { $('.dsc3').toggle( "slow" ); }); $('.ids4').click(function() { $('.dsc4').toggle( "slow" ); }); $('.ids5').click(function() { $('.dsc5').toggle( "slow" ); }); $('.ids6').click(function() { $('.dsc6').toggle( "slow" ); }); $('.ids7').click(function() { $('.dsc7').toggle( "slow" ); }); $('.ids8').click(function() { $('.dsc8').toggle( "slow" ); }); $('.ids9').click(function() { $('.dsc9').toggle( "slow" ); }); $('.ids10').click(function() { $('.dsc10').toggle( "slow" ); }); $('.ids11').click(function() { $('.dsc11').toggle( "slow" ); }); $('.ids12').click(function() { $('.dsc12').toggle( "slow" ); }); $('.ids13').click(function() { $('.dsc13').toggle( "slow" ); }); $('.ids14').click(function() { $('.dsc14').toggle( "slow" ); }); $('.ids15').click(function() { $('.dsc15').toggle( "slow" ); }); // }); </script> <?php get_footer(); ?> ```
If you're looking to get the post id to say add it to a div use the\_ID() ``` <div id="post-<?php the_ID(); ?>"> ```
245,769
<p>I want to ger several recent posts. So I use wp_get_recent_posts. But I get only first image.</p> <pre><code>&lt;?php $args = array( 'numberposts' =&gt; '3' ); $recent_posts = wp_get_recent_posts($args); foreach( $recent_posts as $recent ){ echo '&lt;li&gt;&lt;a href="' . get_permalink($recent["ID"]) . '"&gt;' . $recent["post_title"].'&lt;/a&gt; &lt;/li&gt; '; if ( has_post_thumbnail() ) { the_post_thumbnail('thumbnail'); } } ?&gt; </code></pre>
[ { "answer_id": 245772, "author": "Syed Fakhar Abbas", "author_id": 90591, "author_profile": "https://wordpress.stackexchange.com/users/90591", "pm_score": 4, "selected": true, "text": "<p>Actually, the condition is always returning false because you are not passing the post id to the function <a href=\"https://developer.wordpress.org/reference/functions/has_post_thumbnail/\" rel=\"noreferrer\"><code>has_post_thumbnail()</code></a> and the function always getting the default value which is <code>null</code>. </p>\n\n<p><code>has_post_thumbnail( $recent[\"ID\"] )</code>.</p>\n\n<p>Same with the function <a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/\" rel=\"noreferrer\"><code>get_the_post_thumbnail()</code></a>.</p>\n\n<p><code>get_the_post_thumbnail( $recent[\"ID\"] )</code>.</p>\n\n<pre><code>\n$args = array( 'numberposts' => '3' );\n\n$recent_posts = wp_get_recent_posts($args);\n\nforeach( $recent_posts as $recent ){\n if ( has_post_thumbnail( $recent[\"ID\"]) ) {\n echo get_the_post_thumbnail($recent[\"ID\"],'thumbnail');\n }\n}</code></pre>\n\n<p>But if you use the functions <code>has_post_thumbnail();</code> and <code>get_the_post_thumbnail()</code> inside the WordPress <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"noreferrer\"><code>The_Loop</code></a> then you don't need to pass the post id.</p>\n\n<pre><code>\n$args = array( 'posts_per_page' => '3' );\n$recent_posts = new WP_Query($args);\nwhile( $recent_posts->have_posts() ) { \n\n $recent_posts->the_post() ; \n\n if ( has_post_thumbnail() ) {\n echo get_the_post_thumbnail();\n }\n}\n\nwp_reset_postdata();\n</code></pre>\n" }, { "answer_id": 245773, "author": "Jen", "author_id": 13810, "author_profile": "https://wordpress.stackexchange.com/users/13810", "pm_score": 2, "selected": false, "text": "<p>In order to use <code>the_post_thumbnail</code>, you need to initialize a loop. So more like this: </p>\n\n<pre><code>&lt;?php \n$args = array( 'posts_per_page' =&gt; '3' );\n$recent_posts = new WP_Query($args);\nwhile( $recent_posts-&gt;have_posts() ) : \n $recent_posts-&gt;the_post() ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php echo get_permalink() ?&gt;\"&gt;&lt;?php the_title() ?&gt;&lt;/a&gt; \n &lt;?php if ( has_post_thumbnail() ) : ?&gt;\n &lt;?php the_post_thumbnail('thumbnail') ?&gt;\n &lt;?php endif ?&gt; \n &lt;/li&gt;\n&lt;?php endwhile; ?&gt;\n&lt;?php wp_reset_postdata(); # reset post data so that other queries/loops work ?&gt; \n</code></pre>\n\n<p>(I put the thumbnail inside the <code>&lt;li&gt;</code> tags because anything besides <code>&lt;li&gt;</code> inside a <code>&lt;ol&gt;</code> or <code>&lt;ul&gt;</code> is invalid html.)</p>\n" } ]
2016/11/10
[ "https://wordpress.stackexchange.com/questions/245769", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103556/" ]
I want to ger several recent posts. So I use wp\_get\_recent\_posts. But I get only first image. ``` <?php $args = array( 'numberposts' => '3' ); $recent_posts = wp_get_recent_posts($args); foreach( $recent_posts as $recent ){ echo '<li><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</a> </li> '; if ( has_post_thumbnail() ) { the_post_thumbnail('thumbnail'); } } ?> ```
Actually, the condition is always returning false because you are not passing the post id to the function [`has_post_thumbnail()`](https://developer.wordpress.org/reference/functions/has_post_thumbnail/) and the function always getting the default value which is `null`. `has_post_thumbnail( $recent["ID"] )`. Same with the function [`get_the_post_thumbnail()`](https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/). `get_the_post_thumbnail( $recent["ID"] )`. ``` $args = array( 'numberposts' => '3' ); $recent_posts = wp_get_recent_posts($args); foreach( $recent_posts as $recent ){ if ( has_post_thumbnail( $recent["ID"]) ) { echo get_the_post_thumbnail($recent["ID"],'thumbnail'); } } ``` But if you use the functions `has_post_thumbnail();` and `get_the_post_thumbnail()` inside the WordPress [`The_Loop`](https://codex.wordpress.org/The_Loop) then you don't need to pass the post id. ``` $args = array( 'posts_per_page' => '3' ); $recent_posts = new WP_Query($args); while( $recent_posts->have_posts() ) { $recent_posts->the_post() ; if ( has_post_thumbnail() ) { echo get_the_post_thumbnail(); } } wp_reset_postdata(); ```
245,817
<p>I'd like to remove the "Powered by Wordpress" custom link in the footer. </p> <p>I want to do this using action hooks/filters in the child theme's <code>function.php</code> file.</p> <p>I don't want to use CSS (which just hides it), edit the original theme file (which will get overriden when the theme updates), or copy the <code>footer.php</code> file to the child theme and edit it out there (since I will then have to update the file after a theme update).</p> <p>The theme I'm using is 'sparkling'. The footer info function is defined in the <code>extras.php</code> file:</p> <pre><code>function sparkling_footer_info() { global $sparkling_footer_info; printf( esc_html__( 'Theme by %1$s Powered by %2$s', 'sparkling' ) , '&lt;a href="http://colorlib.com/" target="_blank"&gt;Colorlib&lt;/a&gt;', '&lt;a href="http://wordpress.org/" target="_blank"&gt;WordPress&lt;/a&gt;'); } </code></pre> <p>And called in the footer.php file (a few lines from the bottom):</p> <pre><code>&lt;div id="footer-area"&gt; &lt;div class="container footer-inner"&gt; &lt;div class="row"&gt; &lt;?php get_sidebar( 'footer' ); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;footer id="colophon" class="site-footer" role="contentinfo"&gt; &lt;div class="site-info container"&gt; &lt;div class="row"&gt; &lt;?php if( of_get_option('footer_social') ) sparkling_social_icons(); ?&gt; &lt;nav role="navigation" class="col-md-6"&gt; &lt;?php sparkling_footer_links(); ?&gt; &lt;/nav&gt; &lt;div class="copyright col-md-6"&gt; &lt;?php echo of_get_option( 'custom_footer_text', 'sparkling' ); ?&gt; &lt;?php sparkling_footer_info(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;&lt;!-- .site-info --&gt; &lt;div class="scroll-to-top"&gt;&lt;i class="fa fa-angle-up"&gt;&lt;/i&gt;&lt;/div&gt;&lt;!-- .scroll-to-top --&gt; &lt;/footer&gt;&lt;!-- #colophon --&gt; &lt;/div&gt; </code></pre> <p></p> <p></p> <p>I tried inserting the following into the child's <code>function.php</code> (together with a few variants), but it doesn't work:</p> <pre><code>function remove_sparkling_footer(){ remove_action( 'wp_footer', 'sparkling_footer_info' );} add_action( 'init', 'remove_sparkling_footer' ); </code></pre> <p>Any help or ideas would be greatly appreciated.</p>
[ { "answer_id": 245867, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 0, "selected": false, "text": "<p>The function <code>sparkling_footer_info()</code> is directly called from the footer code, without any action or filter you could intercept. There's no filter inside the function either. Presumably the people at Sparkling don't want you to remove it. There might even be something about this in de theme's license, so check if what you are trying to do is legal.</p>\n\n<p>That said, PHP offers a <a href=\"http://php.net/manual/en/function.runkit-function-redefine.php\" rel=\"nofollow noreferrer\">method to redefine functions</a> (provided runkit is included in your PHP install, which isn't automatically the case). You cannot remove the function unless you remove it from the template call in your child theme, which apparently is not what you want. So you redefine it with an empty function (that simply says 'return').</p>\n\n<p>You shuld run the redefinition after <code>sparkling_footer_info()</code> has been loaded, which is after your child theme's <code>functions.php</code> has been loaded. You could, for instance, attach it to <code>wp_head</code> like this:</p>\n\n<pre><code>add_action ('wp_head','wpse245817_replace_function');\n\nfunction wpse245817_replace_function () {\n runkit_function_redefine('sparkling_footer_info','','return;');\n }\n</code></pre>\n\n<p>Please note that I haven't tested this code. Some debugging may be necessary.</p>\n" }, { "answer_id": 246009, "author": "JHoffmann", "author_id": 63847, "author_profile": "https://wordpress.stackexchange.com/users/63847", "pm_score": 2, "selected": true, "text": "<p>As the function <code>sparkling_footer_info()</code> uses <a href=\"https://developer.wordpress.org/reference/functions/esc_html__/\" rel=\"nofollow noreferrer\"><code>esc_html__()</code></a> and this function runs the <a href=\"https://developer.wordpress.org/reference/hooks/esc_html/\" rel=\"nofollow noreferrer\"><code>esc_html</code></a> filter before outputting, you can intercept the output there.</p>\n\n<pre><code>add_filter ('esc_html', 'wpse_245817_esc_html', 100, 2 );\nfunction wpse_245817_esc_html( $safe_text, $text ) {\n if ( $safe_text == 'Theme by %1$s Powered by %2$s' ) {\n return '';\n }\n return $safe_text;\n}\n</code></pre>\n\n<p>Maybe you have to adapt the code a little for your own needs, I didn't test it either.</p>\n" } ]
2016/11/11
[ "https://wordpress.stackexchange.com/questions/245817", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106748/" ]
I'd like to remove the "Powered by Wordpress" custom link in the footer. I want to do this using action hooks/filters in the child theme's `function.php` file. I don't want to use CSS (which just hides it), edit the original theme file (which will get overriden when the theme updates), or copy the `footer.php` file to the child theme and edit it out there (since I will then have to update the file after a theme update). The theme I'm using is 'sparkling'. The footer info function is defined in the `extras.php` file: ``` function sparkling_footer_info() { global $sparkling_footer_info; printf( esc_html__( 'Theme by %1$s Powered by %2$s', 'sparkling' ) , '<a href="http://colorlib.com/" target="_blank">Colorlib</a>', '<a href="http://wordpress.org/" target="_blank">WordPress</a>'); } ``` And called in the footer.php file (a few lines from the bottom): ``` <div id="footer-area"> <div class="container footer-inner"> <div class="row"> <?php get_sidebar( 'footer' ); ?> </div> </div> <footer id="colophon" class="site-footer" role="contentinfo"> <div class="site-info container"> <div class="row"> <?php if( of_get_option('footer_social') ) sparkling_social_icons(); ?> <nav role="navigation" class="col-md-6"> <?php sparkling_footer_links(); ?> </nav> <div class="copyright col-md-6"> <?php echo of_get_option( 'custom_footer_text', 'sparkling' ); ?> <?php sparkling_footer_info(); ?> </div> </div> </div><!-- .site-info --> <div class="scroll-to-top"><i class="fa fa-angle-up"></i></div><!-- .scroll-to-top --> </footer><!-- #colophon --> </div> ``` I tried inserting the following into the child's `function.php` (together with a few variants), but it doesn't work: ``` function remove_sparkling_footer(){ remove_action( 'wp_footer', 'sparkling_footer_info' );} add_action( 'init', 'remove_sparkling_footer' ); ``` Any help or ideas would be greatly appreciated.
As the function `sparkling_footer_info()` uses [`esc_html__()`](https://developer.wordpress.org/reference/functions/esc_html__/) and this function runs the [`esc_html`](https://developer.wordpress.org/reference/hooks/esc_html/) filter before outputting, you can intercept the output there. ``` add_filter ('esc_html', 'wpse_245817_esc_html', 100, 2 ); function wpse_245817_esc_html( $safe_text, $text ) { if ( $safe_text == 'Theme by %1$s Powered by %2$s' ) { return ''; } return $safe_text; } ``` Maybe you have to adapt the code a little for your own needs, I didn't test it either.
245,819
<p>I want to display a custom button in my "Edit post" screen which saves the current post (everything including custom fields) and then runs a function (in my case redirecting to another page).</p> <p>I know how to redirect after saving the post using the <code>save_posts</code> action and <code>wp_redirect</code> but I can't figure out how to save the post when a custom button is clicked.</p> <p>This is my function for redirecting using <code>save_post</code> (which doesn't work for me since I need to use a custom button):</p> <pre><code>function redirect_after_save_post() { global $post; if ( 'event' == get_post_type() ) { $url = 'http://www.google.com'; wp_redirect( $url ); exit; } } add_action( 'save_post', 'redirect_after_save_post' ); </code></pre>
[ { "answer_id": 245867, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 0, "selected": false, "text": "<p>The function <code>sparkling_footer_info()</code> is directly called from the footer code, without any action or filter you could intercept. There's no filter inside the function either. Presumably the people at Sparkling don't want you to remove it. There might even be something about this in de theme's license, so check if what you are trying to do is legal.</p>\n\n<p>That said, PHP offers a <a href=\"http://php.net/manual/en/function.runkit-function-redefine.php\" rel=\"nofollow noreferrer\">method to redefine functions</a> (provided runkit is included in your PHP install, which isn't automatically the case). You cannot remove the function unless you remove it from the template call in your child theme, which apparently is not what you want. So you redefine it with an empty function (that simply says 'return').</p>\n\n<p>You shuld run the redefinition after <code>sparkling_footer_info()</code> has been loaded, which is after your child theme's <code>functions.php</code> has been loaded. You could, for instance, attach it to <code>wp_head</code> like this:</p>\n\n<pre><code>add_action ('wp_head','wpse245817_replace_function');\n\nfunction wpse245817_replace_function () {\n runkit_function_redefine('sparkling_footer_info','','return;');\n }\n</code></pre>\n\n<p>Please note that I haven't tested this code. Some debugging may be necessary.</p>\n" }, { "answer_id": 246009, "author": "JHoffmann", "author_id": 63847, "author_profile": "https://wordpress.stackexchange.com/users/63847", "pm_score": 2, "selected": true, "text": "<p>As the function <code>sparkling_footer_info()</code> uses <a href=\"https://developer.wordpress.org/reference/functions/esc_html__/\" rel=\"nofollow noreferrer\"><code>esc_html__()</code></a> and this function runs the <a href=\"https://developer.wordpress.org/reference/hooks/esc_html/\" rel=\"nofollow noreferrer\"><code>esc_html</code></a> filter before outputting, you can intercept the output there.</p>\n\n<pre><code>add_filter ('esc_html', 'wpse_245817_esc_html', 100, 2 );\nfunction wpse_245817_esc_html( $safe_text, $text ) {\n if ( $safe_text == 'Theme by %1$s Powered by %2$s' ) {\n return '';\n }\n return $safe_text;\n}\n</code></pre>\n\n<p>Maybe you have to adapt the code a little for your own needs, I didn't test it either.</p>\n" } ]
2016/11/11
[ "https://wordpress.stackexchange.com/questions/245819", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70492/" ]
I want to display a custom button in my "Edit post" screen which saves the current post (everything including custom fields) and then runs a function (in my case redirecting to another page). I know how to redirect after saving the post using the `save_posts` action and `wp_redirect` but I can't figure out how to save the post when a custom button is clicked. This is my function for redirecting using `save_post` (which doesn't work for me since I need to use a custom button): ``` function redirect_after_save_post() { global $post; if ( 'event' == get_post_type() ) { $url = 'http://www.google.com'; wp_redirect( $url ); exit; } } add_action( 'save_post', 'redirect_after_save_post' ); ```
As the function `sparkling_footer_info()` uses [`esc_html__()`](https://developer.wordpress.org/reference/functions/esc_html__/) and this function runs the [`esc_html`](https://developer.wordpress.org/reference/hooks/esc_html/) filter before outputting, you can intercept the output there. ``` add_filter ('esc_html', 'wpse_245817_esc_html', 100, 2 ); function wpse_245817_esc_html( $safe_text, $text ) { if ( $safe_text == 'Theme by %1$s Powered by %2$s' ) { return ''; } return $safe_text; } ``` Maybe you have to adapt the code a little for your own needs, I didn't test it either.
245,822
<p>I am developing my WordPress theme using Material Bootstrap Design (MDB), a Material variant that uses Bootstrap 4 plus its own code.</p> <p>It <a href="http://mdbootstrap.com/mdb-quick-start/" rel="nofollow noreferrer">calls for</a> using the following scripts...</p> <pre><code>&lt;!-- JQuery --&gt; &lt;script type="text/javascript" src="/wp-content/themes/blankslate/mdb/js/jquery-2.2.3.min.js"&gt;&lt;/script&gt; &lt;!-- Bootstrap tooltips --&gt; &lt;script type="text/javascript" src="/wp-content/themes/blankslate/mdb/js/tether.min.js"&gt;&lt;/script&gt; &lt;!-- Bootstrap core JavaScript --&gt; &lt;script type="text/javascript" src="/wp-content/themes/blankslate/mdb/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;!-- MDB core JavaScript --&gt; &lt;script type="text/javascript" src="/wp-content/themes/blankslate/mdb/js/mdb.min.js"&gt;&lt;/script&gt; </code></pre> <p>I had simply added these to the bottom of my <code>footer.php</code>. But now I have read that I should add Javascripts to WordPress properly, ie, by enqueuing.</p> <p>So far, I have used this...</p> <pre><code>// Add Javascripts for my Bootstrap theme function bootstrap_scripts_with_jquery() { // Register the script like this for a theme: wp_enqueue_script( 'bootstra-jquery', get_stylesheet_directory_uri() . '/mdb/js/jquery-2.2.3.min.js', array( 'jquery' ) ); wp_enqueue_script( 'bootstrap-jquery-min', get_stylesheet_directory_uri() . '/mdb/js/jquery.min.js' ); wp_enqueue_script( 'bootstrap', get_stylesheet_directory_uri() . '/mdb/js/bootstrap.min.js' ); wp_enqueue_script( 'bootstrap-material', get_stylesheet_directory_uri() . '/mdb/js/mdb.min.js' ); } add_action( 'wp_enqueue_scripts', 'bootstrap_scripts_with_jquery' ); // http://stackoverflow.com/questions/26583978/how-to-load-bootstrap-script-and-style-in-functions-php-wordpress </code></pre> <p>This works, to a point - it adds my four lines to the code (though I don't know if doing it this way makes any difference).</p> <p>However, I also see two remaining/default JS lines in my header that I didn't add...</p> <pre><code>&lt;script type='text/javascript' src='http://www.example.com/wp-includes/js/jquery/jquery.js?ver=1.12.4'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://www.example.com/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.4.1'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://www.example.com/wp-content/themes/blankslate/mdb/js/jquery-2.2.3.min.js?ver=4.6.1'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://www.example.com/wp-content/themes/blankslate/mdb/js/jquery.min.js?ver=4.6.1'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://www.example.com/wp-content/themes/blankslate/mdb/js/bootstrap.min.js?ver=4.6.1'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://www.example.com/wp-content/themes/blankslate/mdb/js/mdb.min.js?ver=4.6.1'&gt;&lt;/script&gt; </code></pre> <p>And I am still seeing this line in the footer, though I didn't add it (I think I want to leave this, right?)...</p> <pre><code>&lt;script type='text/javascript' src='http://www.example.com/wp-includes/js/wp-embed.min.js?ver=4.6.1'&gt;&lt;/script&gt; </code></pre> <p>The main question, then, is - how should I deal with the fact that WordPress includes <code>jquery.js?ver=1.12.4</code> and <code>jquery-migrate.min.js?ver=1.4.1</code> when my theme does not call for them? Is there a conflict here? If WordPress' own JQuery is being served by passing a version number to it, is it possible that I can force it to use v2.2.3 as requested by my theme? And what about this "migrate" version?</p> <p>I'm aware that you can dequeue scripts, and have read that you can <a href="https://www.webhostinghero.com/change-the-jquery-version-wordpress/" rel="nofollow noreferrer">force a custom version using a filter</a> <a href="https://premium.wpmudev.org/blog/replacing-default-wordpress-scripts/?utm_expid=3606929-91.15T0nlf8TFCqo1W_BlZjGg.0&amp;utm_referrer=https%3A%2F%2Fwww.google.co.uk%2F" rel="nofollow noreferrer">or similar</a>. But I have also read that you should not be tinkering with removing WordPress' default version of JQuery.</p> <p>I am confused.</p> <p>And do I need to enqueue CSS?</p>
[ { "answer_id": 245847, "author": "Jesper Nilsson", "author_id": 102950, "author_profile": "https://wordpress.stackexchange.com/users/102950", "pm_score": 0, "selected": false, "text": "<p>Maybe this is not that much of a WordPress question after all. But as far as I have seen the Bootstrap 4 works with jQuery 1.2.0. Tested Simon Padburys <a href=\"https://github.com/SimonPadbury/b4st\" rel=\"nofollow noreferrer\">Bootstrap 4 Starter Theme</a> for WordPress which enqueue WordPress onboard (pre-registered) jQuery.</p>\n\n<p><a href=\"https://github.com/SimonPadbury/b4st/blob/master/functions/enqueues.php\" rel=\"nofollow noreferrer\">https://github.com/SimonPadbury/b4st/blob/master/functions/enqueues.php</a></p>\n" }, { "answer_id": 245859, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": true, "text": "<p>WordPress loads jQuery because plugins and themes suppose it does. If you want another version of jQuery for your theme, there is a risk that plugins you may be using will not work, since (if they are maintained well) they are designed to work <a href=\"https://wordpress.stackexchange.com/questions/244537/why-does-wordpress-use-outdated-jquery-v1-12-4/244543#244543\">with default jquery</a>.</p>\n\n<p>That said, if you insist on using your own version of jQuery you can easily deregister it, as you found out. If you're not planning a public release of your theme you can control the consequences.</p>\n\n<p>And yes, you should <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">enqueue styles</a> as well. The reason to do this, is it allows you to set dependencies, which is important if (for instance) you would want to make a child theme and deregister the parent styles.</p>\n" } ]
2016/11/11
[ "https://wordpress.stackexchange.com/questions/245822", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/39300/" ]
I am developing my WordPress theme using Material Bootstrap Design (MDB), a Material variant that uses Bootstrap 4 plus its own code. It [calls for](http://mdbootstrap.com/mdb-quick-start/) using the following scripts... ``` <!-- JQuery --> <script type="text/javascript" src="/wp-content/themes/blankslate/mdb/js/jquery-2.2.3.min.js"></script> <!-- Bootstrap tooltips --> <script type="text/javascript" src="/wp-content/themes/blankslate/mdb/js/tether.min.js"></script> <!-- Bootstrap core JavaScript --> <script type="text/javascript" src="/wp-content/themes/blankslate/mdb/js/bootstrap.min.js"></script> <!-- MDB core JavaScript --> <script type="text/javascript" src="/wp-content/themes/blankslate/mdb/js/mdb.min.js"></script> ``` I had simply added these to the bottom of my `footer.php`. But now I have read that I should add Javascripts to WordPress properly, ie, by enqueuing. So far, I have used this... ``` // Add Javascripts for my Bootstrap theme function bootstrap_scripts_with_jquery() { // Register the script like this for a theme: wp_enqueue_script( 'bootstra-jquery', get_stylesheet_directory_uri() . '/mdb/js/jquery-2.2.3.min.js', array( 'jquery' ) ); wp_enqueue_script( 'bootstrap-jquery-min', get_stylesheet_directory_uri() . '/mdb/js/jquery.min.js' ); wp_enqueue_script( 'bootstrap', get_stylesheet_directory_uri() . '/mdb/js/bootstrap.min.js' ); wp_enqueue_script( 'bootstrap-material', get_stylesheet_directory_uri() . '/mdb/js/mdb.min.js' ); } add_action( 'wp_enqueue_scripts', 'bootstrap_scripts_with_jquery' ); // http://stackoverflow.com/questions/26583978/how-to-load-bootstrap-script-and-style-in-functions-php-wordpress ``` This works, to a point - it adds my four lines to the code (though I don't know if doing it this way makes any difference). However, I also see two remaining/default JS lines in my header that I didn't add... ``` <script type='text/javascript' src='http://www.example.com/wp-includes/js/jquery/jquery.js?ver=1.12.4'></script> <script type='text/javascript' src='http://www.example.com/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.4.1'></script> <script type='text/javascript' src='http://www.example.com/wp-content/themes/blankslate/mdb/js/jquery-2.2.3.min.js?ver=4.6.1'></script> <script type='text/javascript' src='http://www.example.com/wp-content/themes/blankslate/mdb/js/jquery.min.js?ver=4.6.1'></script> <script type='text/javascript' src='http://www.example.com/wp-content/themes/blankslate/mdb/js/bootstrap.min.js?ver=4.6.1'></script> <script type='text/javascript' src='http://www.example.com/wp-content/themes/blankslate/mdb/js/mdb.min.js?ver=4.6.1'></script> ``` And I am still seeing this line in the footer, though I didn't add it (I think I want to leave this, right?)... ``` <script type='text/javascript' src='http://www.example.com/wp-includes/js/wp-embed.min.js?ver=4.6.1'></script> ``` The main question, then, is - how should I deal with the fact that WordPress includes `jquery.js?ver=1.12.4` and `jquery-migrate.min.js?ver=1.4.1` when my theme does not call for them? Is there a conflict here? If WordPress' own JQuery is being served by passing a version number to it, is it possible that I can force it to use v2.2.3 as requested by my theme? And what about this "migrate" version? I'm aware that you can dequeue scripts, and have read that you can [force a custom version using a filter](https://www.webhostinghero.com/change-the-jquery-version-wordpress/) [or similar](https://premium.wpmudev.org/blog/replacing-default-wordpress-scripts/?utm_expid=3606929-91.15T0nlf8TFCqo1W_BlZjGg.0&utm_referrer=https%3A%2F%2Fwww.google.co.uk%2F). But I have also read that you should not be tinkering with removing WordPress' default version of JQuery. I am confused. And do I need to enqueue CSS?
WordPress loads jQuery because plugins and themes suppose it does. If you want another version of jQuery for your theme, there is a risk that plugins you may be using will not work, since (if they are maintained well) they are designed to work [with default jquery](https://wordpress.stackexchange.com/questions/244537/why-does-wordpress-use-outdated-jquery-v1-12-4/244543#244543). That said, if you insist on using your own version of jQuery you can easily deregister it, as you found out. If you're not planning a public release of your theme you can control the consequences. And yes, you should [enqueue styles](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) as well. The reason to do this, is it allows you to set dependencies, which is important if (for instance) you would want to make a child theme and deregister the parent styles.
245,838
<p>First, i'd like to point I do this probably wrong, but this is a bit of a desperate thing and it popped in my head.</p> <p>We are developing a site for a client, and he wants breadcrumbs. Now we downloaded a plugin that allows you to place breadcrumbs by calling the breadcrumbs_trial function. Since the theme doesn't support PHP additions, and we want to place it a dynamic spot within the page that isnt accessable easily.</p> <p>Since the theme codeblock accepts shortcode, i thought (maybe stupid) to create run the breadcrumb in a shortcode, so I made an attempt,</p> <pre><code>function breadcrumbs_func( $atts ){ breadcrumb_trail(); } add_shortcode( 'breadcrumbs', 'breadcrumbs_func' ); </code></pre> <p>Now I realise, I go offcourse in the scope of the function, and the breadcrumb_trail() function isn't defined in here. Is there a way i can run this stand alone function from another plugin in such thing?</p> <p><strong>edit</strong></p> <p>I made a typo, and it does run, but it just isn't displayed at the right position now... tweaking further i guess</p>
[ { "answer_id": 245841, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>That is very tricky. I would manually place it in the template directly where I want it (or where the client wants it) using: </p>\n\n<pre><code>&lt;?php echo do_shortcode('[some-shotcode]'); ?&gt; \n</code></pre>\n\n<p>But then again, that is just me. If you rely on the WYSIWYG content box, you will end up with undesired results – possibly. </p>\n" }, { "answer_id": 245843, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 3, "selected": true, "text": "<p>This will probably not work, or work in unexpected way. Shortcodes should <strong>probably</strong> be displayed only on a \"post\" single page. Using a shortcode in the way you want will either make the breadcrumbs not to be displayed on archive pages or have them displayed there multiple times or wrong places.</p>\n\n<p>What you should do is a minimal modification to the theme. Insert a <code>do_action('show_bc</code>); at the appropriate place in the header file (\"fork\" it in a child theme if you use one). Then add something like <code>add_action('show_bc','breadcrumb_trail');</code> in the theme's <code>functions.php</code> or in a plugin.</p>\n\n<p>As for the exact problem you have in your code, it is because shortcode handlers are supposed to return HTML, and not to output it. If the BC function do not have an option to return the HTML instead of echo-ing, you will have to do output buffering around its call.</p>\n" }, { "answer_id": 245872, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 0, "selected": false, "text": "<p>you could try this:</p>\n\n<pre><code> add_filter( 'the_content', 'customcode_after_content' ); \n\n function customcode_after_content( $content ) { \n if ( is_singular('post') {\n $extracode = '&lt;p&gt;hi&lt;/p&gt;';\n\n $content = $extracode . $content;\n\n }\n\n return $content;\n}\n</code></pre>\n\n<p>then you could input either a shortcode or just the actual code. Wouldn't have to mess with header either.</p>\n" } ]
2016/11/11
[ "https://wordpress.stackexchange.com/questions/245838", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87085/" ]
First, i'd like to point I do this probably wrong, but this is a bit of a desperate thing and it popped in my head. We are developing a site for a client, and he wants breadcrumbs. Now we downloaded a plugin that allows you to place breadcrumbs by calling the breadcrumbs\_trial function. Since the theme doesn't support PHP additions, and we want to place it a dynamic spot within the page that isnt accessable easily. Since the theme codeblock accepts shortcode, i thought (maybe stupid) to create run the breadcrumb in a shortcode, so I made an attempt, ``` function breadcrumbs_func( $atts ){ breadcrumb_trail(); } add_shortcode( 'breadcrumbs', 'breadcrumbs_func' ); ``` Now I realise, I go offcourse in the scope of the function, and the breadcrumb\_trail() function isn't defined in here. Is there a way i can run this stand alone function from another plugin in such thing? **edit** I made a typo, and it does run, but it just isn't displayed at the right position now... tweaking further i guess
This will probably not work, or work in unexpected way. Shortcodes should **probably** be displayed only on a "post" single page. Using a shortcode in the way you want will either make the breadcrumbs not to be displayed on archive pages or have them displayed there multiple times or wrong places. What you should do is a minimal modification to the theme. Insert a `do_action('show_bc`); at the appropriate place in the header file ("fork" it in a child theme if you use one). Then add something like `add_action('show_bc','breadcrumb_trail');` in the theme's `functions.php` or in a plugin. As for the exact problem you have in your code, it is because shortcode handlers are supposed to return HTML, and not to output it. If the BC function do not have an option to return the HTML instead of echo-ing, you will have to do output buffering around its call.
245,853
<p>I am building a custom loop where I want to display post content only if its title matches a specific string. But I am out of luck on getting this done right. </p> <p>Here is my code so far. </p> <pre><code>$args = array( 'post_type' =&gt; 'property', 'posts_per_page' =&gt; -1 ); $query = new WP_Query( $args ); if ( $query-&gt;have_posts() ) { // The Loop while ( $query-&gt;have_posts() ) { $query-&gt;the_post(); if( in_array( 'California', get_the_title() ) ){ $post = get_page_by_title( get_the_title() ); /*not sure how to move forward*/ } } wp_reset_postdata(); } </code></pre> <p>Any help or correct guidance would be highly appreciated. </p> <p>Thanks in advance.</p>
[ { "answer_id": 245841, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>That is very tricky. I would manually place it in the template directly where I want it (or where the client wants it) using: </p>\n\n<pre><code>&lt;?php echo do_shortcode('[some-shotcode]'); ?&gt; \n</code></pre>\n\n<p>But then again, that is just me. If you rely on the WYSIWYG content box, you will end up with undesired results – possibly. </p>\n" }, { "answer_id": 245843, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 3, "selected": true, "text": "<p>This will probably not work, or work in unexpected way. Shortcodes should <strong>probably</strong> be displayed only on a \"post\" single page. Using a shortcode in the way you want will either make the breadcrumbs not to be displayed on archive pages or have them displayed there multiple times or wrong places.</p>\n\n<p>What you should do is a minimal modification to the theme. Insert a <code>do_action('show_bc</code>); at the appropriate place in the header file (\"fork\" it in a child theme if you use one). Then add something like <code>add_action('show_bc','breadcrumb_trail');</code> in the theme's <code>functions.php</code> or in a plugin.</p>\n\n<p>As for the exact problem you have in your code, it is because shortcode handlers are supposed to return HTML, and not to output it. If the BC function do not have an option to return the HTML instead of echo-ing, you will have to do output buffering around its call.</p>\n" }, { "answer_id": 245872, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 0, "selected": false, "text": "<p>you could try this:</p>\n\n<pre><code> add_filter( 'the_content', 'customcode_after_content' ); \n\n function customcode_after_content( $content ) { \n if ( is_singular('post') {\n $extracode = '&lt;p&gt;hi&lt;/p&gt;';\n\n $content = $extracode . $content;\n\n }\n\n return $content;\n}\n</code></pre>\n\n<p>then you could input either a shortcode or just the actual code. Wouldn't have to mess with header either.</p>\n" } ]
2016/11/11
[ "https://wordpress.stackexchange.com/questions/245853", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58787/" ]
I am building a custom loop where I want to display post content only if its title matches a specific string. But I am out of luck on getting this done right. Here is my code so far. ``` $args = array( 'post_type' => 'property', 'posts_per_page' => -1 ); $query = new WP_Query( $args ); if ( $query->have_posts() ) { // The Loop while ( $query->have_posts() ) { $query->the_post(); if( in_array( 'California', get_the_title() ) ){ $post = get_page_by_title( get_the_title() ); /*not sure how to move forward*/ } } wp_reset_postdata(); } ``` Any help or correct guidance would be highly appreciated. Thanks in advance.
This will probably not work, or work in unexpected way. Shortcodes should **probably** be displayed only on a "post" single page. Using a shortcode in the way you want will either make the breadcrumbs not to be displayed on archive pages or have them displayed there multiple times or wrong places. What you should do is a minimal modification to the theme. Insert a `do_action('show_bc`); at the appropriate place in the header file ("fork" it in a child theme if you use one). Then add something like `add_action('show_bc','breadcrumb_trail');` in the theme's `functions.php` or in a plugin. As for the exact problem you have in your code, it is because shortcode handlers are supposed to return HTML, and not to output it. If the BC function do not have an option to return the HTML instead of echo-ing, you will have to do output buffering around its call.
245,877
<h1>Question</h1> <p>What are all the files that I have to modify to get this to work?</p> <h2>Background</h2> <p>I have been searching stackoverflow for similar answers. Most talk about modifying something called a <code>php.ini</code> file. Which i have not been able to locate. But is that actually the case for WordPress themes?</p> <p>I installed the Aqueduct theme. The problem I am having is that the images will now show up as thumbnails. So that is where I get the error</p> <h2>Error</h2> <pre><code>Warning: getimagesize() [function.getimagesize]: http:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /nfs/c09/h01/mnt/133267/domains/lame.io/html/wp-content/themes/aqueduct/content.php on line 38 </code></pre> <p>I opened up the file to make the edit, but I don't actually see the <code>allow_url_fopen=0</code> on line 38.</p> <h2>Code</h2> <pre><code>&lt;?php /** * @package HowlThemes */ ?&gt; &lt;article id=&quot;post-&lt;?php the_ID(); ?&gt;&quot; &lt;?php post_class(); ?&gt; itemscope=&quot;itemscope&quot; itemtype=&quot;http://schema.org/BlogPosting&quot; itemprop=&quot;blogPost&quot;&gt; &lt;header class=&quot;entry-header&quot;&gt; &lt;?php the_title( sprintf( '&lt;h2 class=&quot;entry-title&quot; itemprop=&quot;headline&quot;&gt;&lt;a href=&quot;%s&quot; rel=&quot;bookmark&quot;&gt;', esc_url( get_permalink() ) ), '&lt;/a&gt;&lt;/h2&gt;' ); ?&gt; &lt;?php if ( 'post' == get_post_type() ) : ?&gt; &lt;div class=&quot;entry-meta&quot;&gt; &lt;div class=&quot;postdcp&quot;&gt;&lt;?php drag_themes_posted_on(); ?&gt;&lt;/div&gt; &lt;/div&gt;&lt;!-- .entry-meta --&gt; &lt;?php endif; ?&gt; &lt;/header&gt;&lt;!-- .entry-header --&gt; &lt;div class=&quot;entry-content&quot;&gt; &lt;div class=&quot;thumbnail-container&quot; itemprop=&quot;image&quot;&gt; &lt;?php if ( get_the_post_thumbnail() != '' ) { echo '&lt;a href=&quot;'; the_permalink(); echo '&quot; class=&quot;thumbnail-wrapper&quot;&gt;'; $source_image_url = wp_get_attachment_url( get_post_thumbnail_id($post-&gt;ID, 'thumbnail') ); $imginfo = getimagesize($source_image_url); if($imginfo[0] &gt;= 250 &amp;&amp; $imginfo[1] &gt;= 200){ $resizedImage = aq_resize($source_image_url, 250, 200, true); } else{ $resizedImage = $source_image_url; } echo '&lt;img src=&quot;'; echo $resizedImage; echo '&quot; alt=&quot;';the_title(); echo '&quot; /&gt;'; echo '&lt;/a&gt;'; } elseif(howlthemes_catch_that_image()){ $source_image_url = howlthemes_catch_that_image(); $imginfo = getimagesize($source_image_url); if($imginfo[0] &gt;= 250 &amp;&amp; $imginfo[1] &gt;= 200){ $resizedImage = aq_resize($source_image_url, 250, 200, true); } else{ $resizedImage = $source_image_url; } echo '&lt;a href=&quot;'; the_permalink(); echo '&quot; class=&quot;thumbnail-wrapper&quot;&gt;'; echo '&lt;img src=&quot;'; echo $resizedImage; echo '&quot; alt=&quot;';the_title(); echo '&quot; /&gt;'; echo '&lt;/a&gt;'; } else{ echo '&lt;a href=&quot;'; the_permalink(); echo '&quot; class=&quot;thumbnail-wrapper&quot;&gt;'; echo '&lt;img src=&quot;'; echo esc_url( get_template_directory_uri() ); echo '/img/thumbnail.jpg&quot; alt=&quot;';the_title(); echo '&quot; /&gt;'; echo '&lt;/a&gt;'; } ?&gt; &lt;/div&gt; &lt;div class=&quot;entry-summary&quot; itemprop=&quot;text&quot;&gt; &lt;?php the_excerpt(); ?&gt;&lt;/div&gt; &lt;/div&gt;&lt;!-- .entry-content --&gt; &lt;footer class=&quot;entry-footer&quot;&gt; &lt;div class=&quot;read-more-button&quot;&gt;&lt;a href=&quot;&lt;?php the_permalink(); ?&gt;&quot;&gt;&lt;?php _e( 'Read More', 'aqueduct'); ?&gt; &lt;i class=&quot;fa fa-long-arrow-right&quot;&gt;&lt;/i&gt;&lt;/a&gt;&lt;/div&gt; &lt;/footer&gt;&lt;!-- .entry-footer --&gt; &lt;/article&gt;&lt;!-- #post-## --&gt; </code></pre> <p>EDIT 1:</p> <p>Found the <code>php.ini</code> file. But not sure exactly what what change i am supposed to make</p> <pre><code>; Rename this file to php.ini and uncomment or add directives. ; For a complete list of valid directives, visit: ; http://us2.php.net/manual/en/ini.php [PHP] ; We highly recommend that you leave this options enabled cgi.fix_pathinfo=1 ; Increase maximum post size ;post_max_size = 20M ; Increase execution time ;max_execution_time = 300 ; pull in EGPCS [Environment, GET, POST, Cookie, Server] variables as globals ;register_globals = true ; For performance reasons, (mt) does not load all of the modules that are available ; into PHP. You may uncomment any one of the following &quot;extension&quot; lines to enable ; the desired module ; Salblotron XSLT ;extension=xslt.so ; save in local tmp session.save_path=/home/133267/data/tmp </code></pre> <p>My experience is with Ruby, not PHP, and I have limited WordPress experience, so please answer like I am totally new.</p>
[ { "answer_id": 245944, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 1, "selected": false, "text": "<p>The issue is exactly what @shanebp says - it's a PHP configuration issue. <em>However</em>, I can't see any reason why the code is calling <code>getimagesize</code> on the URL, when you can use <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"nofollow noreferrer\"><code>wp_get_attachment_image_src</code></a>, which will get the data via the filesystem instead:</p>\n\n<pre><code>$imginfo = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), 'thumbnail' );\nif ( $imginfo[1] &gt;= 250 &amp;&amp; $imginfo[2] &gt;= 200 )\n $resizedImage = aq_resize( $imginfo[0], 250, 200, true );\nelse\n $resizedImage = $imginfo[0];\n</code></pre>\n" }, { "answer_id": 246163, "author": "JGallardo", "author_id": 104295, "author_profile": "https://wordpress.stackexchange.com/users/104295", "pm_score": 3, "selected": true, "text": "<p>I fixed the problem of not being able to see the thumbnails. Not sure this is the best overall long term solution, but it works now</p>\n<p><a href=\"https://i.stack.imgur.com/cwGad.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cwGad.png\" alt=\"enter image description here\" /></a></p>\n<p>I added this line to the <code>php.ini</code> file.</p>\n<pre><code>allow_url_fopen = On\n</code></pre>\n<p>I found the file not on the server under <code>etc</code> [this site is hosted on media temple, you might need to contact your own host if you cannot find it]</p>\n<p><a href=\"https://i.stack.imgur.com/dYkZm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dYkZm.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/IxR1j.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IxR1j.png\" alt=\"enter image description here\" /></a></p>\n<p>Here is the complete file that I uploaded. There was a php.ini.sample. I copied it to edit locally, added the line, then uploaded back</p>\n<h2>php.ini</h2>\n<pre><code>; Rename this file to php.ini and uncomment or add directives.\n; For a complete list of valid directives, visit:\n; http://us2.php.net/manual/en/ini.php\n\n[PHP]\n; We highly recommend that you leave this options enabled\ncgi.fix_pathinfo=1\n\n; Increase maximum post size\n;post_max_size = 20M\n\n; Increase execution time\n;max_execution_time = 300\n\n; pull in EGPCS [Environment, GET, POST, Cookie, Server] variables as globals\n;register_globals = true\n\n; For performance reasons, (mt) does not load all of the modules that are available\n; into PHP. You may uncomment any one of the following &quot;extension&quot; lines to enable\n; the desired module\n\n; Salblotron XSLT\n;extension=xslt.so\n\n; save in local tmp\nsession.save_path=/home/133267/data/tmp\n\nallow_url_fopen = On\n</code></pre>\n<p>I had found this related answer about the <code>php.ini</code> which you can see for further details <a href=\"https://stackoverflow.com/questions/3694240/add-allow-url-fopen-to-my-php-ini-using-htaccess\">https://stackoverflow.com/questions/3694240/add-allow-url-fopen-to-my-php-ini-using-htaccess</a></p>\n" } ]
2016/11/11
[ "https://wordpress.stackexchange.com/questions/245877", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104295/" ]
Question ======== What are all the files that I have to modify to get this to work? Background ---------- I have been searching stackoverflow for similar answers. Most talk about modifying something called a `php.ini` file. Which i have not been able to locate. But is that actually the case for WordPress themes? I installed the Aqueduct theme. The problem I am having is that the images will now show up as thumbnails. So that is where I get the error Error ----- ``` Warning: getimagesize() [function.getimagesize]: http:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /nfs/c09/h01/mnt/133267/domains/lame.io/html/wp-content/themes/aqueduct/content.php on line 38 ``` I opened up the file to make the edit, but I don't actually see the `allow_url_fopen=0` on line 38. Code ---- ``` <?php /** * @package HowlThemes */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?> itemscope="itemscope" itemtype="http://schema.org/BlogPosting" itemprop="blogPost"> <header class="entry-header"> <?php the_title( sprintf( '<h2 class="entry-title" itemprop="headline"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); ?> <?php if ( 'post' == get_post_type() ) : ?> <div class="entry-meta"> <div class="postdcp"><?php drag_themes_posted_on(); ?></div> </div><!-- .entry-meta --> <?php endif; ?> </header><!-- .entry-header --> <div class="entry-content"> <div class="thumbnail-container" itemprop="image"> <?php if ( get_the_post_thumbnail() != '' ) { echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">'; $source_image_url = wp_get_attachment_url( get_post_thumbnail_id($post->ID, 'thumbnail') ); $imginfo = getimagesize($source_image_url); if($imginfo[0] >= 250 && $imginfo[1] >= 200){ $resizedImage = aq_resize($source_image_url, 250, 200, true); } else{ $resizedImage = $source_image_url; } echo '<img src="'; echo $resizedImage; echo '" alt="';the_title(); echo '" />'; echo '</a>'; } elseif(howlthemes_catch_that_image()){ $source_image_url = howlthemes_catch_that_image(); $imginfo = getimagesize($source_image_url); if($imginfo[0] >= 250 && $imginfo[1] >= 200){ $resizedImage = aq_resize($source_image_url, 250, 200, true); } else{ $resizedImage = $source_image_url; } echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">'; echo '<img src="'; echo $resizedImage; echo '" alt="';the_title(); echo '" />'; echo '</a>'; } else{ echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">'; echo '<img src="'; echo esc_url( get_template_directory_uri() ); echo '/img/thumbnail.jpg" alt="';the_title(); echo '" />'; echo '</a>'; } ?> </div> <div class="entry-summary" itemprop="text"> <?php the_excerpt(); ?></div> </div><!-- .entry-content --> <footer class="entry-footer"> <div class="read-more-button"><a href="<?php the_permalink(); ?>"><?php _e( 'Read More', 'aqueduct'); ?> <i class="fa fa-long-arrow-right"></i></a></div> </footer><!-- .entry-footer --> </article><!-- #post-## --> ``` EDIT 1: Found the `php.ini` file. But not sure exactly what what change i am supposed to make ``` ; Rename this file to php.ini and uncomment or add directives. ; For a complete list of valid directives, visit: ; http://us2.php.net/manual/en/ini.php [PHP] ; We highly recommend that you leave this options enabled cgi.fix_pathinfo=1 ; Increase maximum post size ;post_max_size = 20M ; Increase execution time ;max_execution_time = 300 ; pull in EGPCS [Environment, GET, POST, Cookie, Server] variables as globals ;register_globals = true ; For performance reasons, (mt) does not load all of the modules that are available ; into PHP. You may uncomment any one of the following "extension" lines to enable ; the desired module ; Salblotron XSLT ;extension=xslt.so ; save in local tmp session.save_path=/home/133267/data/tmp ``` My experience is with Ruby, not PHP, and I have limited WordPress experience, so please answer like I am totally new.
I fixed the problem of not being able to see the thumbnails. Not sure this is the best overall long term solution, but it works now [![enter image description here](https://i.stack.imgur.com/cwGad.png)](https://i.stack.imgur.com/cwGad.png) I added this line to the `php.ini` file. ``` allow_url_fopen = On ``` I found the file not on the server under `etc` [this site is hosted on media temple, you might need to contact your own host if you cannot find it] [![enter image description here](https://i.stack.imgur.com/dYkZm.png)](https://i.stack.imgur.com/dYkZm.png) [![enter image description here](https://i.stack.imgur.com/IxR1j.png)](https://i.stack.imgur.com/IxR1j.png) Here is the complete file that I uploaded. There was a php.ini.sample. I copied it to edit locally, added the line, then uploaded back php.ini ------- ``` ; Rename this file to php.ini and uncomment or add directives. ; For a complete list of valid directives, visit: ; http://us2.php.net/manual/en/ini.php [PHP] ; We highly recommend that you leave this options enabled cgi.fix_pathinfo=1 ; Increase maximum post size ;post_max_size = 20M ; Increase execution time ;max_execution_time = 300 ; pull in EGPCS [Environment, GET, POST, Cookie, Server] variables as globals ;register_globals = true ; For performance reasons, (mt) does not load all of the modules that are available ; into PHP. You may uncomment any one of the following "extension" lines to enable ; the desired module ; Salblotron XSLT ;extension=xslt.so ; save in local tmp session.save_path=/home/133267/data/tmp allow_url_fopen = On ``` I had found this related answer about the `php.ini` which you can see for further details <https://stackoverflow.com/questions/3694240/add-allow-url-fopen-to-my-php-ini-using-htaccess>
245,894
<p>i'm using wordpress 4.6 i'd like to remove just the title tag automatically outputted by wordpress because need to hardcode the html title tag in the template.</p> <p>i guess is something like this:</p> <pre><code>add_action('wp_head', '//remove title tag command'); </code></pre> <p>but i didn't find any valid solution so far.</p>
[ { "answer_id": 245901, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 4, "selected": true, "text": "<p>You can see everything added to <code>wp_head</code> in the file <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/default-filters.php#L237\" rel=\"noreferrer\"><code>/wp-includes/default-filters.php</code></a>.</p>\n\n<p>If your theme supports the title tag, you can remove it entirely with <code>remove_action</code>:</p>\n\n<pre><code>remove_action( 'wp_head', '_wp_render_title_tag', 1 );\n</code></pre>\n\n<p>Though it may be simpler/better to use <code>remove_theme_support( 'title-tag' )</code> in a child theme, which is what <code>_wp_render_title_tag</code> checks before outputting the title tag.</p>\n" }, { "answer_id": 388945, "author": "Andrew Kozoriz", "author_id": 207146, "author_profile": "https://wordpress.stackexchange.com/users/207146", "pm_score": 2, "selected": false, "text": "<p>Wordpress 5.7.1 with Yoast SEO installed\nWorking code is:</p>\n<pre><code>add_filter('document_title_parts', '__return_empty_array', 10);\n</code></pre>\n" }, { "answer_id": 404125, "author": "Arvind Srivastava", "author_id": 173747, "author_profile": "https://wordpress.stackexchange.com/users/173747", "pm_score": 0, "selected": false, "text": "<pre><code>if ( is_page('138') )\n{\n add_filter( 'the_title', '__return_false' );\n}\n\nadd_filter('wp_head', function () {\n if (!current_theme_supports('title-tag')) {\n return;\n }\n\n if (did_action('wp_head') || doing_action('wp_head') &amp;&amp; is_single()) {\n $categories = get_the_category();\n // Assuming the post has many categories will take the first\n $category = reset($categories);\n\n if ($category) {\n echo '&lt;title&gt;' . $category-&gt;name . ' - ' . get_the_title() . '&lt;/title&gt;' . &quot;\\n&quot;;\n }\n }\n echo '&lt;title&gt;' . wp_get_document_title() . '&lt;/title&gt;' . &quot;\\n&quot;;\n});\n</code></pre>\n" }, { "answer_id": 404127, "author": "Arvind Srivastava", "author_id": 173747, "author_profile": "https://wordpress.stackexchange.com/users/173747", "pm_score": 0, "selected": false, "text": "<pre><code>add_filter( 'pre_get_document_title' , 'render_title' );\nfunction render_title($title){\n return 'New title ';\n}\nadd_filter( 'document_title_parts' , 'render_title' );\nfunction render_title($parts){\n $parts[&quot;title&quot;] = &quot;My Prefix &quot;. $parts[&quot;title&quot;];\n return $parts;\n}\n</code></pre>\n" } ]
2016/11/12
[ "https://wordpress.stackexchange.com/questions/245894", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104218/" ]
i'm using wordpress 4.6 i'd like to remove just the title tag automatically outputted by wordpress because need to hardcode the html title tag in the template. i guess is something like this: ``` add_action('wp_head', '//remove title tag command'); ``` but i didn't find any valid solution so far.
You can see everything added to `wp_head` in the file [`/wp-includes/default-filters.php`](https://github.com/WordPress/WordPress/blob/master/wp-includes/default-filters.php#L237). If your theme supports the title tag, you can remove it entirely with `remove_action`: ``` remove_action( 'wp_head', '_wp_render_title_tag', 1 ); ``` Though it may be simpler/better to use `remove_theme_support( 'title-tag' )` in a child theme, which is what `_wp_render_title_tag` checks before outputting the title tag.
245,906
<p>I'm working on a custom project for a client and having an issue adding in <code>data-scroll</code> before the links in WordPress. I want the output to be <code>&lt;a data-scroll href='#'&gt;</code>. </p> <p>Data-scroll is what I am looking to add in just after the a, <em>here</em> <code>href ="#"</code></p> <p>Hope someone can help me out.</p>
[ { "answer_id": 245910, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 2, "selected": false, "text": "<p>You'll want to use the following filter:</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/nav_menu_link_attributes\" rel=\"nofollow noreferrer\"><code>nav_menu_link_attributes</code></a></p>\n\n<p>Example:</p>\n\n<pre><code>function filter_nav_menu_link_attributes($atts, $item, $args) {\n\n if ( isset($args-&gt;theme_location) &amp;&amp; $args-&gt;theme_location === 'my-menu-location' ) {\n $atts['data-scroll'] = 'some-value';\n }\n\n return $atts;\n\n}\n\nadd_filter('nav_menu_link_attributes', 'filter_nav_menu_link_attributes', 10, 3);\n</code></pre>\n\n<p>Use <code>$item</code> and <code>$args</code> to isolate and act on the specific menu or specific menu item in which you wish to add your attribute to.</p>\n\n<p>Read more here: <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/nav_menu_link_attributes\" rel=\"nofollow noreferrer\"><code>nav_menu_link_attributes</code></a></p>\n" }, { "answer_id": 245912, "author": "hashtagerrors", "author_id": 102412, "author_profile": "https://wordpress.stackexchange.com/users/102412", "pm_score": 1, "selected": true, "text": "<p>A Custom Walker would be the best way to add anything anywhere to your wp_nav_menu</p>\n\n<p>You hav to keep the following in your function.php</p>\n\n<pre><code> &lt;?php\n class MV_Cleaner_Walker_Nav_Menu extends Walker {\n var $tree_type = array( 'post_type', 'taxonomy', 'custom' );\n var $db_fields = array( 'parent' =&gt; 'menu_item_parent', 'id' =&gt; 'db_id' );\n function start_lvl(&amp;$output, $depth) {\n $indent = str_repeat(\"\\t\", $depth);\n $output .= \"\\n$indent&lt;ul class=\\\"sub-menu\\\"&gt;\\n\";\n }\n function end_lvl(&amp;$output, $depth) {\n $indent = str_repeat(\"\\t\", $depth);\n $output .= \"$indent&lt;/ul&gt;\\n\";\n }\n function start_el(&amp;$output, $item, $depth, $args) {\n global $wp_query;\n $indent = ( $depth ) ? str_repeat( \"\\t\", $depth ) : '';\n $class_names = $value = '';\n $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes;\n $classes = in_array( 'current-menu-item', $classes ) ? array( 'current-menu-item' ) : array();\n $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );\n $class_names = strlen( trim( $class_names ) ) &gt; 0 ? ' class=\"' . esc_attr( $class_names ) . '\"' : '';\n $id = apply_filters( 'nav_menu_item_id', '', $item, $args );\n $id = strlen( $id ) ? ' id=\"' . esc_attr( $id ) . '\"' : '';\n $output .= $indent . '&lt;li' . $id . $value . $class_names .'&gt;';\n $attributes = ! empty( $item-&gt;attr_title ) ? ' title=\"' . esc_attr( $item-&gt;attr_title ) .'\"' : '';\n $attributes .= ! empty( $item-&gt;target ) ? ' target=\"' . esc_attr( $item-&gt;target ) .'\"' : '';\n $attributes .= ! empty( $item-&gt;xfn ) ? ' rel=\"' . esc_attr( $item-&gt;xfn ) .'\"' : '';\n $attributes .= ! empty( $item-&gt;url ) ? ' href=\"' . esc_attr( $item-&gt;url ) .'\"' : '';\n $item_output = $args-&gt;before;\n $item_output .= '&lt;a data-scroll'. $attributes .'&gt;';\n $item_output .= $args-&gt;link_before . apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID ) . $args-&gt;link_after;\n $item_output .= '&lt;/a&gt;';\n $item_output .= $args-&gt;after;\n $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );\n }\n function end_el(&amp;$output, $item, $depth) {\n $output .= \"&lt;/li&gt;\\n\";\n }\n }\n ?&gt;\n</code></pre>\n\n<p>and then you can call the menu by </p>\n\n<pre><code>&lt;?php wp_nav_menu( array( 'menu'=&gt;'Footer Menu 1',\nmenu_class =&gt; 'menu vertical footer-menu',\n'walker' =&gt; new MV_Cleaner_Walker_Nav_Menu() ) ); ?&gt;\n</code></pre>\n" }, { "answer_id": 245914, "author": "Dhiraj Suthar", "author_id": 106755, "author_profile": "https://wordpress.stackexchange.com/users/106755", "pm_score": 0, "selected": false, "text": "<p>You need to add this code on functions.php file of current theme.</p>\n\n<pre><code>add_action( 'wp_footer', 'add_attr_nav_menu_link' );\nfunction add_attr_nav_menu_link(){\n ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n\n jQuery( document ).ready(function() {\n\n jQuery('.nav-menu ul.menu li a').each(function() {\n jQuery(\".nav-menu ul.menu li a\").attr('data-scroll', '');\n\n });\n\n });\n &lt;/script&gt;\n\n &lt;?php\n\n}\n</code></pre>\n\n<p>Let me know if you have any query!!!!</p>\n" } ]
2016/11/12
[ "https://wordpress.stackexchange.com/questions/245906", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106819/" ]
I'm working on a custom project for a client and having an issue adding in `data-scroll` before the links in WordPress. I want the output to be `<a data-scroll href='#'>`. Data-scroll is what I am looking to add in just after the a, *here* `href ="#"` Hope someone can help me out.
A Custom Walker would be the best way to add anything anywhere to your wp\_nav\_menu You hav to keep the following in your function.php ``` <?php class MV_Cleaner_Walker_Nav_Menu extends Walker { var $tree_type = array( 'post_type', 'taxonomy', 'custom' ); var $db_fields = array( 'parent' => 'menu_item_parent', 'id' => 'db_id' ); function start_lvl(&$output, $depth) { $indent = str_repeat("\t", $depth); $output .= "\n$indent<ul class=\"sub-menu\">\n"; } function end_lvl(&$output, $depth) { $indent = str_repeat("\t", $depth); $output .= "$indent</ul>\n"; } function start_el(&$output, $item, $depth, $args) { global $wp_query; $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $class_names = $value = ''; $classes = empty( $item->classes ) ? array() : (array) $item->classes; $classes = in_array( 'current-menu-item', $classes ) ? array( 'current-menu-item' ) : array(); $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) ); $class_names = strlen( trim( $class_names ) ) > 0 ? ' class="' . esc_attr( $class_names ) . '"' : ''; $id = apply_filters( 'nav_menu_item_id', '', $item, $args ); $id = strlen( $id ) ? ' id="' . esc_attr( $id ) . '"' : ''; $output .= $indent . '<li' . $id . $value . $class_names .'>'; $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : ''; $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : ''; $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : ''; $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : ''; $item_output = $args->before; $item_output .= '<a data-scroll'. $attributes .'>'; $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after; $item_output .= '</a>'; $item_output .= $args->after; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } function end_el(&$output, $item, $depth) { $output .= "</li>\n"; } } ?> ``` and then you can call the menu by ``` <?php wp_nav_menu( array( 'menu'=>'Footer Menu 1', menu_class => 'menu vertical footer-menu', 'walker' => new MV_Cleaner_Walker_Nav_Menu() ) ); ?> ```
245,915
<p>I'm developing a plugin and I'd like to use colorbox in my plugin . So I use <code>wp_enqueue_script('jquery');</code> but it doesn't work . Then I search for it and add the following code and it is working now . But why should I deregister jquery ?</p> <pre><code>wp_deregister_script('jquery'); wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js', false, '1.8.1'); wp_enqueue_script('jquery'); </code></pre>
[ { "answer_id": 245921, "author": "Third Essential Designer", "author_id": 103698, "author_profile": "https://wordpress.stackexchange.com/users/103698", "pm_score": 2, "selected": false, "text": "<p>Linking jquery code twice conflicts the functions as they are present twice. So deregistering helps you but it is not good choice. You should go through jQuery no conflict thing. And you should register your jquery version with different name, so that it does not break wordpress.</p>\n\n<p>Ref- jQuery <a href=\"https://forum.jquery.com/topic/multiple-versions-of-jquery-on-the-same-page\" rel=\"nofollow noreferrer\">Forum</a> and <a href=\"https://api.jquery.com/jquery.noconflict/\" rel=\"nofollow noreferrer\">Documentation</a></p>\n" }, { "answer_id": 246031, "author": "Megan Rose", "author_id": 84643, "author_profile": "https://wordpress.stackexchange.com/users/84643", "pm_score": 0, "selected": false, "text": "<p>Building off what Vishal &amp; toscho wrote:</p>\n\n<p>You should avoid deregistering WordPress's version of jQuery. What those lines do is tell WP that you do not want to use their version, and that you want to use a different version of jQuery (version 1.8.1 in your example). Depending on your version of colorbox, the reason it might work now is because it wasn't compatible with the latest version of jQuery included in WP core.</p>\n\n<p>So the best solution would be to find a jQuery plugin that works with the latest version of jQuery.</p>\n" } ]
2016/11/12
[ "https://wordpress.stackexchange.com/questions/245915", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/14448/" ]
I'm developing a plugin and I'd like to use colorbox in my plugin . So I use `wp_enqueue_script('jquery');` but it doesn't work . Then I search for it and add the following code and it is working now . But why should I deregister jquery ? ``` wp_deregister_script('jquery'); wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js', false, '1.8.1'); wp_enqueue_script('jquery'); ```
Linking jquery code twice conflicts the functions as they are present twice. So deregistering helps you but it is not good choice. You should go through jQuery no conflict thing. And you should register your jquery version with different name, so that it does not break wordpress. Ref- jQuery [Forum](https://forum.jquery.com/topic/multiple-versions-of-jquery-on-the-same-page) and [Documentation](https://api.jquery.com/jquery.noconflict/)
245,947
<p>Actually it is more general question but now i am trying to use it on wordpress site so I preferred to post it here.</p> <p>I am trying to understand the difference between remote post and form post. </p> <p>When I query a string and post it to remote server, I get the result as string and with "print $response" see it on browser console. But I want it to be displayed as html on browser. Am I expecting wrong thing or could i do such thing?</p> <p>Basically I want to see raw response as html.</p> <p><strong>EDIT</strong></p> <p>In case of being more expressive.. I am trying to write credit card payment gateway inside woocommerce</p> <p>Inside process_payment function which is called at the end of customer order, I am posting all info to bank server like below:</p> <pre><code>public function process_payment( $order_id ) { global $woocommerce; .... ... $okUrl = "http://localhost/xxx/wc-api/paymentpos/"; $failUrl = "http://localhost/xxx/wc-api/paymentpos/"; $payload = array(.....); $response = wp_remote_post( $environment_url, array( 'method' =&gt; 'POST', 'body' =&gt; http_build_query( $payload ), 'timeout' =&gt; 45, 'sslverify' =&gt; false, ) ); $respbody = wp_remote_retrieve_body($response); print $respbody; } </code></pre> <p>After that, bank server should reply to payment_callback() which is like</p> <pre><code>public function payment_callback(){ global $woocommerce; wc_add_notice( 'OK', 'success' ); ..... exit(); } </code></pre> <p>I am getting $respbody as below on console.</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt; &lt;html&gt; &lt;head&gt; &lt;META http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; &lt;script type="text/javascript" language="javascript"&gt; function moveWindow() { document.returnform.submit(); } &lt;/script&gt; &lt;/head&gt; &lt;body onLoad="javascript:moveWindow()"&gt; &lt;form action="http://localhost/xxx/wc-api/paymentpos/" method="post" name="returnform"&gt; &lt;input type="hidden" name="EXTRA.ERTELEMESABITTARIH" value="20121123"&gt; .... &lt;input type="hidden" name="okUrl" value="http://localhost/xxx/wc-api/paymentpos/"&gt; ... &lt;input type="hidden" name="mdStatus" value="2"&gt; &lt;input type="hidden" name="HASH" value="QZVV9Zfv4tlzi36WJNbLVlbuWY8="&gt; &lt;input type="hidden" name="rnd" value="GSZV87rHM+Ol5WDiMbtC"&gt; &lt;input type="hidden" name="HASHPARAMS" value="clientid:oid:AuthCode:ProcReturnCode:Response:mdStatus:cavv:eci:md:rnd:"&gt; &lt;input type="hidden" name="HASHPARAMSVAL" value="100200000160451Declined2499850:FE7D7E1062435636DEA77FD3F96CE40C68334FAFE6458F2FC530F26814B29935:4043:##100200000GSZV87rHM+Ol5WDiMbtC"&gt; ... &lt;!-- To support javascript unaware/disabled browsers --&gt; &lt;noscript&gt; &lt;center&gt;&lt;br&gt; Please Click to continue.&lt;br&gt; &lt;input type="submit" name="submit" value="Submit" id="btnSbmt"&gt;&lt;/center&gt; &lt;/noscript&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; {"result":"failure","messages":"","refresh":"false","reload":"false"} </code></pre> <p>This response should trigger payment_callback() function. Manually I could trigger payment_callback() like <a href="http://localhost/xxx/wc-api/paymentpos/" rel="nofollow noreferrer">http://localhost/xxx/wc-api/paymentpos/</a>. But this response could not trigger. I am suspicious about I could handle wp_remote_post response correctly.</p>
[ { "answer_id": 245937, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 0, "selected": false, "text": "<p>You don't need to edit any file. Most of WordPress function can be hook with actions and filters.</p>\n\n<p>Depending on where you want to display your posts, you'll need to search the most appopriate filter to make the job.</p>\n\n<p>An example in your case can be:</p>\n\n<p>I want to display 12 posts from category 'car' except a few post ids (72,121)</p>\n\n<pre><code> function exclude_single_posts($query) {\n if ($query-&gt;category_name == 'car' &amp;&amp; $query-&gt;is_main_query()) {\n $query-&gt;set('post__not_in', array(72,121));\n $query-&gt;set('posts_per_page', 12);\n }\n }\n\n add_action('pre_get_posts', 'exclude_single_posts');\n</code></pre>\n\n<p>Put this on functions.php</p>\n\n<p>There's many way change default arguments to change the query. </p>\n\n<p>For more details search for actions and filters.</p>\n\n<p>Hope it helps</p>\n" }, { "answer_id": 245941, "author": "JHoffmann", "author_id": 63847, "author_profile": "https://wordpress.stackexchange.com/users/63847", "pm_score": 3, "selected": true, "text": "<p>WordPress uses a <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">hierarchy of templates</a> (see the <a href=\"https://developer.wordpress.org/files/2014/10/template-hierarchy.png\" rel=\"nofollow noreferrer\">visual overview</a>) which it checks for presence. In your case when showing a category archive it will check for presence the following files in this order and use the first one it finds:</p>\n\n<ul>\n<li>category-$slug.php (In your case probably category-news-events.php)</li>\n<li>category-$id.php</li>\n<li>category.php</li>\n<li>archive.php</li>\n<li>[paged.php] if paged</li>\n<li>index.php</li>\n</ul>\n\n<p>So if you want to change things for a specific category, you best create a <code>category-$slug.php</code> (copy from <code>category.php</code>). If you want to to modify the general presentation of categories modify <code>category.php</code> directly. If <code>category.php</code> is not present, just use the next existing file according to the hierarchy.</p>\n" }, { "answer_id": 245964, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>Use <a href=\"https://wphierarchy.com/\" rel=\"nofollow noreferrer\">https://wphierarchy.com/</a> to track down the file.</p>\n\n<p>Interactive diagram for the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">template hierachy</a>\n<a href=\"http://wphierarchy.com\" rel=\"nofollow noreferrer\"><img src=\"https://developer.wordpress.org/files/2014/10/template-hierarchy.png\" alt=\"\"></a></p>\n" } ]
2016/11/12
[ "https://wordpress.stackexchange.com/questions/245947", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106036/" ]
Actually it is more general question but now i am trying to use it on wordpress site so I preferred to post it here. I am trying to understand the difference between remote post and form post. When I query a string and post it to remote server, I get the result as string and with "print $response" see it on browser console. But I want it to be displayed as html on browser. Am I expecting wrong thing or could i do such thing? Basically I want to see raw response as html. **EDIT** In case of being more expressive.. I am trying to write credit card payment gateway inside woocommerce Inside process\_payment function which is called at the end of customer order, I am posting all info to bank server like below: ``` public function process_payment( $order_id ) { global $woocommerce; .... ... $okUrl = "http://localhost/xxx/wc-api/paymentpos/"; $failUrl = "http://localhost/xxx/wc-api/paymentpos/"; $payload = array(.....); $response = wp_remote_post( $environment_url, array( 'method' => 'POST', 'body' => http_build_query( $payload ), 'timeout' => 45, 'sslverify' => false, ) ); $respbody = wp_remote_retrieve_body($response); print $respbody; } ``` After that, bank server should reply to payment\_callback() which is like ``` public function payment_callback(){ global $woocommerce; wc_add_notice( 'OK', 'success' ); ..... exit(); } ``` I am getting $respbody as below on console. ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" language="javascript"> function moveWindow() { document.returnform.submit(); } </script> </head> <body onLoad="javascript:moveWindow()"> <form action="http://localhost/xxx/wc-api/paymentpos/" method="post" name="returnform"> <input type="hidden" name="EXTRA.ERTELEMESABITTARIH" value="20121123"> .... <input type="hidden" name="okUrl" value="http://localhost/xxx/wc-api/paymentpos/"> ... <input type="hidden" name="mdStatus" value="2"> <input type="hidden" name="HASH" value="QZVV9Zfv4tlzi36WJNbLVlbuWY8="> <input type="hidden" name="rnd" value="GSZV87rHM+Ol5WDiMbtC"> <input type="hidden" name="HASHPARAMS" value="clientid:oid:AuthCode:ProcReturnCode:Response:mdStatus:cavv:eci:md:rnd:"> <input type="hidden" name="HASHPARAMSVAL" value="100200000160451Declined2499850:FE7D7E1062435636DEA77FD3F96CE40C68334FAFE6458F2FC530F26814B29935:4043:##100200000GSZV87rHM+Ol5WDiMbtC"> ... <!-- To support javascript unaware/disabled browsers --> <noscript> <center><br> Please Click to continue.<br> <input type="submit" name="submit" value="Submit" id="btnSbmt"></center> </noscript> </form> </body> </html> {"result":"failure","messages":"","refresh":"false","reload":"false"} ``` This response should trigger payment\_callback() function. Manually I could trigger payment\_callback() like <http://localhost/xxx/wc-api/paymentpos/>. But this response could not trigger. I am suspicious about I could handle wp\_remote\_post response correctly.
WordPress uses a [hierarchy of templates](https://developer.wordpress.org/themes/basics/template-hierarchy/) (see the [visual overview](https://developer.wordpress.org/files/2014/10/template-hierarchy.png)) which it checks for presence. In your case when showing a category archive it will check for presence the following files in this order and use the first one it finds: * category-$slug.php (In your case probably category-news-events.php) * category-$id.php * category.php * archive.php * [paged.php] if paged * index.php So if you want to change things for a specific category, you best create a `category-$slug.php` (copy from `category.php`). If you want to to modify the general presentation of categories modify `category.php` directly. If `category.php` is not present, just use the next existing file according to the hierarchy.
246,004
<p>I just want to start out by saying, that I have tried multiple things before I resorted to writing this entry. You guys are my only hope.</p> <p>My site works in Chrome, but disappears in Firefox or Safari. </p> <p><strong>Things I have tried:</strong> </p> <ul> <li>Added register script then enqueue; In hopes that my grid-12.css is loaded before frontstyle.css(grid-12.css has jumbotron code; bootstrap.css just has my modal.) <ul> <li>Moving the end of my while/endif; wp_reset_postdata to the bottom of my jumbotron.</li> <li>Put my jumbotron as inline css instead of in the style sheet.(currently); Splitting the css does not work for some reason.</li> <li>Put jumbotron in front-style.css(main stylesheet)</li> <li>Making grid-12.css a dependency of my front-style.css(currently)</li> <li>And a few other things....</li> </ul></li> </ul> <p><strong>function.php:</strong></p> <pre><code>function _cc_scripts() { wp_register_style('grid_12', get_template_directory_uri() . '/inc/css/grid12.css'); wp_register_style('normalize_css', get_template_directory_uri() . '/inc/css/normalize.css'); wp_register_style('bootstrap_css', get_template_directory_uri() . '/inc/css/bootstrap.css'); wp_register_style('front_css', get_template_directory_uri() . '/inc/css/front-style.css', 'grid_12'); wp_register_style( 'main_style', get_template_directory_uri() . '/style.css'); wp_register_style('animate_css', get_template_directory_uri() . '/inc/css/animate.css'); wp_register_style( 'font-awesome', '//maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css', array(), '4.6.1' ); wp_register_style( '_cc-style', get_stylesheet_uri() ); wp_register_style( '_cc-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true ); wp_enqueue_style('grid_12'); wp_enqueue_style('normalize_css'); wp_enqueue_style('bootstrap_css'); wp_enqueue_style('front_css'); wp_enqueue_style('main_style'); wp_enqueue_style('animate_css'); wp_enqueue_style('font-awesome'); wp_enqueue_style('_cc-style'); wp_enqueue_style('_cc-skip-link-focus-fix'); if ( is_singular() &amp;&amp; comments_open() &amp;&amp; get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } } // End of _cc_scripts() add_action( 'wp_enqueue_scripts', '_cc_scripts' ); </code></pre> <p><strong>header.php:</strong></p> <pre><code>&lt;?php $args = array( 'category_name' =&gt; 'jumbotron', ); $the_query = new WP_Query( $args ); ?&gt; &lt;?php if ( have_posts() ): while ( $the_query-&gt;have_posts() ): $the_query-&gt;the_post(); ?&gt; &lt;?php $thumbnail_jumbo = get_post_thumbnail_id($post-&gt;ID); $featuredImage = wp_get_attachment_image_src( $thumbnail_jumbo , 'full'); $thumbnail_jumbo = $featuredImage[0]; list($width, $height) = getimagesize($thumbnail_jumbo); ?&gt; &lt;div class="jumbotron"&gt; &lt;style type="text/css"&gt; .jumbotron { background: no-repeat center right fixed url('&lt;?php echo $thumbnail_jumbo ?&gt;'); padding:0; margin-bottom: 0px; max-width:100%; min-height: 500px; background-size: 100%; box-shadow:0px 0px 10px #000; -webkit-background-size: 100%; -moz-background-size: 100%; -o-background-size: 100%; background-size: cover; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; } &lt;/style&gt; &lt;div class="scroll-down text-center hidden-sm hidden-md hidden-lg"&gt; &lt;a href="#" class="about"&gt;&lt;span class="icon-down"&gt; &lt;i class="fa fa-chevron-down fa-3x"&gt;&lt;/i&gt;&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; endif; wp_reset_postdata(); ?&gt; </code></pre> <p><strong>Other things to note</strong></p> <ul> <li>I'm trying to avoid inline CSS.</li> <li>Custom Css needs to be loaded after Bootstrap.css(in this case grid-12.css)</li> </ul> <p>Right now, on Safari/Firefox, I can see the color of the picture/jumbotron behind my navbar but it does not stretch and take up the space I want it to. </p> <p>Thanks any advice on this would be great.</p>
[ { "answer_id": 245937, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 0, "selected": false, "text": "<p>You don't need to edit any file. Most of WordPress function can be hook with actions and filters.</p>\n\n<p>Depending on where you want to display your posts, you'll need to search the most appopriate filter to make the job.</p>\n\n<p>An example in your case can be:</p>\n\n<p>I want to display 12 posts from category 'car' except a few post ids (72,121)</p>\n\n<pre><code> function exclude_single_posts($query) {\n if ($query-&gt;category_name == 'car' &amp;&amp; $query-&gt;is_main_query()) {\n $query-&gt;set('post__not_in', array(72,121));\n $query-&gt;set('posts_per_page', 12);\n }\n }\n\n add_action('pre_get_posts', 'exclude_single_posts');\n</code></pre>\n\n<p>Put this on functions.php</p>\n\n<p>There's many way change default arguments to change the query. </p>\n\n<p>For more details search for actions and filters.</p>\n\n<p>Hope it helps</p>\n" }, { "answer_id": 245941, "author": "JHoffmann", "author_id": 63847, "author_profile": "https://wordpress.stackexchange.com/users/63847", "pm_score": 3, "selected": true, "text": "<p>WordPress uses a <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">hierarchy of templates</a> (see the <a href=\"https://developer.wordpress.org/files/2014/10/template-hierarchy.png\" rel=\"nofollow noreferrer\">visual overview</a>) which it checks for presence. In your case when showing a category archive it will check for presence the following files in this order and use the first one it finds:</p>\n\n<ul>\n<li>category-$slug.php (In your case probably category-news-events.php)</li>\n<li>category-$id.php</li>\n<li>category.php</li>\n<li>archive.php</li>\n<li>[paged.php] if paged</li>\n<li>index.php</li>\n</ul>\n\n<p>So if you want to change things for a specific category, you best create a <code>category-$slug.php</code> (copy from <code>category.php</code>). If you want to to modify the general presentation of categories modify <code>category.php</code> directly. If <code>category.php</code> is not present, just use the next existing file according to the hierarchy.</p>\n" }, { "answer_id": 245964, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>Use <a href=\"https://wphierarchy.com/\" rel=\"nofollow noreferrer\">https://wphierarchy.com/</a> to track down the file.</p>\n\n<p>Interactive diagram for the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">template hierachy</a>\n<a href=\"http://wphierarchy.com\" rel=\"nofollow noreferrer\"><img src=\"https://developer.wordpress.org/files/2014/10/template-hierarchy.png\" alt=\"\"></a></p>\n" } ]
2016/11/13
[ "https://wordpress.stackexchange.com/questions/246004", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94933/" ]
I just want to start out by saying, that I have tried multiple things before I resorted to writing this entry. You guys are my only hope. My site works in Chrome, but disappears in Firefox or Safari. **Things I have tried:** * Added register script then enqueue; In hopes that my grid-12.css is loaded before frontstyle.css(grid-12.css has jumbotron code; bootstrap.css just has my modal.) + Moving the end of my while/endif; wp\_reset\_postdata to the bottom of my jumbotron. + Put my jumbotron as inline css instead of in the style sheet.(currently); Splitting the css does not work for some reason. + Put jumbotron in front-style.css(main stylesheet) + Making grid-12.css a dependency of my front-style.css(currently) + And a few other things.... **function.php:** ``` function _cc_scripts() { wp_register_style('grid_12', get_template_directory_uri() . '/inc/css/grid12.css'); wp_register_style('normalize_css', get_template_directory_uri() . '/inc/css/normalize.css'); wp_register_style('bootstrap_css', get_template_directory_uri() . '/inc/css/bootstrap.css'); wp_register_style('front_css', get_template_directory_uri() . '/inc/css/front-style.css', 'grid_12'); wp_register_style( 'main_style', get_template_directory_uri() . '/style.css'); wp_register_style('animate_css', get_template_directory_uri() . '/inc/css/animate.css'); wp_register_style( 'font-awesome', '//maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css', array(), '4.6.1' ); wp_register_style( '_cc-style', get_stylesheet_uri() ); wp_register_style( '_cc-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true ); wp_enqueue_style('grid_12'); wp_enqueue_style('normalize_css'); wp_enqueue_style('bootstrap_css'); wp_enqueue_style('front_css'); wp_enqueue_style('main_style'); wp_enqueue_style('animate_css'); wp_enqueue_style('font-awesome'); wp_enqueue_style('_cc-style'); wp_enqueue_style('_cc-skip-link-focus-fix'); if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } } // End of _cc_scripts() add_action( 'wp_enqueue_scripts', '_cc_scripts' ); ``` **header.php:** ``` <?php $args = array( 'category_name' => 'jumbotron', ); $the_query = new WP_Query( $args ); ?> <?php if ( have_posts() ): while ( $the_query->have_posts() ): $the_query->the_post(); ?> <?php $thumbnail_jumbo = get_post_thumbnail_id($post->ID); $featuredImage = wp_get_attachment_image_src( $thumbnail_jumbo , 'full'); $thumbnail_jumbo = $featuredImage[0]; list($width, $height) = getimagesize($thumbnail_jumbo); ?> <div class="jumbotron"> <style type="text/css"> .jumbotron { background: no-repeat center right fixed url('<?php echo $thumbnail_jumbo ?>'); padding:0; margin-bottom: 0px; max-width:100%; min-height: 500px; background-size: 100%; box-shadow:0px 0px 10px #000; -webkit-background-size: 100%; -moz-background-size: 100%; -o-background-size: 100%; background-size: cover; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; } </style> <div class="scroll-down text-center hidden-sm hidden-md hidden-lg"> <a href="#" class="about"><span class="icon-down"> <i class="fa fa-chevron-down fa-3x"></i></span> </a> </div> </div> <?php endwhile; endif; wp_reset_postdata(); ?> ``` **Other things to note** * I'm trying to avoid inline CSS. * Custom Css needs to be loaded after Bootstrap.css(in this case grid-12.css) Right now, on Safari/Firefox, I can see the color of the picture/jumbotron behind my navbar but it does not stretch and take up the space I want it to. Thanks any advice on this would be great.
WordPress uses a [hierarchy of templates](https://developer.wordpress.org/themes/basics/template-hierarchy/) (see the [visual overview](https://developer.wordpress.org/files/2014/10/template-hierarchy.png)) which it checks for presence. In your case when showing a category archive it will check for presence the following files in this order and use the first one it finds: * category-$slug.php (In your case probably category-news-events.php) * category-$id.php * category.php * archive.php * [paged.php] if paged * index.php So if you want to change things for a specific category, you best create a `category-$slug.php` (copy from `category.php`). If you want to to modify the general presentation of categories modify `category.php` directly. If `category.php` is not present, just use the next existing file according to the hierarchy.
246,026
<p>I use Multi-Site at <code>example.com</code>. Is there any simple method to redirect users to specific blog dashboard? for example, when I login at:</p> <p><code>example.com/wp-login.php</code> instead of default redirection to </p> <p><code>example.com/wp-admin</code> I want to be redirected to</p> <p><code>example.com/sub-site/wp-admin</code></p>
[ { "answer_id": 251374, "author": "malik irfan", "author_id": 110267, "author_profile": "https://wordpress.stackexchange.com/users/110267", "pm_score": 1, "selected": false, "text": "<p>please see this it working fine for me :)</p>\n\n<pre><code>function uop_login_redirect( $redirect_to, $request, $user ) {\n return ( is_array( $user-&gt;roles ) &amp;&amp; in_array( 'administrator', $user-&gt;roles ) ) ? admin_url() : site_url();\n}\nadd_filter( 'login_redirect', 'uop_login_redirect', 10, 3 );\n</code></pre>\n" }, { "answer_id": 251376, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 0, "selected": false, "text": "<p>I use this:</p>\n\n<pre><code>// redirecting to chosen language dashboard \nadd_filter( 'login_redirect', 'admin_redirect', 10, 3 ); //\nfunction admin_redirect( $redirect_to, $request, $user ) {\n if(isset($_POST['redirect_to']) &amp;&amp; $_POST['redirect_to']==network_home_url().'wp-admin/') {\n //is there a user to check?\n if ( isset( $user-&gt;roles ) &amp;&amp; is_array( $user-&gt;roles ) ) {\n return network_home_url().'eng/wp-admin';\n }\n }\n else { return $redirect_to; }\n}\n</code></pre>\n" } ]
2016/11/13
[ "https://wordpress.stackexchange.com/questions/246026", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33667/" ]
I use Multi-Site at `example.com`. Is there any simple method to redirect users to specific blog dashboard? for example, when I login at: `example.com/wp-login.php` instead of default redirection to `example.com/wp-admin` I want to be redirected to `example.com/sub-site/wp-admin`
please see this it working fine for me :) ``` function uop_login_redirect( $redirect_to, $request, $user ) { return ( is_array( $user->roles ) && in_array( 'administrator', $user->roles ) ) ? admin_url() : site_url(); } add_filter( 'login_redirect', 'uop_login_redirect', 10, 3 ); ```
246,028
<p>I would like to create an Angular 2 SPA that uses the WordPress REST API as a back-end. How can I use the API to fetch the page the user has set as their front page?</p>
[ { "answer_id": 246035, "author": "Connel", "author_id": 42843, "author_profile": "https://wordpress.stackexchange.com/users/42843", "pm_score": 1, "selected": false, "text": "<p>I have just got this working using the plugin 'WP API Options' plugin. You can find the plugin here:\n<a href=\"https://en-gb.wordpress.org/plugins/wp-rest-api-options/\" rel=\"nofollow noreferrer\">https://en-gb.wordpress.org/plugins/wp-rest-api-options/</a></p>\n\n<p>It allows you to see which page has been configured as the front page. Below is a TypeScript code snippet that uses the 'wp-api-angular' package.</p>\n\n<pre><code>getFrontPage(): Promise&lt;any&gt; {\n return this.wpApiPages\n .httpGet('/options/page_on_front')\n .toPromise()\n .then(response =&gt; response.json())\n .then(body =&gt; body.page_on_front)\n .then(frontPageId =&gt; this.wpApiPages\n .get(frontPageId)\n .toPromise()\n .then(response =&gt; response.json()))\n .catch(error =&gt; {});\n}\n</code></pre>\n" }, { "answer_id": 246036, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": false, "text": "<p>We could implement our own endpoint:</p>\n\n<pre><code>https://example.tld/wpse/v1/frontpage\n</code></pre>\n\n<p>Here's a simple demo (<em>PHP 5.4+</em>):</p>\n\n<pre><code>&lt;?php\n/** \n * Plugin Name: WPSE - Static Frontpage Rest Endpoint\n */\nnamespace WPSE\\RestAPI\\Frontpage;\n\n\\add_action( 'rest_api_init', function()\n{\n \\register_rest_route( 'wpse/v1', '/frontpage/', \n [\n 'methods' =&gt; 'GET',\n 'callback' =&gt; __NAMESPACE__.'\\rest_results'\n ] \n );\n} );\n\nfunction rest_results( $request )\n{\n // Get the ID of the static frontpage. If not set it's 0\n $pid = (int) \\get_option( 'page_on_front' ); \n\n // Get the corresponding post object (let's show our intention explicitly)\n $post = ( $pid &gt; 0 ) ? \\get_post( $pid ) : null; \n\n // No static frontpage is set\n if( ! is_a( $post, '\\WP_Post' ) )\n return new \\WP_Error( 'wpse-error', \n \\esc_html__( 'No Static Frontpage', 'wpse' ), [ 'status' =&gt; 404 ] );\n\n // Response setup\n $data = [\n 'ID' =&gt; $post-&gt;ID,\n 'content' =&gt; [ 'raw' =&gt; $post-&gt;post_content ]\n ];\n\n return new \\WP_REST_Response( $data, 200 ); \n}\n</code></pre>\n\n<p>A successful response is like:</p>\n\n<pre><code>{\"ID\":123,\"content\":{\"raw\":\"Some content\"}}\n</code></pre>\n\n<p>and an error response is like:</p>\n\n<pre><code>{\"code\":\"wpse-error\",\"message\":\"No Static Frontpage\",\"data\":{\"status\":404}}\n</code></pre>\n\n<p>Then we can extend it to support other fields or <em>rendered</em> content by applying the <code>the_content</code> filter.</p>\n" }, { "answer_id": 266480, "author": "Marnix Harderwijk", "author_id": 119391, "author_profile": "https://wordpress.stackexchange.com/users/119391", "pm_score": 2, "selected": false, "text": "<p>Because I build several Polymer &amp; Angular SPA's for the frontend with WordPress backends I've created a plugin for this purpose <a href=\"https://wordpress.org/plugins/wp-rest-api-frontpage/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-rest-api-frontpage/</a></p>\n\n<p>I hope this helps...</p>\n\n<p>Basically it extends the native REST API with a new route:</p>\n\n<pre><code>wp-json/wp/v2/frontpage\n</code></pre>\n\n<p>Cheers!</p>\n" }, { "answer_id": 315035, "author": "mustra", "author_id": 151200, "author_profile": "https://wordpress.stackexchange.com/users/151200", "pm_score": 1, "selected": false, "text": "<p>This happens to be very simple. WordPress doesn't have frontpage endpoint by default but you can create one like this.</p>\n\n<pre><code>// Register Front Page route.\n// URL will be: domainname.ext/wp-json/my-namespace/v1/frontpage/\nregister_rest_route(\n 'my-namespace/v1', '/frontpage',\n array(\n 'methods' =&gt; 'GET',\n 'callback' =&gt; [ $this, 'get_frontpage' ],\n )\n);\n\n\n// Callback function.\nfunction get_frontpage( $object ) {\n\n // Get WP options front page from settings &gt; reading.\n $frontpage_id = get_option('page_on_front');\n\n // Handle if error.\n if ( empty( $frontpage_id ) ) {\n // return error\n return 'error';\n }\n\n // Create request from pages endpoint by frontpage id.\n $request = new \\WP_REST_Request( 'GET', '/wp/v2/pages/' . $frontpage_id );\n\n // Parse request to get data.\n $response = rest_do_request( $request );\n\n // Handle if error.\n if ( $response-&gt;is_error() ) {\n return 'error';\n }\n\n return $response-&gt;get_data();\n}\n</code></pre>\n" } ]
2016/11/13
[ "https://wordpress.stackexchange.com/questions/246028", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/42843/" ]
I would like to create an Angular 2 SPA that uses the WordPress REST API as a back-end. How can I use the API to fetch the page the user has set as their front page?
We could implement our own endpoint: ``` https://example.tld/wpse/v1/frontpage ``` Here's a simple demo (*PHP 5.4+*): ``` <?php /** * Plugin Name: WPSE - Static Frontpage Rest Endpoint */ namespace WPSE\RestAPI\Frontpage; \add_action( 'rest_api_init', function() { \register_rest_route( 'wpse/v1', '/frontpage/', [ 'methods' => 'GET', 'callback' => __NAMESPACE__.'\rest_results' ] ); } ); function rest_results( $request ) { // Get the ID of the static frontpage. If not set it's 0 $pid = (int) \get_option( 'page_on_front' ); // Get the corresponding post object (let's show our intention explicitly) $post = ( $pid > 0 ) ? \get_post( $pid ) : null; // No static frontpage is set if( ! is_a( $post, '\WP_Post' ) ) return new \WP_Error( 'wpse-error', \esc_html__( 'No Static Frontpage', 'wpse' ), [ 'status' => 404 ] ); // Response setup $data = [ 'ID' => $post->ID, 'content' => [ 'raw' => $post->post_content ] ]; return new \WP_REST_Response( $data, 200 ); } ``` A successful response is like: ``` {"ID":123,"content":{"raw":"Some content"}} ``` and an error response is like: ``` {"code":"wpse-error","message":"No Static Frontpage","data":{"status":404}} ``` Then we can extend it to support other fields or *rendered* content by applying the `the_content` filter.
246,037
<p>I want to add an option in pages' backend.<br> Searching on the internet I find guides on how to create a backend page dedicated to options esclusively. I'd like to add an option to a page instead, under the page content editor (or on the right sidebar).<br><br> Can anyone help me?</p>
[ { "answer_id": 246039, "author": "vol4ikman", "author_id": 31075, "author_profile": "https://wordpress.stackexchange.com/users/31075", "pm_score": 0, "selected": false, "text": "<p>I think, the easiest way for you is:\n<a href=\"https://wordpress.org/plugins/advanced-custom-fields/\" rel=\"nofollow\">Advanced custom fields plugin</a></p>\n" }, { "answer_id": 246042, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 2, "selected": false, "text": "<p>To add a option box for a page or post, you need to use <code>add_meta_boxes</code> action.</p>\n\n<pre><code> //Register Meta Box\n function register_meta_box() {\n add_meta_box(\n 'meta-box-id',\n __( 'MetaBox Title', 'text-domain' ), \n 'meta_box_callback', \n 'post', \n 'advanced', \n 'high' \n );\n }\n add_action( 'add_meta_boxes', 'register_meta_box');\n\n //Add field\n function meta_box_callback( $post_id ) {\n\n $output = '&lt;label for=\"title_field\"&gt;'. esc_html__('Title Field', 'text-domain') .'&lt;/label&gt;';\n $title_field = get_post_meta( $post_id-&gt;ID, 'title_field', true );\n $output .= '&lt;input type=\"text\" name=\"title_field\" id=\"title_field\" class=\"title_field\" value=\"'. esc_attr($title_field) .'\" /&gt;';\n\n echo $output;\n }\n\n// Save meta field\nadd_action('save_post', 'save_meta_field');\n\nfunction save_meta_field($post_id){\n // Check nonce, sanitize field\n update_post_meta($post_id, 'title_field', $_POST['title_field']);\n}\n</code></pre>\n\n<p>The <code>add_meta_box()</code> parameters must be set to fit your needs (advanced and 'high'), and of course the field name and the screen(s) where your want the box to appears.</p>\n\n<p>You will find more details about <code>add_meta_boxes</code> <a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow\">here</a></p>\n\n<p>Hope it helps</p>\n" } ]
2016/11/13
[ "https://wordpress.stackexchange.com/questions/246037", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106889/" ]
I want to add an option in pages' backend. Searching on the internet I find guides on how to create a backend page dedicated to options esclusively. I'd like to add an option to a page instead, under the page content editor (or on the right sidebar). Can anyone help me?
To add a option box for a page or post, you need to use `add_meta_boxes` action. ``` //Register Meta Box function register_meta_box() { add_meta_box( 'meta-box-id', __( 'MetaBox Title', 'text-domain' ), 'meta_box_callback', 'post', 'advanced', 'high' ); } add_action( 'add_meta_boxes', 'register_meta_box'); //Add field function meta_box_callback( $post_id ) { $output = '<label for="title_field">'. esc_html__('Title Field', 'text-domain') .'</label>'; $title_field = get_post_meta( $post_id->ID, 'title_field', true ); $output .= '<input type="text" name="title_field" id="title_field" class="title_field" value="'. esc_attr($title_field) .'" />'; echo $output; } // Save meta field add_action('save_post', 'save_meta_field'); function save_meta_field($post_id){ // Check nonce, sanitize field update_post_meta($post_id, 'title_field', $_POST['title_field']); } ``` The `add_meta_box()` parameters must be set to fit your needs (advanced and 'high'), and of course the field name and the screen(s) where your want the box to appears. You will find more details about `add_meta_boxes` [here](https://developer.wordpress.org/reference/functions/add_meta_box/) Hope it helps
246,055
<p>I'm looking for a function that will count and show .jpg URLs or images in my post and then echo the results (eg. 12 images).</p> <p>I've only found a way to count the attached images in the post. I also found an xpath function but I'm not sure if it is working, because I can't get it to echo the results.</p> <p>Here's what I have so far:</p> <pre><code>function post_photo_count_xpath( $post_id ) { global $wpdb; $post_id_safe = intval( $post_id ); $html = $wpdb-&gt;get_row( "select * from {$wpdb-&gt;posts} where ID={$post_id_safe} limit 1" ); $doc = new DOMDocument(); @$doc-&gt;loadHTML( $html-&gt;post_content ); $path = new DOMXpath( $doc ); $images = $path-&gt;query( "//img" ); return( $images-&gt;length ); } </code></pre>
[ { "answer_id": 246057, "author": "Shamsur Rahman", "author_id": 92258, "author_profile": "https://wordpress.stackexchange.com/users/92258", "pm_score": 0, "selected": false, "text": "<p>for more information visit <a href=\"https://blog.josemcastaneda.com/2014/03/18/get-image-count-in-wordpress-post/\" rel=\"nofollow noreferrer\">https://blog.josemcastaneda.com/2014/03/18/get-image-count-in-wordpress-post/</a></p>\n\n<pre><code>// Get all the galleries in the current post\n $galleries = get_post_galleries( get_the_ID(), false );\n // Count all the galleries\n $total_gal = count( $galleries );\n /**\n * count all the images\n * @param array $array The array needed\n * @return int returns the number of images in the post\n */\n function _get_total_images( $array ){\n $key = 0;\n $src = 0;\n while ( $key &lt; count( $array ) ){\n $src += count( $array[$key]['src'] );\n $key++;\n }\n return intval( $src );\n }\n\n echo _get_total_images( $galleries );\n</code></pre>\n" }, { "answer_id": 246058, "author": "sMyles", "author_id": 51201, "author_profile": "https://wordpress.stackexchange.com/users/51201", "pm_score": 0, "selected": false, "text": "<p>To get all the image URLs from HTML content, or a PHP string/variable, and filter them by a specific extension, and only include remote domains, use this code:</p>\n\n<pre><code>$data = 'alsdj&lt;img src=\"http://localdomain.com/donotinclude.jpg\"&gt;fklasjdf&lt;img src=\"image.jpg\"&gt;asdfasdf&lt;img src=\"http://remotedomain.com/image.jpg\"&gt;asdfasdfsf&lt;img src=\"dont_include_me.png\"&gt;asdfasfasdf';\n$images = array();\n\n// Domains to not include images from (for instances where the full URL is specified to image)\n$localhosts = array( 'localdomain.com' );\n// Remove or add any extensions TO be included\n$allowed_extensions = array( 'jpg', 'jpeg' );\n\npreg_match_all('/(img|src)\\=(\\\"|\\')[^\\\"\\'\\&gt;]+/i', $data, $media);\nunset($data);\n$data=preg_replace('/(img|src)(\\\"|\\'|\\=\\\"|\\=\\')(.*)/i',\"$3\",$media[0]);\n\n\nforeach($data as $url)\n{\n $url_data = parse_url( $url );\n $info = pathinfo($url);\n\n // Goto next, we're only looking for remote hosts\n if( ! array_key_exists( 'host', $url_data ) ) continue;\n\n // Check if this is an extension we want to include\n if( array_key_exists( 'extension', $info ) &amp;&amp; in_array( $info['extension'], $allowed_extensions) ){\n\n // Verify this isn't one of our local hosts (where the full URL is specified)\n if( ! in_array( $url_data['host'], $localhosts ) ){\n array_push($images, $url);\n }\n\n }\n\n}\n\necho 'Total Images: ' . count( $images );\n// This is just linebreaks for display formatting\nprint \"\\n\\n\";\necho 'Image Data:';\nvar_dump( $images );\n</code></pre>\n\n<p>Example of code:\n<a href=\"https://glot.io/snippets/ekahzvu8sh\" rel=\"nofollow noreferrer\">https://glot.io/snippets/ekahzvu8sh</a></p>\n\n<p>Result output of code example above:</p>\n\n<pre><code>Total Images: 1\n\nImage Data:array(1) {\n [0]=&gt;\n string(27) \"http://remotedomain.com/image.jpg\"\n}\n</code></pre>\n\n<p>Make sure you set what your domain is in the <code>$localhosts</code> array, that way if for some reason the full URL is specified, it won't include that one.</p>\n\n<p>Using the example code from above, here's your updated function to use that code and return the number of images:</p>\n\n<pre><code>function post_photo_count_xpath( $post_id ) {\n\n $post = get_post( $post_id );\n if( ! $post ) return 0;\n\n $data = $post-&gt;post_content;\n $images = array();\n // Domains to not include images from (for instances where the full URL is specified to image)\n $localhosts = array( 'localdomain.com' );\n // Remove or add any extensions TO be included\n $allowed_extensions = array( 'jpg', 'jpeg' );\n\n preg_match_all('/(img|src)\\=(\\\"|\\')[^\\\"\\'\\&gt;]+/i', $data, $media);\n unset($data);\n $data=preg_replace('/(img|src)(\\\"|\\'|\\=\\\"|\\=\\')(.*)/i',\"$3\",$media[0]);\n\n if( empty( $data ) ) return 0;\n\n foreach( $data as $url ){\n $url_data = parse_url( $url );\n $info = pathinfo($url);\n\n // Goto next, we're only looking for remote hosts\n if( ! array_key_exists( 'host', $url_data ) ) continue;\n\n // Check if this is an extension we want to include\n if( array_key_exists( 'extension', $info ) &amp;&amp; in_array( $info['extension'], $allowed_extensions) ){\n\n // Verify this isn't one of our local hosts (where the full URL is specified)\n if( ! in_array( $url_data['host'], $localhosts ) ){\n array_push($images, $url);\n }\n\n }\n\n }\n\n return count( $images );\n}\n</code></pre>\n\n<p>Resource:\n<a href=\"https://davebrooks.wordpress.com/2009/04/22/php-preg_replace-some-useful-regular-expressions/\" rel=\"nofollow noreferrer\">https://davebrooks.wordpress.com/2009/04/22/php-preg_replace-some-useful-regular-expressions/</a></p>\n" }, { "answer_id": 246063, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 3, "selected": true, "text": "<p>Use regex to find all the urls and filter by type.</p>\n\n<pre><code>$post = get_post( 504 );\n$content = $post-&gt;post_content;\n\n// match all urls\npreg_match_all( '/(http:|https:)?\\/\\/([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&amp;:\\/~+#-]*[\\w@?^=%&amp;\\/~+#-])?/', $content, $matches );\n\n$count = 0;\nif ( ! empty( $matches ) &amp;&amp; ! empty( $matches[ 0 ] ) ) {\n foreach ( $matches[ 0 ] as $url ) {\n $split = explode( '#', $url );\n $split = explode( '?', $split[ 0 ] );\n $split = explode( '&amp;', $split[ 0 ] );\n $filename = basename( $split[ 0 ] );\n $file_type = wp_check_filetype( $filename, wp_get_mime_types() );\n if ( ! empty ( $file_type[ 'ext' ] ) ) {\n\n // (optional) limit inclusion based on file type\n if( ! in_array( $file_type[ 'ext' ], array('jpg', 'png')) ) continue;\n\n $files[ $url ] = $file_type;\n $urls[]=$url;\n $count ++;\n }\n }\n}\n\n// print out urls and total count\nprint_r( array ( \n 'total' =&gt; $count, \n 'unique' =&gt; array_keys( $files ),\n 'urls' =&gt; $urls \n) );\n</code></pre>\n\n<hr>\n\n<h2>OOP</h2>\n\n<p>If you want this as a reusable function...</p>\n\n<pre><code>function get_file_urls( $content = '', $file_types = array ( 'jpg', 'png' ) ) {\n\n // match all urls\n preg_match_all( '/(http:|https:)?\\/\\/([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&amp;:\\/~+#-]*[\\w@?^=%&amp;\\/~+#-])?/', $content, $matches );\n\n $urls = array ();\n $files = array ();\n\n if ( ! empty( $matches ) &amp;&amp; ! empty( $matches[ 0 ] ) ) {\n foreach ( $matches[ 0 ] as $url ) {\n $split = explode( '#', $url );\n $split = explode( '?', $split[ 0 ] );\n $split = explode( '&amp;', $split[ 0 ] );\n $filename = basename( $split[ 0 ] );\n $file_type = wp_check_filetype( $filename, wp_get_mime_types() );\n if ( ! empty ( $file_type[ 'ext' ] ) ) {\n\n // (optional) limit inclusion based on file type\n if ( ! in_array( $file_type[ 'ext' ], $file_types ) ) {\n continue;\n }\n\n $files[ $url ] = $file_type;\n $urls[] = $url;\n }\n }\n }\n\n // print out urls and total count\n return array (\n 'total' =&gt; count( $urls ),\n 'urls' =&gt; $urls,\n 'total_unique' =&gt; count( $files ),\n 'unique' =&gt; array_keys( $files ),\n );\n}\n\n$post = get_post( 504 );\n$content = $post-&gt;post_content;\n$file_urls = get_file_urls( $content, array ( 'jpg' ) );\n$count = $file_urls[ 'total' ];\n\necho \"&lt;div class='count'&gt;${count}&lt;/div&gt;\";\n</code></pre>\n" } ]
2016/11/14
[ "https://wordpress.stackexchange.com/questions/246055", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106901/" ]
I'm looking for a function that will count and show .jpg URLs or images in my post and then echo the results (eg. 12 images). I've only found a way to count the attached images in the post. I also found an xpath function but I'm not sure if it is working, because I can't get it to echo the results. Here's what I have so far: ``` function post_photo_count_xpath( $post_id ) { global $wpdb; $post_id_safe = intval( $post_id ); $html = $wpdb->get_row( "select * from {$wpdb->posts} where ID={$post_id_safe} limit 1" ); $doc = new DOMDocument(); @$doc->loadHTML( $html->post_content ); $path = new DOMXpath( $doc ); $images = $path->query( "//img" ); return( $images->length ); } ```
Use regex to find all the urls and filter by type. ``` $post = get_post( 504 ); $content = $post->post_content; // match all urls preg_match_all( '/(http:|https:)?\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/', $content, $matches ); $count = 0; if ( ! empty( $matches ) && ! empty( $matches[ 0 ] ) ) { foreach ( $matches[ 0 ] as $url ) { $split = explode( '#', $url ); $split = explode( '?', $split[ 0 ] ); $split = explode( '&', $split[ 0 ] ); $filename = basename( $split[ 0 ] ); $file_type = wp_check_filetype( $filename, wp_get_mime_types() ); if ( ! empty ( $file_type[ 'ext' ] ) ) { // (optional) limit inclusion based on file type if( ! in_array( $file_type[ 'ext' ], array('jpg', 'png')) ) continue; $files[ $url ] = $file_type; $urls[]=$url; $count ++; } } } // print out urls and total count print_r( array ( 'total' => $count, 'unique' => array_keys( $files ), 'urls' => $urls ) ); ``` --- OOP --- If you want this as a reusable function... ``` function get_file_urls( $content = '', $file_types = array ( 'jpg', 'png' ) ) { // match all urls preg_match_all( '/(http:|https:)?\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/', $content, $matches ); $urls = array (); $files = array (); if ( ! empty( $matches ) && ! empty( $matches[ 0 ] ) ) { foreach ( $matches[ 0 ] as $url ) { $split = explode( '#', $url ); $split = explode( '?', $split[ 0 ] ); $split = explode( '&', $split[ 0 ] ); $filename = basename( $split[ 0 ] ); $file_type = wp_check_filetype( $filename, wp_get_mime_types() ); if ( ! empty ( $file_type[ 'ext' ] ) ) { // (optional) limit inclusion based on file type if ( ! in_array( $file_type[ 'ext' ], $file_types ) ) { continue; } $files[ $url ] = $file_type; $urls[] = $url; } } } // print out urls and total count return array ( 'total' => count( $urls ), 'urls' => $urls, 'total_unique' => count( $files ), 'unique' => array_keys( $files ), ); } $post = get_post( 504 ); $content = $post->post_content; $file_urls = get_file_urls( $content, array ( 'jpg' ) ); $count = $file_urls[ 'total' ]; echo "<div class='count'>${count}</div>"; ```
246,067
<p>I have a stuck that make me headache so much, as you see picture, this is my result when i add option to event.</p> <p><a href="https://i.stack.imgur.com/aofam.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aofam.png" alt="enter image description here"></a></p> <p>I'm updated code in: <code>wp-content/theme/mytheme/lib/metabox/function.php</code></p> <pre><code>$meta_boxes[] = array( 'id' =&gt; 'event_date_option', 'title' =&gt; __( 'Event options', 'mytheme' ), 'pages' =&gt; array( Custom_Posts_Type_Event::POST_TYPE ), // Post type 'context' =&gt; 'normal', 'priority' =&gt; 'high', 'show_names' =&gt; true, // Show field names on the left 'fields' =&gt; array( array( 'name' =&gt; __( 'Event type:', 'mytheme' ), 'desc' =&gt; __( 'Choose event type', 'mytheme' ), 'id' =&gt; SHORTNAME . Widget_Event::EVENT_INTERVAL_META_KEY, 'type' =&gt; 'select', 'options' =&gt; array( array( 'value'=&gt;"n" , 'name' =&gt; __( 'Normal', 'mytheme' ) ), array( 'value'=&gt;"c" , 'name' =&gt; __( 'Comunity', 'mytheme' ) ), ), ) </code></pre> <p>It's show in event post, but i don't know how to save when add new event OR when i'm update event post. Please help me, thank you!</p> <p>Ahh, i save it in database with new table like: ID_POST, VALUE</p> <p>Thank you!</p>
[ { "answer_id": 246057, "author": "Shamsur Rahman", "author_id": 92258, "author_profile": "https://wordpress.stackexchange.com/users/92258", "pm_score": 0, "selected": false, "text": "<p>for more information visit <a href=\"https://blog.josemcastaneda.com/2014/03/18/get-image-count-in-wordpress-post/\" rel=\"nofollow noreferrer\">https://blog.josemcastaneda.com/2014/03/18/get-image-count-in-wordpress-post/</a></p>\n\n<pre><code>// Get all the galleries in the current post\n $galleries = get_post_galleries( get_the_ID(), false );\n // Count all the galleries\n $total_gal = count( $galleries );\n /**\n * count all the images\n * @param array $array The array needed\n * @return int returns the number of images in the post\n */\n function _get_total_images( $array ){\n $key = 0;\n $src = 0;\n while ( $key &lt; count( $array ) ){\n $src += count( $array[$key]['src'] );\n $key++;\n }\n return intval( $src );\n }\n\n echo _get_total_images( $galleries );\n</code></pre>\n" }, { "answer_id": 246058, "author": "sMyles", "author_id": 51201, "author_profile": "https://wordpress.stackexchange.com/users/51201", "pm_score": 0, "selected": false, "text": "<p>To get all the image URLs from HTML content, or a PHP string/variable, and filter them by a specific extension, and only include remote domains, use this code:</p>\n\n<pre><code>$data = 'alsdj&lt;img src=\"http://localdomain.com/donotinclude.jpg\"&gt;fklasjdf&lt;img src=\"image.jpg\"&gt;asdfasdf&lt;img src=\"http://remotedomain.com/image.jpg\"&gt;asdfasdfsf&lt;img src=\"dont_include_me.png\"&gt;asdfasfasdf';\n$images = array();\n\n// Domains to not include images from (for instances where the full URL is specified to image)\n$localhosts = array( 'localdomain.com' );\n// Remove or add any extensions TO be included\n$allowed_extensions = array( 'jpg', 'jpeg' );\n\npreg_match_all('/(img|src)\\=(\\\"|\\')[^\\\"\\'\\&gt;]+/i', $data, $media);\nunset($data);\n$data=preg_replace('/(img|src)(\\\"|\\'|\\=\\\"|\\=\\')(.*)/i',\"$3\",$media[0]);\n\n\nforeach($data as $url)\n{\n $url_data = parse_url( $url );\n $info = pathinfo($url);\n\n // Goto next, we're only looking for remote hosts\n if( ! array_key_exists( 'host', $url_data ) ) continue;\n\n // Check if this is an extension we want to include\n if( array_key_exists( 'extension', $info ) &amp;&amp; in_array( $info['extension'], $allowed_extensions) ){\n\n // Verify this isn't one of our local hosts (where the full URL is specified)\n if( ! in_array( $url_data['host'], $localhosts ) ){\n array_push($images, $url);\n }\n\n }\n\n}\n\necho 'Total Images: ' . count( $images );\n// This is just linebreaks for display formatting\nprint \"\\n\\n\";\necho 'Image Data:';\nvar_dump( $images );\n</code></pre>\n\n<p>Example of code:\n<a href=\"https://glot.io/snippets/ekahzvu8sh\" rel=\"nofollow noreferrer\">https://glot.io/snippets/ekahzvu8sh</a></p>\n\n<p>Result output of code example above:</p>\n\n<pre><code>Total Images: 1\n\nImage Data:array(1) {\n [0]=&gt;\n string(27) \"http://remotedomain.com/image.jpg\"\n}\n</code></pre>\n\n<p>Make sure you set what your domain is in the <code>$localhosts</code> array, that way if for some reason the full URL is specified, it won't include that one.</p>\n\n<p>Using the example code from above, here's your updated function to use that code and return the number of images:</p>\n\n<pre><code>function post_photo_count_xpath( $post_id ) {\n\n $post = get_post( $post_id );\n if( ! $post ) return 0;\n\n $data = $post-&gt;post_content;\n $images = array();\n // Domains to not include images from (for instances where the full URL is specified to image)\n $localhosts = array( 'localdomain.com' );\n // Remove or add any extensions TO be included\n $allowed_extensions = array( 'jpg', 'jpeg' );\n\n preg_match_all('/(img|src)\\=(\\\"|\\')[^\\\"\\'\\&gt;]+/i', $data, $media);\n unset($data);\n $data=preg_replace('/(img|src)(\\\"|\\'|\\=\\\"|\\=\\')(.*)/i',\"$3\",$media[0]);\n\n if( empty( $data ) ) return 0;\n\n foreach( $data as $url ){\n $url_data = parse_url( $url );\n $info = pathinfo($url);\n\n // Goto next, we're only looking for remote hosts\n if( ! array_key_exists( 'host', $url_data ) ) continue;\n\n // Check if this is an extension we want to include\n if( array_key_exists( 'extension', $info ) &amp;&amp; in_array( $info['extension'], $allowed_extensions) ){\n\n // Verify this isn't one of our local hosts (where the full URL is specified)\n if( ! in_array( $url_data['host'], $localhosts ) ){\n array_push($images, $url);\n }\n\n }\n\n }\n\n return count( $images );\n}\n</code></pre>\n\n<p>Resource:\n<a href=\"https://davebrooks.wordpress.com/2009/04/22/php-preg_replace-some-useful-regular-expressions/\" rel=\"nofollow noreferrer\">https://davebrooks.wordpress.com/2009/04/22/php-preg_replace-some-useful-regular-expressions/</a></p>\n" }, { "answer_id": 246063, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 3, "selected": true, "text": "<p>Use regex to find all the urls and filter by type.</p>\n\n<pre><code>$post = get_post( 504 );\n$content = $post-&gt;post_content;\n\n// match all urls\npreg_match_all( '/(http:|https:)?\\/\\/([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&amp;:\\/~+#-]*[\\w@?^=%&amp;\\/~+#-])?/', $content, $matches );\n\n$count = 0;\nif ( ! empty( $matches ) &amp;&amp; ! empty( $matches[ 0 ] ) ) {\n foreach ( $matches[ 0 ] as $url ) {\n $split = explode( '#', $url );\n $split = explode( '?', $split[ 0 ] );\n $split = explode( '&amp;', $split[ 0 ] );\n $filename = basename( $split[ 0 ] );\n $file_type = wp_check_filetype( $filename, wp_get_mime_types() );\n if ( ! empty ( $file_type[ 'ext' ] ) ) {\n\n // (optional) limit inclusion based on file type\n if( ! in_array( $file_type[ 'ext' ], array('jpg', 'png')) ) continue;\n\n $files[ $url ] = $file_type;\n $urls[]=$url;\n $count ++;\n }\n }\n}\n\n// print out urls and total count\nprint_r( array ( \n 'total' =&gt; $count, \n 'unique' =&gt; array_keys( $files ),\n 'urls' =&gt; $urls \n) );\n</code></pre>\n\n<hr>\n\n<h2>OOP</h2>\n\n<p>If you want this as a reusable function...</p>\n\n<pre><code>function get_file_urls( $content = '', $file_types = array ( 'jpg', 'png' ) ) {\n\n // match all urls\n preg_match_all( '/(http:|https:)?\\/\\/([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&amp;:\\/~+#-]*[\\w@?^=%&amp;\\/~+#-])?/', $content, $matches );\n\n $urls = array ();\n $files = array ();\n\n if ( ! empty( $matches ) &amp;&amp; ! empty( $matches[ 0 ] ) ) {\n foreach ( $matches[ 0 ] as $url ) {\n $split = explode( '#', $url );\n $split = explode( '?', $split[ 0 ] );\n $split = explode( '&amp;', $split[ 0 ] );\n $filename = basename( $split[ 0 ] );\n $file_type = wp_check_filetype( $filename, wp_get_mime_types() );\n if ( ! empty ( $file_type[ 'ext' ] ) ) {\n\n // (optional) limit inclusion based on file type\n if ( ! in_array( $file_type[ 'ext' ], $file_types ) ) {\n continue;\n }\n\n $files[ $url ] = $file_type;\n $urls[] = $url;\n }\n }\n }\n\n // print out urls and total count\n return array (\n 'total' =&gt; count( $urls ),\n 'urls' =&gt; $urls,\n 'total_unique' =&gt; count( $files ),\n 'unique' =&gt; array_keys( $files ),\n );\n}\n\n$post = get_post( 504 );\n$content = $post-&gt;post_content;\n$file_urls = get_file_urls( $content, array ( 'jpg' ) );\n$count = $file_urls[ 'total' ];\n\necho \"&lt;div class='count'&gt;${count}&lt;/div&gt;\";\n</code></pre>\n" } ]
2016/11/14
[ "https://wordpress.stackexchange.com/questions/246067", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106904/" ]
I have a stuck that make me headache so much, as you see picture, this is my result when i add option to event. [![enter image description here](https://i.stack.imgur.com/aofam.png)](https://i.stack.imgur.com/aofam.png) I'm updated code in: `wp-content/theme/mytheme/lib/metabox/function.php` ``` $meta_boxes[] = array( 'id' => 'event_date_option', 'title' => __( 'Event options', 'mytheme' ), 'pages' => array( Custom_Posts_Type_Event::POST_TYPE ), // Post type 'context' => 'normal', 'priority' => 'high', 'show_names' => true, // Show field names on the left 'fields' => array( array( 'name' => __( 'Event type:', 'mytheme' ), 'desc' => __( 'Choose event type', 'mytheme' ), 'id' => SHORTNAME . Widget_Event::EVENT_INTERVAL_META_KEY, 'type' => 'select', 'options' => array( array( 'value'=>"n" , 'name' => __( 'Normal', 'mytheme' ) ), array( 'value'=>"c" , 'name' => __( 'Comunity', 'mytheme' ) ), ), ) ``` It's show in event post, but i don't know how to save when add new event OR when i'm update event post. Please help me, thank you! Ahh, i save it in database with new table like: ID\_POST, VALUE Thank you!
Use regex to find all the urls and filter by type. ``` $post = get_post( 504 ); $content = $post->post_content; // match all urls preg_match_all( '/(http:|https:)?\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/', $content, $matches ); $count = 0; if ( ! empty( $matches ) && ! empty( $matches[ 0 ] ) ) { foreach ( $matches[ 0 ] as $url ) { $split = explode( '#', $url ); $split = explode( '?', $split[ 0 ] ); $split = explode( '&', $split[ 0 ] ); $filename = basename( $split[ 0 ] ); $file_type = wp_check_filetype( $filename, wp_get_mime_types() ); if ( ! empty ( $file_type[ 'ext' ] ) ) { // (optional) limit inclusion based on file type if( ! in_array( $file_type[ 'ext' ], array('jpg', 'png')) ) continue; $files[ $url ] = $file_type; $urls[]=$url; $count ++; } } } // print out urls and total count print_r( array ( 'total' => $count, 'unique' => array_keys( $files ), 'urls' => $urls ) ); ``` --- OOP --- If you want this as a reusable function... ``` function get_file_urls( $content = '', $file_types = array ( 'jpg', 'png' ) ) { // match all urls preg_match_all( '/(http:|https:)?\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/', $content, $matches ); $urls = array (); $files = array (); if ( ! empty( $matches ) && ! empty( $matches[ 0 ] ) ) { foreach ( $matches[ 0 ] as $url ) { $split = explode( '#', $url ); $split = explode( '?', $split[ 0 ] ); $split = explode( '&', $split[ 0 ] ); $filename = basename( $split[ 0 ] ); $file_type = wp_check_filetype( $filename, wp_get_mime_types() ); if ( ! empty ( $file_type[ 'ext' ] ) ) { // (optional) limit inclusion based on file type if ( ! in_array( $file_type[ 'ext' ], $file_types ) ) { continue; } $files[ $url ] = $file_type; $urls[] = $url; } } } // print out urls and total count return array ( 'total' => count( $urls ), 'urls' => $urls, 'total_unique' => count( $files ), 'unique' => array_keys( $files ), ); } $post = get_post( 504 ); $content = $post->post_content; $file_urls = get_file_urls( $content, array ( 'jpg' ) ); $count = $file_urls[ 'total' ]; echo "<div class='count'>${count}</div>"; ```
246,090
<p>I have a "cmb2" custom field with <code>type-&gt;file</code>. and i use it to upload images.</p> <p><strong>If i use:</strong></p> <p><code>echo get_post_meta( $post-&gt;ID, '_pf_photo1', 'medium' );</code></p> <p>i get the url of the full image (not the medium one).</p> <p>How can i get the url of the 'medium' / 'thumbnail' and so on...</p>
[ { "answer_id": 246095, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 2, "selected": false, "text": "<p>You can get the <em>ID</em> of the file with <code>_pf_photo1_id</code>, then it's easy to get any size URL:</p>\n\n<pre><code>$file_id = get_post_meta( $post-&gt;ID, '_pf_photo1_id', true );\n\nif ( $file_id )\n echo wp_get_attachment_image_url( $file_id, 'medium' );\n</code></pre>\n" }, { "answer_id": 246096, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 3, "selected": true, "text": "<p>The <code>get_post_meta()</code> function can help to get the meta field but will not retrieve different size.</p>\n\n<p>Assuming <code>_pf_photo1</code> embed the attachment id, you can do something like that:</p>\n\n<pre><code>// Note the \"_id\" suffix\n$attachment_id = get_post_meta($post-&gt;ID, '_pf_photo1_id', true);\n</code></pre>\n\n<p>Last parameter for this function can not be 'medium', </p>\n\n<p>Now,you can use <code>$attachment_id</code> with different function depending on what you really want to get (url, img element...):</p>\n\n<pre><code>$attachment_element = wp_get_attachment_image( $attachment_id, 'medium' );\necho $attachment_element;\n</code></pre>\n\n<p>There is more ways to get details for attachment <code>wp_get_attachment_url()</code>, <code>wp_get_attachment_image_src</code> (that returns an array with url, width, height).</p>\n\n<p>You will find more details to discover these functions <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_url\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>Hope it helps !</p>\n" } ]
2016/11/14
[ "https://wordpress.stackexchange.com/questions/246090", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/43619/" ]
I have a "cmb2" custom field with `type->file`. and i use it to upload images. **If i use:** `echo get_post_meta( $post->ID, '_pf_photo1', 'medium' );` i get the url of the full image (not the medium one). How can i get the url of the 'medium' / 'thumbnail' and so on...
The `get_post_meta()` function can help to get the meta field but will not retrieve different size. Assuming `_pf_photo1` embed the attachment id, you can do something like that: ``` // Note the "_id" suffix $attachment_id = get_post_meta($post->ID, '_pf_photo1_id', true); ``` Last parameter for this function can not be 'medium', Now,you can use `$attachment_id` with different function depending on what you really want to get (url, img element...): ``` $attachment_element = wp_get_attachment_image( $attachment_id, 'medium' ); echo $attachment_element; ``` There is more ways to get details for attachment `wp_get_attachment_url()`, `wp_get_attachment_image_src` (that returns an array with url, width, height). You will find more details to discover these functions [here](https://codex.wordpress.org/Function_Reference/wp_get_attachment_url) Hope it helps !
246,124
<p>When I try to login via domain.com/wp-admin/ it will not allow me to do so. However, when I log in via domain.com/admin/ it will allow me to login with no problems.</p> <p>Does anyone have any ideas as to why this is? And possibly how to fix this?</p> <p>Thanks in advance.</p>
[ { "answer_id": 246127, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>It could be a plugin installed on the site for security purposes, to restrict bots from accessing to the wp-admin. </p>\n\n<p>Or it could be settings in your .htaccess file. You can reverse the changes either way. </p>\n" }, { "answer_id": 246132, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 3, "selected": true, "text": "<p>In general you can change where items link with <a href=\"https://codex.wordpress.org/Determining_Plugin_and_Content_Directories#Constants\" rel=\"nofollow noreferrer\">WP Constants</a>. But according to <a href=\"https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-includes/link-template.php#L3106\" rel=\"nofollow noreferrer\"><code>get_admin_url()</code></a> it's possible the URL was filtered with <code>admin_url</code> in which case you might be able to add a filter with a high priority and override what is being sent. The default is;</p>\n\n<pre><code>$url = get_site_url($blog_id, 'wp-admin/', $scheme);\n\nif ( $path &amp;&amp; is_string( $path ) )\n $url .= ltrim( $path, '/' );\n\nreturn apply_filters( 'admin_url', $url, $path, $blog_id );\n</code></pre>\n\n<p>As stated before, you should check your installed plugins (mainly security plugins) or <code>.htaccess</code> for wild redirects. Try disabling all plugins to narrow down that aspect pretty quick. Be sure to check the <code>/wp-content/mu-plugins/</code> folder for auto-loaded plugins.</p>\n\n<p>If you can, search your theme and plugins for any reference to <code>admin</code> as well as search your database for <code>admin</code> to see where it might be set.</p>\n" } ]
2016/11/14
[ "https://wordpress.stackexchange.com/questions/246124", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98494/" ]
When I try to login via domain.com/wp-admin/ it will not allow me to do so. However, when I log in via domain.com/admin/ it will allow me to login with no problems. Does anyone have any ideas as to why this is? And possibly how to fix this? Thanks in advance.
In general you can change where items link with [WP Constants](https://codex.wordpress.org/Determining_Plugin_and_Content_Directories#Constants). But according to [`get_admin_url()`](https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-includes/link-template.php#L3106) it's possible the URL was filtered with `admin_url` in which case you might be able to add a filter with a high priority and override what is being sent. The default is; ``` $url = get_site_url($blog_id, 'wp-admin/', $scheme); if ( $path && is_string( $path ) ) $url .= ltrim( $path, '/' ); return apply_filters( 'admin_url', $url, $path, $blog_id ); ``` As stated before, you should check your installed plugins (mainly security plugins) or `.htaccess` for wild redirects. Try disabling all plugins to narrow down that aspect pretty quick. Be sure to check the `/wp-content/mu-plugins/` folder for auto-loaded plugins. If you can, search your theme and plugins for any reference to `admin` as well as search your database for `admin` to see where it might be set.
246,137
<p>I have a wordpress installation at a location in the form: www.mydomain.com/mysite.</p> <p>I would like to redirect the DNS such that the address will (always!) appear as mysite.com.</p> <p>I own both domain names. How can I do the redirection without breaking everything?</p>
[ { "answer_id": 246194, "author": "user42826", "author_id": 42826, "author_profile": "https://wordpress.stackexchange.com/users/42826", "pm_score": 1, "selected": false, "text": "<p>1) You have to change all references of www.mydomain.com to mysite.com in WP. WP will only respond to the hostname/url that it was configured for. If you make a request with a different url, WP will respond with an error message. WP stores the url in two places wp-config.php and the database. In wp-config.php just do a manual search and replace. For the database one method to change site's url - export the database, do a search and replace, then import (be sure to keep a copy of the original export as backup). There are also plugin that will do the search and replace for you.</p>\n\n<p>2) DNS change. This depends on your DNS provider of www.mydomain.com. Some providers have the ability to add 301 redirects. See if your DNS provider has this capability. If not, you can add 301 redirects into your WP .htaccess near the top</p>\n\n<pre><code>RewriteEngine on\nRewriteCond %{HTTP_HOST} ^www.mydomain.com [NC]\nRewriteRule ^(.*)$ http://example.com/$1 [L,R=301,NC]\n</code></pre>\n" }, { "answer_id": 246198, "author": "Jarod Thornton", "author_id": 44017, "author_profile": "https://wordpress.stackexchange.com/users/44017", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>The easiest way to move a WordPress website from one domain to another is to create a mysql database dump and import this data into the new website.</p>\n</blockquote>\n\n<p>Backup your site files and database. Export the database, drop all the tables in said database, then use this tool to change the URL from old to new here - <a href=\"http://pixelentity.com/wordpress-search-replace-domain/\" rel=\"nofollow noreferrer\">http://pixelentity.com/wordpress-search-replace-domain/</a> </p>\n\n<blockquote>\n <p>this online tool to solve this problem by letting you replace an old domain or URL with a new one while fixing the serialized data at the same time.</p>\n</blockquote>\n\n<p>We serialize the data because there are character counts for everything and since www. or /site has more characters than the .com as we want it will cause problems. </p>\n\n<p>Once you have the fresh and clean database from that website, import it. </p>\n\n<p>Move all your files from the /mysite directory to the public root folder. </p>\n\n<p>Now put this in your .htaccess to redirect all www to non-www</p>\n\n<p><code>RewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]\nRewriteRule ^(.*)$ http://%1/$1 [R=301,L]</code></p>\n\n<p>DONE AND DONE :)</p>\n" } ]
2016/11/14
[ "https://wordpress.stackexchange.com/questions/246137", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78708/" ]
I have a wordpress installation at a location in the form: www.mydomain.com/mysite. I would like to redirect the DNS such that the address will (always!) appear as mysite.com. I own both domain names. How can I do the redirection without breaking everything?
1) You have to change all references of www.mydomain.com to mysite.com in WP. WP will only respond to the hostname/url that it was configured for. If you make a request with a different url, WP will respond with an error message. WP stores the url in two places wp-config.php and the database. In wp-config.php just do a manual search and replace. For the database one method to change site's url - export the database, do a search and replace, then import (be sure to keep a copy of the original export as backup). There are also plugin that will do the search and replace for you. 2) DNS change. This depends on your DNS provider of www.mydomain.com. Some providers have the ability to add 301 redirects. See if your DNS provider has this capability. If not, you can add 301 redirects into your WP .htaccess near the top ``` RewriteEngine on RewriteCond %{HTTP_HOST} ^www.mydomain.com [NC] RewriteRule ^(.*)$ http://example.com/$1 [L,R=301,NC] ```
246,140
<p>I recently took over web admin for a nonprofit organization and one of the things they would like changed with their site is to have multiple forms such as contact, volunteer, donations, more info, etc. They would like this data sent in an email so that it can be sent to focus group members but need it sent in a daily/ weekly email rather than an email for each individual submission. I think that an excel file is the best way to accomplish what they want and I have looked at several form plugins but they only support manual export of excel files. Is there either a plugin that supports emailing excel files or is there another way I can automate an export and email that export? Thanks in advance!</p>
[ { "answer_id": 246194, "author": "user42826", "author_id": 42826, "author_profile": "https://wordpress.stackexchange.com/users/42826", "pm_score": 1, "selected": false, "text": "<p>1) You have to change all references of www.mydomain.com to mysite.com in WP. WP will only respond to the hostname/url that it was configured for. If you make a request with a different url, WP will respond with an error message. WP stores the url in two places wp-config.php and the database. In wp-config.php just do a manual search and replace. For the database one method to change site's url - export the database, do a search and replace, then import (be sure to keep a copy of the original export as backup). There are also plugin that will do the search and replace for you.</p>\n\n<p>2) DNS change. This depends on your DNS provider of www.mydomain.com. Some providers have the ability to add 301 redirects. See if your DNS provider has this capability. If not, you can add 301 redirects into your WP .htaccess near the top</p>\n\n<pre><code>RewriteEngine on\nRewriteCond %{HTTP_HOST} ^www.mydomain.com [NC]\nRewriteRule ^(.*)$ http://example.com/$1 [L,R=301,NC]\n</code></pre>\n" }, { "answer_id": 246198, "author": "Jarod Thornton", "author_id": 44017, "author_profile": "https://wordpress.stackexchange.com/users/44017", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>The easiest way to move a WordPress website from one domain to another is to create a mysql database dump and import this data into the new website.</p>\n</blockquote>\n\n<p>Backup your site files and database. Export the database, drop all the tables in said database, then use this tool to change the URL from old to new here - <a href=\"http://pixelentity.com/wordpress-search-replace-domain/\" rel=\"nofollow noreferrer\">http://pixelentity.com/wordpress-search-replace-domain/</a> </p>\n\n<blockquote>\n <p>this online tool to solve this problem by letting you replace an old domain or URL with a new one while fixing the serialized data at the same time.</p>\n</blockquote>\n\n<p>We serialize the data because there are character counts for everything and since www. or /site has more characters than the .com as we want it will cause problems. </p>\n\n<p>Once you have the fresh and clean database from that website, import it. </p>\n\n<p>Move all your files from the /mysite directory to the public root folder. </p>\n\n<p>Now put this in your .htaccess to redirect all www to non-www</p>\n\n<p><code>RewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]\nRewriteRule ^(.*)$ http://%1/$1 [R=301,L]</code></p>\n\n<p>DONE AND DONE :)</p>\n" } ]
2016/11/14
[ "https://wordpress.stackexchange.com/questions/246140", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106947/" ]
I recently took over web admin for a nonprofit organization and one of the things they would like changed with their site is to have multiple forms such as contact, volunteer, donations, more info, etc. They would like this data sent in an email so that it can be sent to focus group members but need it sent in a daily/ weekly email rather than an email for each individual submission. I think that an excel file is the best way to accomplish what they want and I have looked at several form plugins but they only support manual export of excel files. Is there either a plugin that supports emailing excel files or is there another way I can automate an export and email that export? Thanks in advance!
1) You have to change all references of www.mydomain.com to mysite.com in WP. WP will only respond to the hostname/url that it was configured for. If you make a request with a different url, WP will respond with an error message. WP stores the url in two places wp-config.php and the database. In wp-config.php just do a manual search and replace. For the database one method to change site's url - export the database, do a search and replace, then import (be sure to keep a copy of the original export as backup). There are also plugin that will do the search and replace for you. 2) DNS change. This depends on your DNS provider of www.mydomain.com. Some providers have the ability to add 301 redirects. See if your DNS provider has this capability. If not, you can add 301 redirects into your WP .htaccess near the top ``` RewriteEngine on RewriteCond %{HTTP_HOST} ^www.mydomain.com [NC] RewriteRule ^(.*)$ http://example.com/$1 [L,R=301,NC] ```
246,146
<p>I wonder how can I trigger filter hook only when post is saved with new revision directly after user clicked save button or publish new post.</p> <p>My idea is to replace specific parts of the post, but I don't need to trigger my filter each time ajax request for autosaving is sent or new post draft is created. </p> <p>I am using this filter right now (don't pay attention to var_dump)</p> <pre><code> add_filter('wp_insert_post_data', array(&amp;$this, 'filter_post_data'), '99', 2); function filter_post_data($data, $postarr) { var_dump($data); var_dump($postarr); exit; // Change post title return $data; } </code></pre> <p>And this filter is triggered each time post data is going to be saved into database. But I need to trigger this filter only when user clicks save button.</p> <p>How can I achieve this ? Should I just check post type, status ... in <code>postarr</code> to determine if this post is going to be saved. How can I be sure that the post is save on user click ? (what argument can tell me this)</p> <p>Thanks.</p>
[ { "answer_id": 246149, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 1, "selected": false, "text": "<p>you can use different statement in your function to determine this:</p>\n\n<pre><code> function filter_post_data($data, $postarr){\n if ( is_admin() &amp;&amp; defined( 'DOING_AJAX' ) &amp;&amp; DOING_AJAX ){\n exit;\n }\n // Change post title\n return $data;\n }\n</code></pre>\n\n<p>Post transitions actions are maybe better in your case, for example:</p>\n\n<pre><code> add_action( 'pending_to_publish', 'filter_post_data', 10, 1 );\n</code></pre>\n\n<p>You can discover all of them <a href=\"https://codex.wordpress.org/Post_Status_Transitions\" rel=\"nofollow noreferrer\">Post status transitions</a></p>\n" }, { "answer_id": 246263, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 3, "selected": true, "text": "<p>Look at <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\"><code>'save_post'</code></a> and \n<a href=\"https://codex.wordpress.org/Post_Status_Transitions\" rel=\"nofollow noreferrer\">Post Status Transitions</a>.</p>\n\n<blockquote>\n <p><code>save_post</code> is an action triggered whenever a post or page is created or updated, which could be from an import, post/page edit form, xmlrpc, or post by email. The data for the post is stored in $_POST, $_GET or the global $post_data, depending on how the post was edited. For example, quick edits use $_POST. Since this action is triggered right after the post has been saved, you can easily access this post object by using get_post($post_id)</p>\n</blockquote>\n\n<p>The revision functions can tell you whether this is an autosave:\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_is_post_revision\" rel=\"nofollow noreferrer\"><code>wp_is_post_revision()</code></a> / <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_post_revisions\" rel=\"nofollow noreferrer\"><code>wp_get_post_revisions()</code></a>. </p>\n\n<pre><code>function wpse_save_post( $post_id ) {\n\n // If this is just a revision, so we can ignore it.\n if ( wp_is_post_revision( $post_id ) )\n return;\n\n $post_title = get_the_title( $post_id );\n $post_url = get_permalink( $post_id );\n $subject = 'A post has been updated';\n\n $message = \"A post has been updated on your website:\\n\\n\";\n $message .= $post_title . \": \" . $post_url;\n}\n\nadd_action( 'save_post', 'wpse_save_post' );\n</code></pre>\n\n<p>Here you can update the post content after it was saved using <a href=\"https://codex.wordpress.org/Function_Reference/wp_update_post\" rel=\"nofollow noreferrer\"><code>wp_update_post()</code></a>. But be sure to avoid the infinite loop.</p>\n\n<pre><code>function my_function( $post_id ){\n if ( ! wp_is_post_revision( $post_id ) ){\n\n // unhook this function so it doesn't loop infinitely\n remove_action('save_post', 'my_function');\n\n // update the post, which calls save_post again\n wp_update_post( $my_args );\n\n // re-hook this function\n add_action('save_post', 'my_function');\n }\n}\nadd_action('save_post', 'my_function');\n</code></pre>\n" } ]
2016/11/14
[ "https://wordpress.stackexchange.com/questions/246146", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106950/" ]
I wonder how can I trigger filter hook only when post is saved with new revision directly after user clicked save button or publish new post. My idea is to replace specific parts of the post, but I don't need to trigger my filter each time ajax request for autosaving is sent or new post draft is created. I am using this filter right now (don't pay attention to var\_dump) ``` add_filter('wp_insert_post_data', array(&$this, 'filter_post_data'), '99', 2); function filter_post_data($data, $postarr) { var_dump($data); var_dump($postarr); exit; // Change post title return $data; } ``` And this filter is triggered each time post data is going to be saved into database. But I need to trigger this filter only when user clicks save button. How can I achieve this ? Should I just check post type, status ... in `postarr` to determine if this post is going to be saved. How can I be sure that the post is save on user click ? (what argument can tell me this) Thanks.
Look at [`'save_post'`](https://codex.wordpress.org/Plugin_API/Action_Reference/save_post) and [Post Status Transitions](https://codex.wordpress.org/Post_Status_Transitions). > > `save_post` is an action triggered whenever a post or page is created or updated, which could be from an import, post/page edit form, xmlrpc, or post by email. The data for the post is stored in $\_POST, $\_GET or the global $post\_data, depending on how the post was edited. For example, quick edits use $\_POST. Since this action is triggered right after the post has been saved, you can easily access this post object by using get\_post($post\_id) > > > The revision functions can tell you whether this is an autosave: [`wp_is_post_revision()`](https://codex.wordpress.org/Function_Reference/wp_is_post_revision) / [`wp_get_post_revisions()`](https://codex.wordpress.org/Function_Reference/wp_get_post_revisions). ``` function wpse_save_post( $post_id ) { // If this is just a revision, so we can ignore it. if ( wp_is_post_revision( $post_id ) ) return; $post_title = get_the_title( $post_id ); $post_url = get_permalink( $post_id ); $subject = 'A post has been updated'; $message = "A post has been updated on your website:\n\n"; $message .= $post_title . ": " . $post_url; } add_action( 'save_post', 'wpse_save_post' ); ``` Here you can update the post content after it was saved using [`wp_update_post()`](https://codex.wordpress.org/Function_Reference/wp_update_post). But be sure to avoid the infinite loop. ``` function my_function( $post_id ){ if ( ! wp_is_post_revision( $post_id ) ){ // unhook this function so it doesn't loop infinitely remove_action('save_post', 'my_function'); // update the post, which calls save_post again wp_update_post( $my_args ); // re-hook this function add_action('save_post', 'my_function'); } } add_action('save_post', 'my_function'); ```
246,154
<p>I am creating this role 'grocery' for a client but it basically only needs to be able to edit pages and upload media. For some reason the code I have is still allowing the 'grocery' role to delete posts and create pages and do a bunch of things I DO NOT want this role to be able to do. This is my code, cant't figure out why it is not working. It is adding the role and letting me create users under this role, but again it is allowing the wrong things.</p> <pre><code>// Give capabilities $capabilities_grocery = array( 'activate_plugins' =&gt; false, 'delete_others_pages' =&gt; false, 'delete_others_posts' =&gt; false, 'delete_pages' =&gt; false, 'delete_posts' =&gt; false, 'delete_private_pages' =&gt; false, 'delete_private_posts' =&gt; false, 'delete_published_pages' =&gt; false, 'delete_published_posts' =&gt; false, 'edit_dashboard' =&gt; false, 'edit_others_pages' =&gt; true, 'edit_others_posts' =&gt; true, 'edit_pages' =&gt; true, 'edit_posts' =&gt; true, 'edit_private_pages' =&gt; true, 'edit_private_posts' =&gt; true, 'edit_published_pages' =&gt; true, 'edit_published_posts' =&gt; true, 'edit_theme_options' =&gt; false, 'export' =&gt; true, 'import' =&gt; true, 'list_users' =&gt; false, 'manage_categories' =&gt; false, 'manage_links' =&gt; false, 'manage_options' =&gt; false, 'moderate_comments' =&gt; false, 'promote_users' =&gt; false, 'publish_pages' =&gt; false, 'publish_posts' =&gt; false, 'read_private_pages' =&gt; false, 'read_private_posts' =&gt; false, 'read' =&gt; true, 'remove_users' =&gt; false, 'switch_themes' =&gt; false, 'upload_files' =&gt; true, 'customize' =&gt; false, 'delete_site' =&gt; false, ); // Add The Role add_role('grocery', 'Grocery', $capabilities_grocery); </code></pre>
[ { "answer_id": 246149, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 1, "selected": false, "text": "<p>you can use different statement in your function to determine this:</p>\n\n<pre><code> function filter_post_data($data, $postarr){\n if ( is_admin() &amp;&amp; defined( 'DOING_AJAX' ) &amp;&amp; DOING_AJAX ){\n exit;\n }\n // Change post title\n return $data;\n }\n</code></pre>\n\n<p>Post transitions actions are maybe better in your case, for example:</p>\n\n<pre><code> add_action( 'pending_to_publish', 'filter_post_data', 10, 1 );\n</code></pre>\n\n<p>You can discover all of them <a href=\"https://codex.wordpress.org/Post_Status_Transitions\" rel=\"nofollow noreferrer\">Post status transitions</a></p>\n" }, { "answer_id": 246263, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 3, "selected": true, "text": "<p>Look at <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\"><code>'save_post'</code></a> and \n<a href=\"https://codex.wordpress.org/Post_Status_Transitions\" rel=\"nofollow noreferrer\">Post Status Transitions</a>.</p>\n\n<blockquote>\n <p><code>save_post</code> is an action triggered whenever a post or page is created or updated, which could be from an import, post/page edit form, xmlrpc, or post by email. The data for the post is stored in $_POST, $_GET or the global $post_data, depending on how the post was edited. For example, quick edits use $_POST. Since this action is triggered right after the post has been saved, you can easily access this post object by using get_post($post_id)</p>\n</blockquote>\n\n<p>The revision functions can tell you whether this is an autosave:\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_is_post_revision\" rel=\"nofollow noreferrer\"><code>wp_is_post_revision()</code></a> / <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_post_revisions\" rel=\"nofollow noreferrer\"><code>wp_get_post_revisions()</code></a>. </p>\n\n<pre><code>function wpse_save_post( $post_id ) {\n\n // If this is just a revision, so we can ignore it.\n if ( wp_is_post_revision( $post_id ) )\n return;\n\n $post_title = get_the_title( $post_id );\n $post_url = get_permalink( $post_id );\n $subject = 'A post has been updated';\n\n $message = \"A post has been updated on your website:\\n\\n\";\n $message .= $post_title . \": \" . $post_url;\n}\n\nadd_action( 'save_post', 'wpse_save_post' );\n</code></pre>\n\n<p>Here you can update the post content after it was saved using <a href=\"https://codex.wordpress.org/Function_Reference/wp_update_post\" rel=\"nofollow noreferrer\"><code>wp_update_post()</code></a>. But be sure to avoid the infinite loop.</p>\n\n<pre><code>function my_function( $post_id ){\n if ( ! wp_is_post_revision( $post_id ) ){\n\n // unhook this function so it doesn't loop infinitely\n remove_action('save_post', 'my_function');\n\n // update the post, which calls save_post again\n wp_update_post( $my_args );\n\n // re-hook this function\n add_action('save_post', 'my_function');\n }\n}\nadd_action('save_post', 'my_function');\n</code></pre>\n" } ]
2016/11/14
[ "https://wordpress.stackexchange.com/questions/246154", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93770/" ]
I am creating this role 'grocery' for a client but it basically only needs to be able to edit pages and upload media. For some reason the code I have is still allowing the 'grocery' role to delete posts and create pages and do a bunch of things I DO NOT want this role to be able to do. This is my code, cant't figure out why it is not working. It is adding the role and letting me create users under this role, but again it is allowing the wrong things. ``` // Give capabilities $capabilities_grocery = array( 'activate_plugins' => false, 'delete_others_pages' => false, 'delete_others_posts' => false, 'delete_pages' => false, 'delete_posts' => false, 'delete_private_pages' => false, 'delete_private_posts' => false, 'delete_published_pages' => false, 'delete_published_posts' => false, 'edit_dashboard' => false, 'edit_others_pages' => true, 'edit_others_posts' => true, 'edit_pages' => true, 'edit_posts' => true, 'edit_private_pages' => true, 'edit_private_posts' => true, 'edit_published_pages' => true, 'edit_published_posts' => true, 'edit_theme_options' => false, 'export' => true, 'import' => true, 'list_users' => false, 'manage_categories' => false, 'manage_links' => false, 'manage_options' => false, 'moderate_comments' => false, 'promote_users' => false, 'publish_pages' => false, 'publish_posts' => false, 'read_private_pages' => false, 'read_private_posts' => false, 'read' => true, 'remove_users' => false, 'switch_themes' => false, 'upload_files' => true, 'customize' => false, 'delete_site' => false, ); // Add The Role add_role('grocery', 'Grocery', $capabilities_grocery); ```
Look at [`'save_post'`](https://codex.wordpress.org/Plugin_API/Action_Reference/save_post) and [Post Status Transitions](https://codex.wordpress.org/Post_Status_Transitions). > > `save_post` is an action triggered whenever a post or page is created or updated, which could be from an import, post/page edit form, xmlrpc, or post by email. The data for the post is stored in $\_POST, $\_GET or the global $post\_data, depending on how the post was edited. For example, quick edits use $\_POST. Since this action is triggered right after the post has been saved, you can easily access this post object by using get\_post($post\_id) > > > The revision functions can tell you whether this is an autosave: [`wp_is_post_revision()`](https://codex.wordpress.org/Function_Reference/wp_is_post_revision) / [`wp_get_post_revisions()`](https://codex.wordpress.org/Function_Reference/wp_get_post_revisions). ``` function wpse_save_post( $post_id ) { // If this is just a revision, so we can ignore it. if ( wp_is_post_revision( $post_id ) ) return; $post_title = get_the_title( $post_id ); $post_url = get_permalink( $post_id ); $subject = 'A post has been updated'; $message = "A post has been updated on your website:\n\n"; $message .= $post_title . ": " . $post_url; } add_action( 'save_post', 'wpse_save_post' ); ``` Here you can update the post content after it was saved using [`wp_update_post()`](https://codex.wordpress.org/Function_Reference/wp_update_post). But be sure to avoid the infinite loop. ``` function my_function( $post_id ){ if ( ! wp_is_post_revision( $post_id ) ){ // unhook this function so it doesn't loop infinitely remove_action('save_post', 'my_function'); // update the post, which calls save_post again wp_update_post( $my_args ); // re-hook this function add_action('save_post', 'my_function'); } } add_action('save_post', 'my_function'); ```
246,157
<p>I have a short code in wordpress, below is a part of the shortcode →</p> <p>[tm_single_image animation="fadeInLeft" classname="sub-banner1" image="http://trafficspinners.com/wp-content/uploads/2016/11/wedding-seating-chart-downloadable2.jpg"]</p> <p>I want to put a clickable anchor text in this image, Please guide me.</p> <p>Widget Definition →</p> <pre><code>/*=============Sub Banner ============ */ function shortcode_subbanner($atts, $content = null) { extract(shortcode_atts(array( 'image' =&gt; '', 'padding' =&gt; '', 'margin' =&gt; '', 'height' =&gt; '', 'width' =&gt; '', 'class' =&gt; '', 'link_url' =&gt; '' ), $atts)); $variables = ''; $output = ''; if(!empty($image)) : $variables .= 'padding:'.$padding.';'; $variables .= 'margin:'.$margin.';'; endif; $output .= '&lt;div class="sub-container '.$class.'" style="'.$variables.'"&gt;'; $output .= '&lt;div class="inner-image"&gt;&lt;a href="'.$link_url.'" target="_Blank"&gt;&lt;img src='.$image.' height="'.$height.'" width="'.$width.'"&gt;&lt;/a&gt;&lt;/div&gt;'; $output .= '&lt;/div&gt;'; return $output; } add_shortcode('subbanner', 'shortcode_subbanner'); </code></pre>
[ { "answer_id": 246165, "author": "Michelle", "author_id": 16, "author_profile": "https://wordpress.stackexchange.com/users/16", "pm_score": 2, "selected": true, "text": "<p>I think you just need to add link_url to the shortcode, like so?</p>\n\n<p>[tm_single_image animation=\"fadeInLeft\" classname=\"sub-banner1\" image=\"http://trafficspinners.com/wp-content/uploads/2016/11/wedding-seating-chart-downloadable2.jpg\" link_url=\"YOUR-LINK-HERE\"]</p>\n\n<p>Unless I am not understanding what you mean by 'clickable anchor text'. </p>\n" }, { "answer_id": 246166, "author": "Viktor H. Morales", "author_id": 104535, "author_profile": "https://wordpress.stackexchange.com/users/104535", "pm_score": 0, "selected": false, "text": "<p>Agree with Michelle. In the code you can see the options available in the widget:</p>\n\n<pre><code>'image' =&gt; '',\n'padding' =&gt; '',\n'margin' =&gt; '',\n'height' =&gt; '',\n'width' =&gt; '',\n'class' =&gt; '',\n'link_url' =&gt; '\n</code></pre>\n\n<p>Adding \"link_url\" to your widget will add an anchor to the image.</p>\n" } ]
2016/11/14
[ "https://wordpress.stackexchange.com/questions/246157", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
I have a short code in wordpress, below is a part of the shortcode → [tm\_single\_image animation="fadeInLeft" classname="sub-banner1" image="http://trafficspinners.com/wp-content/uploads/2016/11/wedding-seating-chart-downloadable2.jpg"] I want to put a clickable anchor text in this image, Please guide me. Widget Definition → ``` /*=============Sub Banner ============ */ function shortcode_subbanner($atts, $content = null) { extract(shortcode_atts(array( 'image' => '', 'padding' => '', 'margin' => '', 'height' => '', 'width' => '', 'class' => '', 'link_url' => '' ), $atts)); $variables = ''; $output = ''; if(!empty($image)) : $variables .= 'padding:'.$padding.';'; $variables .= 'margin:'.$margin.';'; endif; $output .= '<div class="sub-container '.$class.'" style="'.$variables.'">'; $output .= '<div class="inner-image"><a href="'.$link_url.'" target="_Blank"><img src='.$image.' height="'.$height.'" width="'.$width.'"></a></div>'; $output .= '</div>'; return $output; } add_shortcode('subbanner', 'shortcode_subbanner'); ```
I think you just need to add link\_url to the shortcode, like so? [tm\_single\_image animation="fadeInLeft" classname="sub-banner1" image="http://trafficspinners.com/wp-content/uploads/2016/11/wedding-seating-chart-downloadable2.jpg" link\_url="YOUR-LINK-HERE"] Unless I am not understanding what you mean by 'clickable anchor text'.
246,218
<p>I want to have different 404 template for each custom post type.</p> <p>eg. I have post type name <strong>event</strong> and the link will be<br> <em>domain.com/event/my-event-name</em></p> <p>but if it link to page that not have post<br> <em>domain.com/event/xxxxxxx</em> <br></p> <p>then it will show 404 page, but I want it different from <code>404.php</code> template, I try get post type in <code>404.php</code> but it can't because it not have a post to get from.</p>
[ { "answer_id": 246222, "author": "elicohenator", "author_id": 98507, "author_profile": "https://wordpress.stackexchange.com/users/98507", "pm_score": 1, "selected": false, "text": "<p>According to WP's template hierarchy , you cannot use different template to a 404 page. as @Ranuka suggested, you can customize your 404 to display custom content by editing the template file or inserting your own messages.</p>\n\n<p>Read this first: <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/basics/template-hierarchy/</a> and then decide (and share please) what's your desired solution?</p>\n" }, { "answer_id": 246236, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>A query returns a 404 when there are no results. So, the problem on your <code>404.php</code> page is that you have no query knowledge about what caused it. Hence, you can't test for a post type.</p>\n\n<p>What you do have, however, is the url that caused the 404. Depending on how you set your permalinks this may contain information about the post type. In the example you give there is <code>/event/</code> as a <a href=\"http://php.net/manual/en/function.strpos.php\" rel=\"nofollow noreferrer\">string you could test for</a> in your template. Like this:</p>\n\n<pre><code>$url = $_SERVER['REQUEST_URI']; // this will return: /event/my-wrong-event-name or so\nif (false === strpos ($url, '/event/')) // important note: use ===, not ==\n ... normal 404 message\nelse\n ... event 404 message;\n</code></pre>\n" }, { "answer_id": 246272, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>WordPress 4.7 introduces a new filter that allows us to easily modify the <em>template hierarchy</em>:</p>\n\n<pre><code>/**\n * Filters the list of template filenames that are searched for when retrieving \n * a template to use.\n *\n * The last element in the array should always be the fallback \n * template for this query type.\n *\n * Possible values for `$type` include: 'index', '404', 'archive', 'author', 'category', \n * 'tag', 'taxonomy', 'date', 'embed', home', 'frontpage', 'page', 'paged', 'search', \n * 'single', 'singular', and 'attachment'.\n *\n * @since 4.7.0\n *\n * @param array $templates A list of template candidates, in descending order of priority.\n */\n$templates = apply_filters( \"{$type}_template_hierarchy\", $templates );\n</code></pre>\n\n<p>For the 404 type, we could check the current path, as suggested by @cjbj. </p>\n\n<p>Here's an example where we modify the 404 template hierarchy by supporting the <code>404-event.php</code> template, if the current path matches the <code>^/event/</code> regex pattern (<em>PHP 5.4+</em>):</p>\n\n<pre><code>add_filter( '404_template_hierarchy', function( $templates ) \n{ \n // Check if current path matches ^/event/ \n if( ! preg_match( '#^/event/#', add_query_arg( [] ) ) )\n return $templates;\n\n // Make sure we have an array \n if( ! is_array( $templates ) )\n return $templates;\n\n // Add our custom 404 template to the top of the 404 template queue\n array_unshift( $templates, '404-event.php' );\n\n return $templates;\n} );\n</code></pre>\n\n<p>If our custom <code>404-event.php</code> doesn't exists, then <code>404.php</code> is the fallback.</p>\n\n<p>We might also just adjust the <code>404.php</code> template file to our needs, as suggested by @EliCohen</p>\n\n<p>We could also use the old <code>404_template</code> filter (since WordPress 1.5), that's fired after the <code>locate_template()</code> is called. </p>\n\n<p>Here's an example (<em>PHP 5.4+</em>):</p>\n\n<pre><code>add_filter( '404_template', function( $template ) \n{\n // Check if current path matches ^/event/ \n if( ! preg_match( '#^/event/#', add_query_arg( [] ) ) )\n return $template;\n\n // Try to locate our custom 404-event.php template \n $new_404_template = locate_template( [ '404-event.php'] );\n\n // Override if it was found \n if( $new_404_template )\n $template = $new_404_template;\n\n return $template;\n} );\n</code></pre>\n\n<p>Hope you can test it further and adjust to your needs!</p>\n" } ]
2016/11/15
[ "https://wordpress.stackexchange.com/questions/246218", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/12397/" ]
I want to have different 404 template for each custom post type. eg. I have post type name **event** and the link will be *domain.com/event/my-event-name* but if it link to page that not have post *domain.com/event/xxxxxxx* then it will show 404 page, but I want it different from `404.php` template, I try get post type in `404.php` but it can't because it not have a post to get from.
WordPress 4.7 introduces a new filter that allows us to easily modify the *template hierarchy*: ``` /** * Filters the list of template filenames that are searched for when retrieving * a template to use. * * The last element in the array should always be the fallback * template for this query type. * * Possible values for `$type` include: 'index', '404', 'archive', 'author', 'category', * 'tag', 'taxonomy', 'date', 'embed', home', 'frontpage', 'page', 'paged', 'search', * 'single', 'singular', and 'attachment'. * * @since 4.7.0 * * @param array $templates A list of template candidates, in descending order of priority. */ $templates = apply_filters( "{$type}_template_hierarchy", $templates ); ``` For the 404 type, we could check the current path, as suggested by @cjbj. Here's an example where we modify the 404 template hierarchy by supporting the `404-event.php` template, if the current path matches the `^/event/` regex pattern (*PHP 5.4+*): ``` add_filter( '404_template_hierarchy', function( $templates ) { // Check if current path matches ^/event/ if( ! preg_match( '#^/event/#', add_query_arg( [] ) ) ) return $templates; // Make sure we have an array if( ! is_array( $templates ) ) return $templates; // Add our custom 404 template to the top of the 404 template queue array_unshift( $templates, '404-event.php' ); return $templates; } ); ``` If our custom `404-event.php` doesn't exists, then `404.php` is the fallback. We might also just adjust the `404.php` template file to our needs, as suggested by @EliCohen We could also use the old `404_template` filter (since WordPress 1.5), that's fired after the `locate_template()` is called. Here's an example (*PHP 5.4+*): ``` add_filter( '404_template', function( $template ) { // Check if current path matches ^/event/ if( ! preg_match( '#^/event/#', add_query_arg( [] ) ) ) return $template; // Try to locate our custom 404-event.php template $new_404_template = locate_template( [ '404-event.php'] ); // Override if it was found if( $new_404_template ) $template = $new_404_template; return $template; } ); ``` Hope you can test it further and adjust to your needs!
246,225
<p>I have to get all the terms from four taxonomies:</p> <ul> <li>vehicle_safely_features</li> <li>vehicle_exterior_features</li> <li>vehicle_interior_features</li> <li>vehicle_extras</li> </ul> <p>I tried this:</p> <pre><code>$terms = get_terms( array( 'taxonomy' =&gt; 'vehicle_safely_features', 'vehicle_exterior_features', 'vehicle_interior_features', 'vehicle_extras' ) ); </code></pre> <p>But, it only gets terms of <code>vehicle_safely_features</code> and not all of the taxonomies. </p>
[ { "answer_id": 246226, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 4, "selected": true, "text": "<p>If you want to retrieve multiple taxonomies you need to put the four taxonomies in an array, you are doing this, but you have put <code>taxonomy=&gt;</code> in the array.</p>\n\n<pre><code>$terms = get_terms(\n 'taxonomy' =&gt; array(\n 'vehicle_safely_features',\n 'vehicle_exterior_features',\n 'vehicle_interior_features',\n 'vehicle_extras')\n);\n</code></pre>\n\n<p>Hope it helps</p>\n" }, { "answer_id": 268807, "author": "Roshan Deshapriya", "author_id": 97402, "author_profile": "https://wordpress.stackexchange.com/users/97402", "pm_score": 2, "selected": false, "text": "<p>Incase someone get an error due to the <code>=&gt;</code> use below</p>\n\n<pre><code>$termsArray = get_the_terms(\n $post-&gt;ID,\n array(\n 'tax1',\n 'tax2',\n 'tax3'\n )\n)\n</code></pre>\n" } ]
2016/11/15
[ "https://wordpress.stackexchange.com/questions/246225", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104741/" ]
I have to get all the terms from four taxonomies: * vehicle\_safely\_features * vehicle\_exterior\_features * vehicle\_interior\_features * vehicle\_extras I tried this: ``` $terms = get_terms( array( 'taxonomy' => 'vehicle_safely_features', 'vehicle_exterior_features', 'vehicle_interior_features', 'vehicle_extras' ) ); ``` But, it only gets terms of `vehicle_safely_features` and not all of the taxonomies.
If you want to retrieve multiple taxonomies you need to put the four taxonomies in an array, you are doing this, but you have put `taxonomy=>` in the array. ``` $terms = get_terms( 'taxonomy' => array( 'vehicle_safely_features', 'vehicle_exterior_features', 'vehicle_interior_features', 'vehicle_extras') ); ``` Hope it helps
246,228
<p>I am using WP-PageNavi plugin, which I incorporated into my custom tpl page. There is woocommerce shortcode which holds all the products that I want to display, but I only ever see the same ones and only one page results. I do not see what am I doing wrong. The code is:</p> <pre><code> &lt;?php /* Template Name: shine*/ ?&gt; &lt;?php get_header(); ?&gt; &lt;div class="wrapper clearfix"&gt; &lt;?php $args = array( 'post_type' =&gt; 'page', 'orderby' =&gt; 'title', 'order' =&gt; 'ASC', 'posts_per_page' =&gt; 5, 'paged' =&gt; get_query_var('paged'), ); ?&gt; &lt;?php query_posts($args); ?&gt; &lt;?php if ( have_posts() ) : ?&gt; &lt;?php while ( have_posts() ) : the_post(); ?&gt; &lt;?php endwhile; ?&gt; &lt;?php endif; ?&gt; &lt;h2&gt;SHINE kolekcija&lt;/h2&gt; &lt;?php echo do_shortcode( '[product_attribute attribute="kolekcije" filter="shine"]' ); ?&gt; &lt;div class="naviButs"&gt; &lt;?php wp_pagenavi(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php get_footer(); ?&gt; </code></pre>
[ { "answer_id": 246230, "author": "Rishabh", "author_id": 81621, "author_profile": "https://wordpress.stackexchange.com/users/81621", "pm_score": 1, "selected": false, "text": "<p>In case of <code>wp_query</code>, you can't use shortcode this way</p>\n\n<pre><code>&lt;?php wp_pagenavi(); ?&gt;\n</code></pre>\n\n<p>You need to use variable (in which you are storing wp_query) in array inside shortcode. Use shortcode like this instead. Replace above shortcode with below one.</p>\n\n<pre><code>&lt;?php wp_pagenavi( array( 'query' =&gt; $query_slider ) ); ?&gt;\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>This is a way in which I am using <code>wp_query</code> to show products list without shortcode that you used to display products.</p>\n\n<pre><code>&lt;?php\n/*\nTemplate Name: shine\n*/\nget_header(); ?&gt;\n&lt;?php \n$paged = get_query_var('paged') ? get_query_var('paged') : 1;\n$args = array('post_type' =&gt; 'product',\n'orderby' =&gt; 'title',\n'order' =&gt; 'ASC',\n'posts_per_page' =&gt; 5, \n'paged' =&gt; $paged);\n$loop = new WP_Query( $args );\nwhile ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\n?&gt;\n &lt;li style=\"list-style:none;\"&gt;\n &lt;h3&gt;&lt;a href=\"&lt;?php the_permalink() ?&gt;\" title=\"&lt;?php the_title(); ?&gt;\"&gt;&lt;?php the_title();?&gt;&lt;/a&gt;&amp;nbsp;(&lt;?php echo get_the_date('d.m.Y');?&gt;)&lt;/h3&gt;\n &lt;a href=\"&lt;?php the_permalink() ?&gt;\" title=\"&lt;?php the_title(); ?&gt;\"&gt;\n &lt;?php \n/***** Thumbnail ******/\nthe_post_thumbnail(\n array(120, 90), \n array(\n\n 'class' =&gt; 'enter-class-here', //Specify class for product's image if any\n 'alt' =&gt; 'Preview unavailable', //Specify alternate text for products, in case if there is no products image\n 'title' =&gt; 'Enter-title-here' //Specify title if any\n )\n);\n/******* Thumbnail Ends ********/\n?&gt; &lt;/a&gt; \n&lt;/li&gt;&lt;hr /&gt;\n&lt;?php \nendwhile; ?&gt;\n\n&lt;?php wp_pagenavi( array( 'query' =&gt; $loop ) ); ?&gt;\n&lt;?php get_footer();?&gt;\n</code></pre>\n" }, { "answer_id": 293109, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>Using <code>query_posts</code> will always kill any hope of any pagination to be successfully done. You should use the <code>pre_get_posts</code> filter to adjust the main query if you care about pagination.</p>\n\n<p>It will be actually hard to achieve if you need whatever you do in a context of a page template and you should better use your own URL structure by adding appropriate rewrite rules.</p>\n" } ]
2016/11/15
[ "https://wordpress.stackexchange.com/questions/246228", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101279/" ]
I am using WP-PageNavi plugin, which I incorporated into my custom tpl page. There is woocommerce shortcode which holds all the products that I want to display, but I only ever see the same ones and only one page results. I do not see what am I doing wrong. The code is: ``` <?php /* Template Name: shine*/ ?> <?php get_header(); ?> <div class="wrapper clearfix"> <?php $args = array( 'post_type' => 'page', 'orderby' => 'title', 'order' => 'ASC', 'posts_per_page' => 5, 'paged' => get_query_var('paged'), ); ?> <?php query_posts($args); ?> <?php if ( have_posts() ) : ?> <?php while ( have_posts() ) : the_post(); ?> <?php endwhile; ?> <?php endif; ?> <h2>SHINE kolekcija</h2> <?php echo do_shortcode( '[product_attribute attribute="kolekcije" filter="shine"]' ); ?> <div class="naviButs"> <?php wp_pagenavi(); ?> </div> </div> <?php get_footer(); ?> ```
In case of `wp_query`, you can't use shortcode this way ``` <?php wp_pagenavi(); ?> ``` You need to use variable (in which you are storing wp\_query) in array inside shortcode. Use shortcode like this instead. Replace above shortcode with below one. ``` <?php wp_pagenavi( array( 'query' => $query_slider ) ); ?> ``` **UPDATE** This is a way in which I am using `wp_query` to show products list without shortcode that you used to display products. ``` <?php /* Template Name: shine */ get_header(); ?> <?php $paged = get_query_var('paged') ? get_query_var('paged') : 1; $args = array('post_type' => 'product', 'orderby' => 'title', 'order' => 'ASC', 'posts_per_page' => 5, 'paged' => $paged); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); ?> <li style="list-style:none;"> <h3><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title();?></a>&nbsp;(<?php echo get_the_date('d.m.Y');?>)</h3> <a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"> <?php /***** Thumbnail ******/ the_post_thumbnail( array(120, 90), array( 'class' => 'enter-class-here', //Specify class for product's image if any 'alt' => 'Preview unavailable', //Specify alternate text for products, in case if there is no products image 'title' => 'Enter-title-here' //Specify title if any ) ); /******* Thumbnail Ends ********/ ?> </a> </li><hr /> <?php endwhile; ?> <?php wp_pagenavi( array( 'query' => $loop ) ); ?> <?php get_footer();?> ```
246,270
<p>I have a custom role, <code>grocery</code>, that I would like to remove the "new content" (the + New dropdown) node from the top admin bar while this role is logged in. I have the following function but it is removing it currently for all roles including admin. Would like to find a way to limit this to just 'grocery' custom role.</p> <p>functions.php</p> <pre><code>add_action( 'admin_bar_menu', 'remove_new_content_menu', 999 ); function remove_new_content_menu( $wp_admin_bar ) { $wp_admin_bar-&gt;remove_node( 'new-content' ); } </code></pre>
[ { "answer_id": 246253, "author": "kovshenin", "author_id": 1316, "author_profile": "https://wordpress.stackexchange.com/users/1316", "pm_score": 2, "selected": false, "text": "<p>Searching the core codebase for <code>eval(</code> yielded no PHP results. Even the one in <code>class-pclzip.php</code> has been removed.</p>\n" }, { "answer_id": 246259, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": false, "text": "<p>No, <a href=\"https://core.trac.wordpress.org/ticket/9602\" rel=\"nofollow noreferrer\">not anymore</a>. </p>\n\n<p>A system like WordPress does not need to evaluate arbitrary code in core. For security reasons as well as a matter of best practices. </p>\n\n<p>If a plugin needs it for something, it's doing it wrong. </p>\n" } ]
2016/11/15
[ "https://wordpress.stackexchange.com/questions/246270", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93770/" ]
I have a custom role, `grocery`, that I would like to remove the "new content" (the + New dropdown) node from the top admin bar while this role is logged in. I have the following function but it is removing it currently for all roles including admin. Would like to find a way to limit this to just 'grocery' custom role. functions.php ``` add_action( 'admin_bar_menu', 'remove_new_content_menu', 999 ); function remove_new_content_menu( $wp_admin_bar ) { $wp_admin_bar->remove_node( 'new-content' ); } ```
Searching the core codebase for `eval(` yielded no PHP results. Even the one in `class-pclzip.php` has been removed.
246,273
<p>I understand this is probably a pretty noob situation, but I can't for the life of me figure out <a href="https://i.imgur.com/EPe5jGw.gifv" rel="nofollow noreferrer">why it's doing this</a>.</p> <p>Any ideas on how to overcome this so I can get WP installed on my server? I've tried searching around for an answer, but apparently nobody else has ran into this issue.</p> <p>The command entered is:</p> <pre><code>curl -O https://wordpress.org/latest.tar.gz </code></pre> <p>The output is a bunch of gobltygook on the screen. Expected output is downloading the zipped file.</p>
[ { "answer_id": 246278, "author": "Jen", "author_id": 13810, "author_profile": "https://wordpress.stackexchange.com/users/13810", "pm_score": 2, "selected": true, "text": "<p>Curl is outputting the response to the screen. You need to send the output to a file, like this:</p>\n\n<pre><code>curl https://wordpress.org/latest.tar.gz -o wordpress.tar.gz\n</code></pre>\n\n<p>Note the lowercase 'o', and the presence of a filename after that argument. You can name the file whatever you want. With this exact command, it will be downloaded into whatever folder you are currently in.</p>\n" }, { "answer_id": 246279, "author": "elicohenator", "author_id": 98507, "author_profile": "https://wordpress.stackexchange.com/users/98507", "pm_score": 2, "selected": false, "text": "<p>We were all noobs once :)</p>\n\n<p>Try running the same command with wget:</p>\n\n<pre><code>wget https://wordpress.org/latest.tar.gz\n</code></pre>\n\n<p>Than, you'll have to extract it with this command: </p>\n\n<pre><code>tar -xzvf latest.tar.gz \n</code></pre>\n\n<p>this will extract WordPress to a new directory called 'wordpress'</p>\n\n<p>Good Luck!</p>\n" } ]
2016/11/15
[ "https://wordpress.stackexchange.com/questions/246273", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107029/" ]
I understand this is probably a pretty noob situation, but I can't for the life of me figure out [why it's doing this](https://i.imgur.com/EPe5jGw.gifv). Any ideas on how to overcome this so I can get WP installed on my server? I've tried searching around for an answer, but apparently nobody else has ran into this issue. The command entered is: ``` curl -O https://wordpress.org/latest.tar.gz ``` The output is a bunch of gobltygook on the screen. Expected output is downloading the zipped file.
Curl is outputting the response to the screen. You need to send the output to a file, like this: ``` curl https://wordpress.org/latest.tar.gz -o wordpress.tar.gz ``` Note the lowercase 'o', and the presence of a filename after that argument. You can name the file whatever you want. With this exact command, it will be downloaded into whatever folder you are currently in.
246,301
<p>I'm running a standard WP_Query on a property website, and I want to find all properties that have a postcode beginning with 'SC1'. In the meta query, doing a normal LIKE on the postcode works, but it also returns properties with postcode SC13, which isn't what I want.</p> <p>As a result, I've changed my meta query to be as follows:</p> <pre><code>array( 'key' =&gt; '_address_postcode', 'value' =&gt; 'SC1 ', // Notice the addition of the space 'compare' =&gt; 'LIKE' ) </code></pre> <p>However.. it's not working. I've dug deeper and it seems that WordPress is trimming the values:</p> <p><a href="https://github.com/WordPress/WordPress/blob/af69f4ab1a0b44594b1f231c183f7a533575a893/wp-includes/class-wp-meta-query.php#L597" rel="nofollow noreferrer">https://github.com/WordPress/WordPress/blob/af69f4ab1a0b44594b1f231c183f7a533575a893/wp-includes/class-wp-meta-query.php#L597</a></p> <p>Any idea how I can search for meta values that specifically have a space at the end? I thought of doing something like so:</p> <pre><code>array( 'key' =&gt; '_address_postcode', 'value' =&gt; 'SC1 %',// Add a space then wildcard 'compare' =&gt; 'LIKE' ) </code></pre> <p>... but that doesn't work. Can anyone think of a way to get around this :-S</p>
[ { "answer_id": 246304, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>Note sure how your structure is, but here's one way, using <code>RLIKE</code> comparison and a <em>space</em> <a href=\"https://mariadb.com/kb/en/mariadb/pcre/#character-classes\" rel=\"nofollow noreferrer\">character class</a>:</p>\n\n<pre><code>array(\n 'key' =&gt; '_address_postcode',\n 'value' =&gt; '^SC1[[:space:]]', // Starts with 'SC1 ' \n 'compare' =&gt; 'RLIKE'\n)\n</code></pre>\n\n<p>Maybe you should consider adjusting the meta values, as suggested by @cybmeta?</p>\n\n<p>But note that meta queries can be slow, so alternatives might be better here (e.g. as a custom taxonomy?).</p>\n" }, { "answer_id": 246306, "author": "Mostafa Soufi", "author_id": 106877, "author_profile": "https://wordpress.stackexchange.com/users/106877", "pm_score": -1, "selected": false, "text": "<p>You can use <code>&amp;nbsp;</code> in your meta query.</p>\n\n<pre><code>array(\n 'key' =&gt; '_address_postcode',\n 'value' =&gt; 'SC1&amp;nbsp;',\n 'compare' =&gt; 'RLIKE'\n)\n</code></pre>\n" } ]
2016/11/15
[ "https://wordpress.stackexchange.com/questions/246301", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106541/" ]
I'm running a standard WP\_Query on a property website, and I want to find all properties that have a postcode beginning with 'SC1'. In the meta query, doing a normal LIKE on the postcode works, but it also returns properties with postcode SC13, which isn't what I want. As a result, I've changed my meta query to be as follows: ``` array( 'key' => '_address_postcode', 'value' => 'SC1 ', // Notice the addition of the space 'compare' => 'LIKE' ) ``` However.. it's not working. I've dug deeper and it seems that WordPress is trimming the values: <https://github.com/WordPress/WordPress/blob/af69f4ab1a0b44594b1f231c183f7a533575a893/wp-includes/class-wp-meta-query.php#L597> Any idea how I can search for meta values that specifically have a space at the end? I thought of doing something like so: ``` array( 'key' => '_address_postcode', 'value' => 'SC1 %',// Add a space then wildcard 'compare' => 'LIKE' ) ``` ... but that doesn't work. Can anyone think of a way to get around this :-S
Note sure how your structure is, but here's one way, using `RLIKE` comparison and a *space* [character class](https://mariadb.com/kb/en/mariadb/pcre/#character-classes): ``` array( 'key' => '_address_postcode', 'value' => '^SC1[[:space:]]', // Starts with 'SC1 ' 'compare' => 'RLIKE' ) ``` Maybe you should consider adjusting the meta values, as suggested by @cybmeta? But note that meta queries can be slow, so alternatives might be better here (e.g. as a custom taxonomy?).
246,319
<p>Using the category.php template file and I can get all other information about a post except the excerpt or the content. Here's the code I'm using:</p> <pre><code>$cat = get_queried_object(); $posts = get_posts(array('posts_per_page' =&gt; 15, 'offset' =&gt; 0, 'category' =&gt; $cat-&gt;term_id)); foreach($posts as $post) { $postID = $post-&gt;ID; $title = get_the_title($postID); $link = get_permalink($postID); $date = get_the_date('M. j, Y', $postID); $authors = coauthors_posts_links(null, null, null, null, false); $excerpt = get_the_excerpt($postID); $thumb = get_the_post_thumbnail($post, array('class' =&gt; 'front-page-tease-sm')); echo '&lt;div class="category-post"&gt;'; // Left box - date printf('&lt;div class="date"&gt;%1$s&lt;/div&gt;', esc_attr($date)); // Middle box flex - headline, author, and excerpt echo '&lt;div class="category-post-info"&gt;'; printf('&lt;a class="category-headline" href="%1$s"&gt;%2$s&lt;/a&gt;', esc_attr($link), esc_html($title)); printf('&lt;div class="category-author"&gt;By %1$s&lt;/div&gt;', $authors); printf('&lt;div class="category-tease"&gt;%1$s&lt;/div&gt;', $excerpt); echo '&lt;/div&gt;'; // Right box - thumbnail printf($thumb); echo '&lt;/div&gt;'; } </code></pre> <p>This code does exactly what I expect it to do except for when it comes to excerpts. It prints nothing for the excerpt, not even HTML tags.</p>
[ { "answer_id": 246304, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>Note sure how your structure is, but here's one way, using <code>RLIKE</code> comparison and a <em>space</em> <a href=\"https://mariadb.com/kb/en/mariadb/pcre/#character-classes\" rel=\"nofollow noreferrer\">character class</a>:</p>\n\n<pre><code>array(\n 'key' =&gt; '_address_postcode',\n 'value' =&gt; '^SC1[[:space:]]', // Starts with 'SC1 ' \n 'compare' =&gt; 'RLIKE'\n)\n</code></pre>\n\n<p>Maybe you should consider adjusting the meta values, as suggested by @cybmeta?</p>\n\n<p>But note that meta queries can be slow, so alternatives might be better here (e.g. as a custom taxonomy?).</p>\n" }, { "answer_id": 246306, "author": "Mostafa Soufi", "author_id": 106877, "author_profile": "https://wordpress.stackexchange.com/users/106877", "pm_score": -1, "selected": false, "text": "<p>You can use <code>&amp;nbsp;</code> in your meta query.</p>\n\n<pre><code>array(\n 'key' =&gt; '_address_postcode',\n 'value' =&gt; 'SC1&amp;nbsp;',\n 'compare' =&gt; 'RLIKE'\n)\n</code></pre>\n" } ]
2016/11/16
[ "https://wordpress.stackexchange.com/questions/246319", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101999/" ]
Using the category.php template file and I can get all other information about a post except the excerpt or the content. Here's the code I'm using: ``` $cat = get_queried_object(); $posts = get_posts(array('posts_per_page' => 15, 'offset' => 0, 'category' => $cat->term_id)); foreach($posts as $post) { $postID = $post->ID; $title = get_the_title($postID); $link = get_permalink($postID); $date = get_the_date('M. j, Y', $postID); $authors = coauthors_posts_links(null, null, null, null, false); $excerpt = get_the_excerpt($postID); $thumb = get_the_post_thumbnail($post, array('class' => 'front-page-tease-sm')); echo '<div class="category-post">'; // Left box - date printf('<div class="date">%1$s</div>', esc_attr($date)); // Middle box flex - headline, author, and excerpt echo '<div class="category-post-info">'; printf('<a class="category-headline" href="%1$s">%2$s</a>', esc_attr($link), esc_html($title)); printf('<div class="category-author">By %1$s</div>', $authors); printf('<div class="category-tease">%1$s</div>', $excerpt); echo '</div>'; // Right box - thumbnail printf($thumb); echo '</div>'; } ``` This code does exactly what I expect it to do except for when it comes to excerpts. It prints nothing for the excerpt, not even HTML tags.
Note sure how your structure is, but here's one way, using `RLIKE` comparison and a *space* [character class](https://mariadb.com/kb/en/mariadb/pcre/#character-classes): ``` array( 'key' => '_address_postcode', 'value' => '^SC1[[:space:]]', // Starts with 'SC1 ' 'compare' => 'RLIKE' ) ``` Maybe you should consider adjusting the meta values, as suggested by @cybmeta? But note that meta queries can be slow, so alternatives might be better here (e.g. as a custom taxonomy?).
246,372
<p>I'd like to create a subclass of <code>WP_Post</code> and add some "model functionality" to it. How can i force WP to create objects of that child class instead of WP_Post itself, when i query for my custom post type?</p> <p><strong>Example:</strong></p> <p>Let's assume i have two custom post types: <code>Book</code> and <code>Review</code>. Each Book can have many Reviews. On my Book, I want a method to sum up all its reviews. I'd define the following class:</p> <pre><code>class Book extends WP_Post { public function reviewsSummary() { // Retrieve all reviews for $this book // Sum up their ratings // Return that sum } } </code></pre> <p>Is there a way, for example when calling <code>register_post_type()</code>, to force WordPress into casting all posts of type "book" into my <code>Book</code> class instead of <code>WP_Post</code>?</p> <p>Could look something like this:</p> <pre><code>register_post_type('book', [ …, 'class' =&gt; Acme\Models\Book::class ]); </code></pre>
[ { "answer_id": 246404, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 3, "selected": false, "text": "<p><code>WP_Post</code> class in WP is <code>final</code>, so it explicitly forbids subclassing. It is also quite vague in practice, a lot of code around will happily take/produce post–<em>like</em> objects as long as they have established data structure.</p>\n\n<p>It is challenging to recommend an alternative without knowing more about your specific needs. In a general and assuming use in templates the typical would be to create a template tag function that will calculate score for review post, provided to it as argument and/or current in the Loop.</p>\n" }, { "answer_id": 246821, "author": "jsphpl", "author_id": 82253, "author_profile": "https://wordpress.stackexchange.com/users/82253", "pm_score": 3, "selected": false, "text": "<h2>How to \"subclass\" <code>WP_Post</code></h2>\n\n<p>Thank you, @Rarst for pointing out the issue that <strong>you can't subclass WP_Post</strong>, which is a major problem in this case.</p>\n\n<h3>Workaround</h3>\n\n<p>There is, however, a way of working around it using a wrapper class that has a real WP_Post object stored as an attribute and exposes it via magic methods in order to behave like one.</p>\n\n<p>Two examples of that approach can be found <a href=\"https://github.com/hanamura/wp-model\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://danielmenjivar.com/blog/extending-the-wp_post-class\" rel=\"nofollow noreferrer\">here</a>. </p>\n\n<p><em>Warning: In many cases, this approach might not work for different reasons, one being that these objects won't pass an <code>instanceof WP_Post</code> check.</em></p>\n\n<hr>\n\n<h2>Where to hook in</h2>\n\n<p>So let's assume we could replace WP_Post somehow. The thing i was actually looking for was <strong>where to hook in</strong> in order to replace <code>WP_Post</code>. The answer to this question is the <code>posts_results</code> filter and was given here: <a href=\"https://stackoverflow.com/a/40631962/3919281\">https://stackoverflow.com/a/40631962/3919281</a></p>\n" } ]
2016/11/16
[ "https://wordpress.stackexchange.com/questions/246372", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82253/" ]
I'd like to create a subclass of `WP_Post` and add some "model functionality" to it. How can i force WP to create objects of that child class instead of WP\_Post itself, when i query for my custom post type? **Example:** Let's assume i have two custom post types: `Book` and `Review`. Each Book can have many Reviews. On my Book, I want a method to sum up all its reviews. I'd define the following class: ``` class Book extends WP_Post { public function reviewsSummary() { // Retrieve all reviews for $this book // Sum up their ratings // Return that sum } } ``` Is there a way, for example when calling `register_post_type()`, to force WordPress into casting all posts of type "book" into my `Book` class instead of `WP_Post`? Could look something like this: ``` register_post_type('book', [ …, 'class' => Acme\Models\Book::class ]); ```
`WP_Post` class in WP is `final`, so it explicitly forbids subclassing. It is also quite vague in practice, a lot of code around will happily take/produce post–*like* objects as long as they have established data structure. It is challenging to recommend an alternative without knowing more about your specific needs. In a general and assuming use in templates the typical would be to create a template tag function that will calculate score for review post, provided to it as argument and/or current in the Loop.
246,377
<p>From the wp admin login page I click to reset my password (not on the theme, on wp). I get the email but it contains no url to click. Plugins are disabled. What shoud I do? </p>
[ { "answer_id": 246395, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p>Check out the <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-login.php#L281\" rel=\"nofollow noreferrer\"><code>wp-login.php</code></a> on GitHub.</p>\n\n<p>The default blocks looks like:</p>\n\n<pre><code>// Redefining user_login ensures we return the right case in the email.\n$user_login = $user_data-&gt;user_login;\n$user_email = $user_data-&gt;user_email;\n$key = get_password_reset_key( $user_data );\nif ( is_wp_error( $key ) ) {\n return $key;\n}\n$message = __('Someone has requested a password reset for the following account:') . \"\\r\\n\\r\\n\";\n$message .= network_home_url( '/' ) . \"\\r\\n\\r\\n\";\n$message .= sprintf(__('Username: %s'), $user_login) . \"\\r\\n\\r\\n\";\n$message .= __('If this was a mistake, just ignore this email and nothing will happen.') . \"\\r\\n\\r\\n\";\n$message .= __('To reset your password, visit the following address:') . \"\\r\\n\\r\\n\";\n$message .= '&lt;' . network_site_url(\"wp-login.php?action=rp&amp;key=$key&amp;login=\" . rawurlencode($user_login), 'login') . \"&gt;\\r\\n\";\n</code></pre>\n\n<p>You should be able to <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-login.php#L359\" rel=\"nofollow noreferrer\">filter</a> the password reset message with <code>'retrieve_password_message'</code> and change it to what you need.</p>\n\n<pre><code>$message = apply_filters( 'retrieve_password_message', $message, $key, $user_login, $user_data );\n</code></pre>\n" }, { "answer_id": 285213, "author": "Luke Seall", "author_id": 29280, "author_profile": "https://wordpress.stackexchange.com/users/29280", "pm_score": 4, "selected": true, "text": "<p>The problem is the <code>&lt;</code> and <code>&gt;</code> which surround the reset URL in <code>wp-login.php</code>. You can remove them using <a href=\"https://developer.wordpress.org/reference/hooks/retrieve_password_message/\" rel=\"nofollow noreferrer\">retrieve_password_message</a> in your theme <code>functions.php</code> file like below:</p>\n\n<pre><code>add_filter(\"retrieve_password_message\", \"mapp_custom_password_reset\", 99, 4);\n\nfunction mapp_custom_password_reset($message, $key, $user_login, $user_data ) {\n\n $message = \"Someone has requested a password reset for the following account:\n\n\" . sprintf(__('%s'), $user_data-&gt;user_email) . \"\n\nIf this was a mistake, just ignore this email and nothing will happen.\n\nTo reset your password, visit the following address:\n\n\" . network_site_url(\"wp-login.php?action=rp&amp;key=$key&amp;login=\" . rawurlencode($user_login), 'login') . \"\\r\\n\";\n\n\n return $message;\n\n}\n</code></pre>\n" }, { "answer_id": 337778, "author": "CDuv", "author_id": 167904, "author_profile": "https://wordpress.stackexchange.com/users/167904", "pm_score": 2, "selected": false, "text": "<p>If you only want to remove the angle brackets WordPress added but let the rest of the generated message unchanged, add the following to the <code>functions.php</code> of your WordPress theme (eg. <code>wp-content/themes/some_awesome_theme/functions.php</code>).</p>\n\n<pre><code>/**\n * Removes angle brackets (characters &lt; and &gt;) arounds URLs in a given string\n *\n * @param string $string The string to remove potential angle brackets from\n *\n * @return string $string where any angle brackets surrounding an URL have been removed.\n */\nfunction remove_angle_brackets_around_url($string)\n{\n return preg_replace('/&lt;(' . preg_quote(network_site_url(), '/') . '[^&gt;]*)&gt;/', '\\1', $string);\n}\n\n// Apply the remove_angle_brackets_around_url() function on the \"retrieve password\" message:\nadd_filter('retrieve_password_message', 'remove_angle_brackets_around_url', 99, 1);\n</code></pre>\n" }, { "answer_id": 338696, "author": "Travis", "author_id": 168766, "author_profile": "https://wordpress.stackexchange.com/users/168766", "pm_score": 1, "selected": false, "text": "<p>I had this problem and wanted to share how I solved it here.</p>\n\n<p>I opened the email and to the right where you would see the time stamp of when you got the email, there will be three dots. </p>\n\n<p>Click on that and then click \"show original\"</p>\n\n<p>From there you will see the code for the email. Look for the part of the email where it says you should click on the link.</p>\n\n<p>Copy the link that is within the &lt; > marks. Paste it into your browser and voila, you will be able to reset.</p>\n" }, { "answer_id": 358109, "author": "H1ghlander", "author_id": 182352, "author_profile": "https://wordpress.stackexchange.com/users/182352", "pm_score": 1, "selected": false, "text": "<p>I had this problem and did similar to Travis...</p>\n\n<ol>\n<li>right click on the email message</li>\n<li>select view source</li>\n<li>copy the link you see below the words 'To reset your password, visit the following address:'</li>\n<li>paste it into your domain box and hey presto.</li>\n</ol>\n\n<p>hope this helps too :)</p>\n" } ]
2016/11/16
[ "https://wordpress.stackexchange.com/questions/246377", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107112/" ]
From the wp admin login page I click to reset my password (not on the theme, on wp). I get the email but it contains no url to click. Plugins are disabled. What shoud I do?
The problem is the `<` and `>` which surround the reset URL in `wp-login.php`. You can remove them using [retrieve\_password\_message](https://developer.wordpress.org/reference/hooks/retrieve_password_message/) in your theme `functions.php` file like below: ``` add_filter("retrieve_password_message", "mapp_custom_password_reset", 99, 4); function mapp_custom_password_reset($message, $key, $user_login, $user_data ) { $message = "Someone has requested a password reset for the following account: " . sprintf(__('%s'), $user_data->user_email) . " If this was a mistake, just ignore this email and nothing will happen. To reset your password, visit the following address: " . network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user_login), 'login') . "\r\n"; return $message; } ```
246,385
<p>I am currently having an issue with memory when my site tries to generate a tree of child pages. to my understanding query is too large (WP has 60000 pages)</p> <p>following is code i am using</p> <pre><code> ?php global $post; wp_list_pages( array( 'child_of' =&gt; $post-&gt;ID, // Only pages that are children of the current page 'depth' =&gt; 1 , // Only show one level of hierarchy 'sort_order' =&gt; 'asc', 'title_li' =&gt;$post-&gt;post_title )); ?&gt; </code></pre> <p>Is there any additional arguments i can add to make the query smaller or is there any better way of displaying a list of child pages?</p> <p>Thank you in advance.</p>
[ { "answer_id": 246394, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">WP_Query</a> has <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters\" rel=\"nofollow noreferrer\">Pagination_Parameters</a> like <code>posts_per_page</code> and <code>offset</code> to help you out. Just page the results to limit the query to a more reasonable number per page. </p>\n" }, { "answer_id": 246407, "author": "Cl0udSt0ne", "author_id": 107136, "author_profile": "https://wordpress.stackexchange.com/users/107136", "pm_score": 0, "selected": false, "text": "<p>I can't see any wrong in your code, maybe you should check that whether you can got correct post id via <code>$post-&gt;ID</code>, sometimes some code before yours changed $post object cause that you can't get it and <code>wp_list_pages()</code> will display all pages.</p>\n" }, { "answer_id": 246995, "author": "Artem Ankudovich", "author_id": 92228, "author_profile": "https://wordpress.stackexchange.com/users/92228", "pm_score": 0, "selected": false, "text": "<p>To shorten the execution time i ended up using WP_Query as suggested by jgraup</p>\n\n<p>the code to generate list of children is below </p>\n\n<pre><code>&lt;?php global $post;\n echo '&lt;p&gt;'. get_the_title().'&lt;/p&gt;'; // current post title\n $query = new WP_Query( array( 'post_type' =&gt; 'page', 'post_parent' =&gt; $post-&gt;ID,'order' =&gt; 'ASC') ); // find all pages with parentId of current page id \n if ( $query-&gt;have_posts() ) {\n echo '&lt;ul&gt;'; \n while ( $query-&gt;have_posts() ) {//loop through results\n $query-&gt;the_post();\n echo '&lt;li&gt;&lt;a href='. get_page_link($post-&gt;ID) .'&gt;' . get_the_title() . '&lt;/a&gt;&lt;/li&gt;';//li with link to the page\n }\n echo '&lt;/ul&gt;';\n /* Restore original Post Data */\n wp_reset_postdata();\n } else {\n // no posts found\n }\n\n\n ?&gt;\n</code></pre>\n" } ]
2016/11/16
[ "https://wordpress.stackexchange.com/questions/246385", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92228/" ]
I am currently having an issue with memory when my site tries to generate a tree of child pages. to my understanding query is too large (WP has 60000 pages) following is code i am using ``` ?php global $post; wp_list_pages( array( 'child_of' => $post->ID, // Only pages that are children of the current page 'depth' => 1 , // Only show one level of hierarchy 'sort_order' => 'asc', 'title_li' =>$post->post_title )); ?> ``` Is there any additional arguments i can add to make the query smaller or is there any better way of displaying a list of child pages? Thank you in advance.
[WP\_Query](https://codex.wordpress.org/Class_Reference/WP_Query) has [Pagination\_Parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters) like `posts_per_page` and `offset` to help you out. Just page the results to limit the query to a more reasonable number per page.
246,401
<p>I'm developing a new theme for WP and I want to add different sorts of widgets and different classes, because I want these widgets to look different (for example footer widgets should have another styling, and now I can only target them with the "widget class", one class for all).</p> <pre><code>function create_widget($name, $id, $description) { register_sidebar(array( 'name' =&gt; __( $name ), 'id' =&gt; $id, 'description' =&gt; __( $description ), 'before_widget' =&gt; '&lt;div class="widget"&gt;', 'after_widget' =&gt; '&lt;/div&gt;', 'before_title' =&gt; '&lt;h2&gt;', 'after_title' =&gt; '&lt;/h2&gt;', )); } </code></pre> <p>Is this even possible or do I have to delete my class "widgets" and adding new classes everytime to the new widget?</p>
[ { "answer_id": 246405, "author": "prosti", "author_id": 88606, "author_profile": "https://wordpress.stackexchange.com/users/88606", "pm_score": 0, "selected": false, "text": "<p>How about</p>\n\n<pre><code>function create_widget($name, $id, $description) {\n\n register_sidebar(array(\n\n'name' =&gt; __( $name ),\n\n 'id' =&gt; $id,\n 'description' =&gt; __( $description ),\n 'before_widget' =&gt; '&lt;div class=\"widget widget_' . $name . '\" &gt;',\n 'after_widget' =&gt; '&lt;/div&gt;',\n 'before_title' =&gt; '&lt;h2&gt;',\n 'after_title' =&gt; '&lt;/h2&gt;',\n ));\n\n}\n</code></pre>\n\n<p>This way you will have the <code>widget</code> class wrapper for your widgets and also the <code>widget_$name</code> class, that you use from CSS.\nOr you can completely remove the <code>widget</code> CSS class if you plan to do that, and everything looks great when you test.</p>\n\n<p>Make sure you understand what CSS styles you will loose after you remove the <code>widget</code> class. But this is possible.</p>\n" }, { "answer_id": 246409, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>When registering a sidebar, you can use certain placeholders for the widget classes. Here's an example taken from the codex:</p>\n\n<pre><code>'before_widget' =&gt; '&lt;li id=\"%1$s\" class=\"widget %2$s\"&gt;',\n</code></pre>\n\n<p>It's the lack of <code>%1$s</code> and <code>%2$s</code> that is causing your issues. When in doubt always read the documentation on the codex and the developer hub/handbooks</p>\n" }, { "answer_id": 246420, "author": "farhan Asad", "author_id": 107126, "author_profile": "https://wordpress.stackexchange.com/users/107126", "pm_score": -1, "selected": false, "text": "<p>To add another sidebar you simply need to register another instance. If you are registering more than one, then you will also need to name them. Change your functions.php file to look like the following. Take care to add in the extra line that specifies the name of your sidebar. Once these are functions are defined, you will notice the extra sidebar appear in the WordPress Dashboard under the Appearance > Widgets option. It’s here that you can drag and drop all your widgets into your various sidebars.</p>\n\n 'sidebar 1',\n 'before_widget' => '',\n 'after_widget' => '',\n 'before_title' => '<h2>',\n 'after_title' => '</h2>'\n ));\n\n register_sidebar(array(\n 'name' => 'footer sidebar 1',\n 'before_widget' => '',\n 'after_widget' => '',\n 'before_title' => '<h2>',\n 'after_title' => '</h2>'\n ));\n\n}?>\n" } ]
2016/11/16
[ "https://wordpress.stackexchange.com/questions/246401", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107133/" ]
I'm developing a new theme for WP and I want to add different sorts of widgets and different classes, because I want these widgets to look different (for example footer widgets should have another styling, and now I can only target them with the "widget class", one class for all). ``` function create_widget($name, $id, $description) { register_sidebar(array( 'name' => __( $name ), 'id' => $id, 'description' => __( $description ), 'before_widget' => '<div class="widget">', 'after_widget' => '</div>', 'before_title' => '<h2>', 'after_title' => '</h2>', )); } ``` Is this even possible or do I have to delete my class "widgets" and adding new classes everytime to the new widget?
When registering a sidebar, you can use certain placeholders for the widget classes. Here's an example taken from the codex: ``` 'before_widget' => '<li id="%1$s" class="widget %2$s">', ``` It's the lack of `%1$s` and `%2$s` that is causing your issues. When in doubt always read the documentation on the codex and the developer hub/handbooks
246,444
<p>I am working on WordPress plugin and I have added support for wp cron there. See the code below:</p> <pre><code>function __construct(){ //Cron Job add_action('init', array($this,'g_order_sync')); add_action('ga_order_syn', array($this,'sync_order')); add_filter('cron_schedules',array($this,'my_cron_schedules')); } function my_cron_schedules($schedules){ if(!isset($schedules["10sec"])){ $schedules["10sec"] = array( 'interval' =&gt; 10, 'display' =&gt; __('Once every 5 minutes')); } return $schedules; } public function g_order_sync(){ if( !wp_next_scheduled('ga_order_syn') ) { wp_schedule_event( time(), '10sec', 'ga_order_syn' ); } } public function sync_order(){ $content = "some text here"; $fp = fopen($_SERVER['DOCUMENT_ROOT']. "/myText.txt","wb"); fwrite($fp,$content); fclose($fp); } </code></pre> <p>When I print cron using <code>print_r( _get_cron_array() );</code>, it shows me that my cron(<code>ga_order_syn</code>) is scheduled every 10 second but <code>sync_order()</code> function does not create file at <code>DOCUMENT_ROOT</code>. If I add a call to the <code>wp_mail()</code> function, it does not send me an mail.</p> <p>What is issue with my code? Why is it not working?</p>
[ { "answer_id": 246422, "author": "Jen", "author_id": 13810, "author_profile": "https://wordpress.stackexchange.com/users/13810", "pm_score": 1, "selected": false, "text": "<p>This is a fantastic question - I've personally never run into this before, but here's what I'd try, assuming:</p>\n\n<ul>\n<li>you have an image of a server that you've been using to spin up new instances</li>\n<li>you're using a CDN and cloud storage for images and uploads (rather than having a local uploads folder)</li>\n</ul>\n\n<p>With those two assumptions, it means you can spin up and spin down instances of the server without worrying about data loss - the files and config between each server are identical.</p>\n\n<ul>\n<li>Spin up a new instance of your server, but don't add it to the load balancer</li>\n<li>point your hosts file to the IP of the instance</li>\n<li>update the plugin on the instance, make sure everything is working as you expect</li>\n<li>create an image of the updated server</li>\n<li>spin up one more instance based on the updated image</li>\n<li>point the LB at the new instances</li>\n</ul>\n\n<p>This is a bit of a painful process, and I think next would also look into automated deployment tools, such as Capistrano, or maybe a service like Deploy.</p>\n" }, { "answer_id": 246423, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>This needs to be done in few steps</p>\n\n<ol>\n<li>replicate the DB (in case you do not already have one). </li>\n<li>remove one server from the LB, change its config to point to the \"new\" DB.</li>\n<li>connect to the admin area only to that server (define in your localhosts file the IP or any other way and do the upgrade.). </li>\n<li>In the LB turn the other server off and the upgraded one on.</li>\n<li>update the plugin on the other server (basically it is enough to update the code)</li>\n<li>connect the other server to the \"new\" DB</li>\n<li>change the LB configuration to enable the other server.</li>\n</ol>\n\n<p>As this is not an extremely quick procedure you should either minimize the number of plugins you use as pure plugins, or try to upgrade as many as possible at the same time.</p>\n\n<p>(I wrote plugin, but it applies to themes and core as well)</p>\n" }, { "answer_id": 259504, "author": "Erik Kangas", "author_id": 115093, "author_profile": "https://wordpress.stackexchange.com/users/115093", "pm_score": 0, "selected": false, "text": "<p>I have been in this same situation for many years -- 3 servers behind a load balancer. Different disk subsystems. Shared database. I actually found this question by searching for some way to simplify management. What I have been doing (and what has been working fine) for many years is the following:</p>\n\n<ol>\n<li>Make sure that I have automatic backups of everything (database and files) ... just in case. I have never needed them, but that is always a prerequisite.</li>\n<li>Login to the WP admin console and note what server you are connecting to, if possible</li>\n<li>Update wordpress and plugins using the normal UI methods </li>\n<li>Login to the server in question (and if you could not tell which it was using some feature of your infrastructure, look at the time stamps of the plugin files that you just updated).</li>\n<li>Copy the wordpress directory tree to the other server(s)</li>\n<li>Backup the old WP directories there and replace with the new directories.</li>\n</ol>\n\n<p>This has never failed. However, it is not 100% recommended as WP running on the severs that are not yet upgraded could have issues during the upgrade due to software or database inconsistencies. Usually the process is very quick anyway.</p>\n\n<p>The best solution is to do the above, but by taking the servers you are not updating out of service first and updating them before re-enabling them on your load balancer. I suppose it is up to you where you fit on the \"quick and easy\" vs \"risk\" curve for your blog.</p>\n" }, { "answer_id": 261228, "author": "indextwo", "author_id": 17826, "author_profile": "https://wordpress.stackexchange.com/users/17826", "pm_score": 0, "selected": false, "text": "<p>Most of these answers seem to be based on the assumption that you are <em>only</em> running/updating your website on a remote server; and as such, some of the solutions seem very complicated. I have two sites that both run behind load balancers - one with 2 servers, and one with 4; both of which are scalable to as many servers as required. Both of these sites are maintained &amp; updated with a couple of clicks using a local build, Git and Jenkins.</p>\n\n<p>I have a functional copy of the sites on <code>localhost</code> running under <code>XAMPP</code>. The databases aren't identical, but the file structure is. I also have a private BitBucket account and a <code>.gitignore</code> to ignore things like my local <code>wp-config</code> and the <code>/uploads/</code> folder (which I don't want or need to sync with the server). </p>\n\n<p>Whenever there's a plugin update, I update it through Wordpress on my <code>localhost</code> as normal. Once it's done, I open up my Git client and push the changes to BitBucket. </p>\n\n<p>On the server, I have a <a href=\"https://jenkins.io/\" rel=\"nofollow noreferrer\">Jenkins</a> service that is set to build from my BitBucket source to the live site. I click <em>Build</em>, wait a couple of minutes, and it's all done. Jenkins builds to all servers, and there's rsync available to make sure everything is simpatico.</p>\n\n<p>So my entire update process is <strong>Update local</strong> -> <strong>Git push</strong> -> <strong>Jenkins build</strong></p>\n\n<p>This is reliant on you having a <code>localhost</code> or other controllable build that you can push with Git, but once it's set up and running, updating your load-balanced Wordpress site becomes incredibly easy.</p>\n" }, { "answer_id": 354018, "author": "Barry Chapman", "author_id": 123076, "author_profile": "https://wordpress.stackexchange.com/users/123076", "pm_score": 0, "selected": false, "text": "<p>It has been a while since this was answered, but I have some thoughts that I thought I would add - having had to take care of this same situation several times over the last few years. It involved several extremely high traffic and high visibility sites that were load balanced with three to four nodes each.</p>\n\n<p>The first thing I did was I wrote a linux script that essentially runs as a cron job twice a day. It checks for available core and plugin updates using the <code>wp-cli</code> tool. It runs on each server that is a node of the LB. It worked (at the time) in conjunction with a plugin that could limit what plugins were updated automatically.</p>\n\n<p>The most recent thing I did was having a staging server that we accessed for content/code changes. The changes on that environment were then synced to whatever live nodes were active at the time. This was done in AWS EC2 instances using RDS for DB. It allowed for relatively seamless updating. We had to do a bit of customization around the DB push in order to preserve production data which had not been synced to our staging environment.</p>\n" } ]
2016/11/16
[ "https://wordpress.stackexchange.com/questions/246444", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98100/" ]
I am working on WordPress plugin and I have added support for wp cron there. See the code below: ``` function __construct(){ //Cron Job add_action('init', array($this,'g_order_sync')); add_action('ga_order_syn', array($this,'sync_order')); add_filter('cron_schedules',array($this,'my_cron_schedules')); } function my_cron_schedules($schedules){ if(!isset($schedules["10sec"])){ $schedules["10sec"] = array( 'interval' => 10, 'display' => __('Once every 5 minutes')); } return $schedules; } public function g_order_sync(){ if( !wp_next_scheduled('ga_order_syn') ) { wp_schedule_event( time(), '10sec', 'ga_order_syn' ); } } public function sync_order(){ $content = "some text here"; $fp = fopen($_SERVER['DOCUMENT_ROOT']. "/myText.txt","wb"); fwrite($fp,$content); fclose($fp); } ``` When I print cron using `print_r( _get_cron_array() );`, it shows me that my cron(`ga_order_syn`) is scheduled every 10 second but `sync_order()` function does not create file at `DOCUMENT_ROOT`. If I add a call to the `wp_mail()` function, it does not send me an mail. What is issue with my code? Why is it not working?
This is a fantastic question - I've personally never run into this before, but here's what I'd try, assuming: * you have an image of a server that you've been using to spin up new instances * you're using a CDN and cloud storage for images and uploads (rather than having a local uploads folder) With those two assumptions, it means you can spin up and spin down instances of the server without worrying about data loss - the files and config between each server are identical. * Spin up a new instance of your server, but don't add it to the load balancer * point your hosts file to the IP of the instance * update the plugin on the instance, make sure everything is working as you expect * create an image of the updated server * spin up one more instance based on the updated image * point the LB at the new instances This is a bit of a painful process, and I think next would also look into automated deployment tools, such as Capistrano, or maybe a service like Deploy.
246,466
<p>In WordPress the default permalink URL like this</p> <p>http://***.com/?p=123</p> <p>when I change it to this: </p> <p>http://***.com/new/sample-post/</p> <p>Is that possible I still can get the default permalink link text, because the second URL is too long, it looks not so good when someone share it.</p>
[ { "answer_id": 246467, "author": "Gonçalo Ribeiro", "author_id": 107156, "author_profile": "https://wordpress.stackexchange.com/users/107156", "pm_score": 2, "selected": false, "text": "<p>When you are editing a post you can notice the URL in your browser looks like</p>\n\n<pre><code>http://***.com/wp-admin/post.php?post=1351&amp;action=edit\n</code></pre>\n\n<p>The number in the URL corresponds to the ID of your post. So you can access your post with that ID. In this example the short link for the post would be</p>\n\n<pre><code>http://***.com/?p=1351\n</code></pre>\n\n<p>When a visitor browsers this URL she will be redirected to the full URL if you have the correct options set in <code>Settings &gt; Permalinks</code>.</p>\n\n<p>If you need to get the short URL programatically you can use the <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_shortlink\" rel=\"nofollow noreferrer\"><code>wp_get_shortlink()</code></a> function. This function returns the link, which can then be printed.</p>\n" }, { "answer_id": 246474, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p>You can concatenate a url with the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Post\" rel=\"nofollow noreferrer\">ID</a> using <a href=\"https://developer.wordpress.org/reference/functions/get_site_url/\" rel=\"nofollow noreferrer\"><code>get_site_url</code></a>. This assumes the <a href=\"https://developer.wordpress.org/reference/functions/get_the_id/\" rel=\"nofollow noreferrer\">ID</a> is valid.</p>\n\n<pre><code>&lt;?php \n\n echo get_site_url(null, '/?p=' . get_the_ID() );\n\n?&gt;\n</code></pre>\n\n<p>Although <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_shortlink\" rel=\"nofollow noreferrer\"><code>wp_get_shortlink()</code></a> above seems like a better choice.</p>\n" } ]
2016/11/17
[ "https://wordpress.stackexchange.com/questions/246466", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/18787/" ]
In WordPress the default permalink URL like this http://\*\*\*.com/?p=123 when I change it to this: http://\*\*\*.com/new/sample-post/ Is that possible I still can get the default permalink link text, because the second URL is too long, it looks not so good when someone share it.
When you are editing a post you can notice the URL in your browser looks like ``` http://***.com/wp-admin/post.php?post=1351&action=edit ``` The number in the URL corresponds to the ID of your post. So you can access your post with that ID. In this example the short link for the post would be ``` http://***.com/?p=1351 ``` When a visitor browsers this URL she will be redirected to the full URL if you have the correct options set in `Settings > Permalinks`. If you need to get the short URL programatically you can use the [`wp_get_shortlink()`](https://codex.wordpress.org/Function_Reference/wp_get_shortlink) function. This function returns the link, which can then be printed.
246,484
<p>I am writing a plugin. When an item (painting) is clicked for deleting while a list of them is shown at the dashboard, I want to delete it and then redirect the user to the previous page shown. So the action "delete" is catched and then goto action "show"</p> <pre><code>public function display_paintings_page() { $request = $this-&gt;get_request(); switch ($request["action"]) { case "delete": ob_clean(); ob_start(); Myplugin_Painting_Info::delete($request["painting_id"]); wp_safe_redirect(wp_get_referer()); break; case "show": include_once( "partials/myplugin-admin-paintings.php" ); break; /* / ... */ } } </code></pre> <p>This is the best I could manage. But the action messages (error, success) from the "delete" method are not shown, as the output buffer has to be cleaned to prevent a "headers already sent" error.</p> <p>Is there any way to do this besides ajax or displaying an intermediate page with an "item removed; click to return"?</p>
[ { "answer_id": 246488, "author": "Jen", "author_id": 13810, "author_profile": "https://wordpress.stackexchange.com/users/13810", "pm_score": 2, "selected": false, "text": "<p>opinion: I like ajax interactions for things like this. DELETEs are cheap, fast things to accomplish server side, loading the whole page all over again takes too long. /opinion</p>\n\n<p>If you're going to use redirects and want to display error messages, you have a couple of options.</p>\n\n<h2>1. Use the redirect url itself to pass information to the next request.</h2>\n\n<p>Something like this:</p>\n\n<pre><code>wp_safe_redirect('your_plugin_url?msg=' . $message_code);\n</code></pre>\n\n<p>In the view:</p>\n\n<pre><code>$messages = array(\n '1' =&gt; 'Success!',\n '2' =&gt; 'Something went wrong :('\n);\n\n$msg_id = isset($_GET['msg']) ? $_GET['err'] : 0;\nif (array_key_exists($msg_id, $messages)) {\n echo $messages[$msg_id];\n}\n</code></pre>\n\n<h2>2. Use the $_SESSION to pass around data.</h2>\n\n<p>Put <code>session_start()</code> somewhere in the early initialization of your plugin, to make sure it's run before any page output is sent. </p>\n\n<p>Then record the error or success messages in the session:</p>\n\n<pre><code>$_SESSION['painting_delete_msg'] = 'success! woot!';\nwp_safe_redirect('your_plugin_url');\n</code></pre>\n\n<p>Then in the page:</p>\n\n<pre><code>if (isset($_SESSION['painting_delete_msg'])) {\n echo $_SESSION['painting_delete_msg'];\n unset($_SESSION['painting_delete_msg']);\n}\n</code></pre>\n\n<p>The <code>unset</code> makes sure that the error is not repeated.</p>\n\n<h2>3. Don't use redirects.</h2>\n\n<pre><code> case \"delete\":\n ob_clean();\n ob_start();\n $status = Myplugin_Painting_Info::delete($request[\"painting_id\"]);\n include_once( \"partials/myplugin-admin-paintings.php\" );\n break;\n\n case \"show\":\n include_once( \"partials/myplugin-admin-paintings.php\" );\n break;\n\n\n// myplugin-admin-paintings.php\nif (isset($status)) {\n echo $status-&gt;message;\n}\n</code></pre>\n" }, { "answer_id": 332209, "author": "John Chandler", "author_id": 163544, "author_profile": "https://wordpress.stackexchange.com/users/163544", "pm_score": -1, "selected": false, "text": "<p>1) Add parameter (e.g. &amp;msg=xxxxxxxxxxxx) to the URL. Redirect to that. </p>\n\n<p>2) Place this in functions.php</p>\n\n<pre><code>if ($_GET['msg']) {\n wc_add_notice($_GET['msg'], 'notice' );\n}\n</code></pre>\n" } ]
2016/11/17
[ "https://wordpress.stackexchange.com/questions/246484", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107179/" ]
I am writing a plugin. When an item (painting) is clicked for deleting while a list of them is shown at the dashboard, I want to delete it and then redirect the user to the previous page shown. So the action "delete" is catched and then goto action "show" ``` public function display_paintings_page() { $request = $this->get_request(); switch ($request["action"]) { case "delete": ob_clean(); ob_start(); Myplugin_Painting_Info::delete($request["painting_id"]); wp_safe_redirect(wp_get_referer()); break; case "show": include_once( "partials/myplugin-admin-paintings.php" ); break; /* / ... */ } } ``` This is the best I could manage. But the action messages (error, success) from the "delete" method are not shown, as the output buffer has to be cleaned to prevent a "headers already sent" error. Is there any way to do this besides ajax or displaying an intermediate page with an "item removed; click to return"?
opinion: I like ajax interactions for things like this. DELETEs are cheap, fast things to accomplish server side, loading the whole page all over again takes too long. /opinion If you're going to use redirects and want to display error messages, you have a couple of options. 1. Use the redirect url itself to pass information to the next request. ----------------------------------------------------------------------- Something like this: ``` wp_safe_redirect('your_plugin_url?msg=' . $message_code); ``` In the view: ``` $messages = array( '1' => 'Success!', '2' => 'Something went wrong :(' ); $msg_id = isset($_GET['msg']) ? $_GET['err'] : 0; if (array_key_exists($msg_id, $messages)) { echo $messages[$msg_id]; } ``` 2. Use the $\_SESSION to pass around data. ------------------------------------------ Put `session_start()` somewhere in the early initialization of your plugin, to make sure it's run before any page output is sent. Then record the error or success messages in the session: ``` $_SESSION['painting_delete_msg'] = 'success! woot!'; wp_safe_redirect('your_plugin_url'); ``` Then in the page: ``` if (isset($_SESSION['painting_delete_msg'])) { echo $_SESSION['painting_delete_msg']; unset($_SESSION['painting_delete_msg']); } ``` The `unset` makes sure that the error is not repeated. 3. Don't use redirects. ----------------------- ``` case "delete": ob_clean(); ob_start(); $status = Myplugin_Painting_Info::delete($request["painting_id"]); include_once( "partials/myplugin-admin-paintings.php" ); break; case "show": include_once( "partials/myplugin-admin-paintings.php" ); break; // myplugin-admin-paintings.php if (isset($status)) { echo $status->message; } ```
246,497
<p>In my plugin, in <code>init</code> action I use <code>get_sites()</code> function... however it throws:</p> <p><code>Call to undefined function get_sites() in XYZ on line 154</code> whats solution? </p> <p>p.s.<br/> 1) The same happens with <code>wp_get_sites()</code>...<br/> 2) no help when I use <code>require_once(ABSPATH . 'wp-includes/ms-blogs.php');</code> <br/>3) I use wordpress version 4.6</p>
[ { "answer_id": 246499, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 1, "selected": false, "text": "<p>Solution seems to be:</p>\n\n<pre><code>if(function_exists('get_sites')) {$sites= get_sites();} \nelseif(function_exists('wp_get_sites')) {$sites= wp_get_sites();} \n</code></pre>\n" }, { "answer_id": 290159, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>The wp_get_sites function was deprecated in WP 4.6. The full answer is the first answer here: <a href=\"https://wordpress.stackexchange.com/questions/231114/sorting-list-of-sites-from-multisite-network-using-wp-get-sites/231121\">Sorting list of sites from multisite network using wp_get_sites</a> .</p>\n\n<p>Also, the function provided by Lance Cleveland (in the answers in the above link) provides a test for the proper function to use. But it is incomplete, as the old function is deprecated so the old function still exists if pre-4.6. The test should look for the WP version, not the existence of the function. (See my answer to the same question.)</p>\n\n<p>I have a plugin for multisites that looped through the sites. The pre-4.6 code was causing problems on 4.6+ site, so changed the plugin's requirements to require WP 4.6 or later. The plugin automatically deactivates with a message if pre-4.6 is found.</p>\n\n<p>That said, keeping WP updated is strongly recommended. There are security risks (and compatibility issues) with not doing updates. </p>\n" }, { "answer_id": 296740, "author": "Patrick", "author_id": 138613, "author_profile": "https://wordpress.stackexchange.com/users/138613", "pm_score": 0, "selected": false, "text": "<p>The <code>get_sites()</code> function (replacing the <code>wp_get_sites()</code> function, <a href=\"https://developer.wordpress.org/reference/functions/wp_get_sites/\" rel=\"nofollow noreferrer\">deprecated</a>) only works in a context of a <em>network of sites</em>.</p>\n\n<p>You can create a network by using the <em>multisite</em> feature, following <a href=\"https://codex.wordpress.org/Create_A_Network\" rel=\"nofollow noreferrer\">those instructions in the Codex</a>.</p>\n" } ]
2016/11/17
[ "https://wordpress.stackexchange.com/questions/246497", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33667/" ]
In my plugin, in `init` action I use `get_sites()` function... however it throws: `Call to undefined function get_sites() in XYZ on line 154` whats solution? p.s. 1) The same happens with `wp_get_sites()`... 2) no help when I use `require_once(ABSPATH . 'wp-includes/ms-blogs.php');` 3) I use wordpress version 4.6
Solution seems to be: ``` if(function_exists('get_sites')) {$sites= get_sites();} elseif(function_exists('wp_get_sites')) {$sites= wp_get_sites();} ```
246,502
<p>I'm building a WordPress site for a local newspaper. This newspaper currently has a "service directory" online which is a bunch of yellow-page style ads for different local businesses. Each of these ads is just a single image with a click-through, although there are two different sized ads (priced at different rates) that need to be displayed differently.</p> <p>The data schema would look something like this (just formatting in JSON for readability -- I know it'll be stored as SQL):</p> <pre><code>service_link: { image: 'plumberad01.png' url: 'http://myplumber.com', type: 'large', active: true } </code></pre> <p>I know I can create a new Page and manually add the images and their links, but management becomes a big hassle. What I want to do is create a custom page which just finds all the active service_links, and then formats them properly. I can easily write the PHP necessary to do that.</p> <p>What I'm not sure of is how to get the service_links added to the database. All my searches just keep coming up with information about custom post types, which doesn't seem to be what I'm looking for as these aren't individual posts. They will only ever be viewed along with everything else.</p> <p>My guess is I'd need to write a custom plugin (mainly so I can add the service_link management stuff to the menu in wp-admin), so I'm looking for a plugin doing something analogous or some kind of tutorial. I feel like this isn't an uncommon use-case (content that isn't a post), so I don't know why I'm having so much trouble finding information.</p>
[ { "answer_id": 246504, "author": "heller_benjamin", "author_id": 96964, "author_profile": "https://wordpress.stackexchange.com/users/96964", "pm_score": 0, "selected": false, "text": "<p>If I understand what you are looking for, the plug in,advance custom fields, should be useful. It allows you to create a page template that can include an image, text fields, etc, that can then be filled out for each page. See <a href=\"https://www.advancedcustomfields.com/\" rel=\"nofollow\">https://www.advancedcustomfields.com/</a></p>\n\n<p>It is easy to use and set up, with good documentation. You create your field and then simply call each field in your page template.</p>\n" }, { "answer_id": 246509, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": true, "text": "<p>From what you describe these ads are separate pieces of information which you want to order and display based on their properties. That would mean storing them as custom posts is still the way to go. After all, posts are the way WordPress stores chunks of related information. That doesn't mean they have to be displayed separately. <a href=\"https://codex.wordpress.org/Post_Types#Navigation_Menu\" rel=\"nofollow noreferrer\">Menus are also stored as a post type</a>, even if they are only included in templates that also include regular posts, and are handled in a completely different way.</p>\n\n<p>Now you have the separate ads in a post type, you can use <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\"><code>wp_query</code></a> to select them and display them in a template. Roughly, there are two ways to go. If you control the template, you can create widget areas in appropriate places and write a widget that displays the ads. If you don't control the template you can write a shortcode and include it in regular posts/pages.</p>\n\n<p>You would assemble all code (custom post type and widget/shortcode) in a plugin. The benefit of doing it this way would be flexibility for future developments. You could, for instance, place individual ads on content pages, if you would choose to do so.</p>\n" } ]
2016/11/17
[ "https://wordpress.stackexchange.com/questions/246502", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107187/" ]
I'm building a WordPress site for a local newspaper. This newspaper currently has a "service directory" online which is a bunch of yellow-page style ads for different local businesses. Each of these ads is just a single image with a click-through, although there are two different sized ads (priced at different rates) that need to be displayed differently. The data schema would look something like this (just formatting in JSON for readability -- I know it'll be stored as SQL): ``` service_link: { image: 'plumberad01.png' url: 'http://myplumber.com', type: 'large', active: true } ``` I know I can create a new Page and manually add the images and their links, but management becomes a big hassle. What I want to do is create a custom page which just finds all the active service\_links, and then formats them properly. I can easily write the PHP necessary to do that. What I'm not sure of is how to get the service\_links added to the database. All my searches just keep coming up with information about custom post types, which doesn't seem to be what I'm looking for as these aren't individual posts. They will only ever be viewed along with everything else. My guess is I'd need to write a custom plugin (mainly so I can add the service\_link management stuff to the menu in wp-admin), so I'm looking for a plugin doing something analogous or some kind of tutorial. I feel like this isn't an uncommon use-case (content that isn't a post), so I don't know why I'm having so much trouble finding information.
From what you describe these ads are separate pieces of information which you want to order and display based on their properties. That would mean storing them as custom posts is still the way to go. After all, posts are the way WordPress stores chunks of related information. That doesn't mean they have to be displayed separately. [Menus are also stored as a post type](https://codex.wordpress.org/Post_Types#Navigation_Menu), even if they are only included in templates that also include regular posts, and are handled in a completely different way. Now you have the separate ads in a post type, you can use [`wp_query`](https://codex.wordpress.org/Class_Reference/WP_Query) to select them and display them in a template. Roughly, there are two ways to go. If you control the template, you can create widget areas in appropriate places and write a widget that displays the ads. If you don't control the template you can write a shortcode and include it in regular posts/pages. You would assemble all code (custom post type and widget/shortcode) in a plugin. The benefit of doing it this way would be flexibility for future developments. You could, for instance, place individual ads on content pages, if you would choose to do so.
246,503
<p>I'm having a problem with WPDB->insert inserting special characters.</p> <p>I'm trying to insert a name (Jiří), the ř is being saved as ?.</p> <p>The character is being able to inserted correctly into the database using <code>add_option</code>, which is strange.</p> <p>Here is a version of the code which I'm trying:-</p> <pre><code>$memberdata = array( 'name' =&gt; 'Jiří', 'email' =&gt; '[email protected]' ); add_option( 'temp_debug', $member_data['name'] ); // inserted as Jiří $insert_into_temp=$wpdb-&gt;insert( wp_table, $member_data, array( '%s', '%s' ); // inserted as Ji?i </code></pre> <p>Any ideas?</p>
[ { "answer_id": 246507, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": false, "text": "<p>If the same code works with <code>add_option()</code> and not with <code>$wpdb-&gt;insert()</code> in a custom table, it is probably because the collation of the custom table does not support the characters of the inserted data.</p>\n\n<p>It shoulud work if you set the collation of your table to UTF-8, <code>utf8_general_ci</code> at minimum (to allow support for emojis, <a href=\"https://make.wordpress.org/core/2015/04/02/the-utf8mb4-upgrade/\" rel=\"nofollow noreferrer\">WordPress uses <code>utf8mb4_unicode_ci</code> since version 4.2</a>).</p>\n" }, { "answer_id": 246649, "author": "Rhys Wynne", "author_id": 9918, "author_profile": "https://wordpress.stackexchange.com/users/9918", "pm_score": 0, "selected": false, "text": "<p>Thanks to @kovshenin &amp; @cybmeta above for putting me on the right lines :)</p>\n\n<p>Although the tables were using <code>utf8mb4_unicode_ci</code>, the individual rows used <code>latin1_swedish_ci</code>. </p>\n\n<p>Switching the rows to <code>utf8mb4_unicode_ci</code>, fixed this issue.</p>\n\n<p>Thanks!</p>\n" } ]
2016/11/17
[ "https://wordpress.stackexchange.com/questions/246503", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9918/" ]
I'm having a problem with WPDB->insert inserting special characters. I'm trying to insert a name (Jiří), the ř is being saved as ?. The character is being able to inserted correctly into the database using `add_option`, which is strange. Here is a version of the code which I'm trying:- ``` $memberdata = array( 'name' => 'Jiří', 'email' => '[email protected]' ); add_option( 'temp_debug', $member_data['name'] ); // inserted as Jiří $insert_into_temp=$wpdb->insert( wp_table, $member_data, array( '%s', '%s' ); // inserted as Ji?i ``` Any ideas?
If the same code works with `add_option()` and not with `$wpdb->insert()` in a custom table, it is probably because the collation of the custom table does not support the characters of the inserted data. It shoulud work if you set the collation of your table to UTF-8, `utf8_general_ci` at minimum (to allow support for emojis, [WordPress uses `utf8mb4_unicode_ci` since version 4.2](https://make.wordpress.org/core/2015/04/02/the-utf8mb4-upgrade/)).
246,510
<p>I am using a php plugin to insert php in my code.</p> <p>I have a form and I want to make it disappears once it is submitted, but even the most simple condition I am trying to make is not working (he always prints the header):</p> <pre><code>[insert_php] echo $_REQUEST['code']; if ($_REQUEST['code'] == 'aba'){ [/insert_php] &lt;h2&gt;HEADER&lt;/h2&gt; [insert_php] } [/insert_php] </code></pre> <p>The php is working normally because if I change it a little it prints what I want:</p> <pre><code> [insert_php] echo $_REQUEST['code']; if ($_REQUEST['code'] == 'aba'){ echo 'example phrase' } [/insert_php] </code></pre> <p>There is anything I am missing ?</p>
[ { "answer_id": 246512, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>I wouldn't recommend writing PHP code in the content this way, e.g. for security reasons.</p>\n\n<p>Most likely the shortcode is using <code>eval()</code> and you need a valid PHP code snippet in each such call.</p>\n\n<p>The PHP documentation has this <a href=\"http://php.net/manual/en/function.eval.php\" rel=\"nofollow noreferrer\">warning</a>:</p>\n\n<blockquote>\n <p><strong>Caution</strong> The <code>eval()</code> language construct is very dangerous because it\n allows execution of arbitrary PHP code. Its use thus is discouraged.\n If you have carefully verified that there is no other option than to\n use this construct, pay special attention not to pass any user\n provided data into it without properly validating it beforehand.</p>\n</blockquote>\n\n<p>You should consider writing your own <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">shortcode</a> instead, keeping the PHP code away from the users and the content editor.</p>\n" }, { "answer_id": 246548, "author": "tanhernandez", "author_id": 87620, "author_profile": "https://wordpress.stackexchange.com/users/87620", "pm_score": 0, "selected": false, "text": "<p>I assume your GET-ting/POST-ting on the same page? (Due to the use of $_REQUEST).</p>\n\n<p>But anyway, you might need to create your own shortcode for your custom content, here is an example to help you get started.</p>\n\n<p>You can paste it in your theme's functions.php</p>\n\n<pre><code>// Attach callback method to the wordpress hook \nadd_shortcode('my_shortcode', 'unique_key_my_shortcode');\n\n// Define the callback\nfunction unique_key_my_shortcode() {\n\n $code = $_REQUEST['code'];\n\n // Catch echoed values\n ob_start();\n ?&gt;\n &lt;!-- Create DIV container, just in case --&gt;\n &lt;div class=\"my_shortcode_container\"&gt;\n\n &lt;!-- Just like in your sample code --&gt;\n &lt;?php echo $code; ?&gt;\n\n &lt;!-- If code == 'aba' then include the html below --&gt;\n &lt;?php if ($code == 'aba'): ?&gt;\n\n &lt;h2&gt;Code is equal to \"aba\"&lt;/h2&gt;\n\n &lt;?php endif; ?&gt;\n &lt;/div&gt;\n\n &lt;?php\n\n // Store the html in a variable\n $html = ob_get_contents();\n\n // Clean\n ob_end_clean();\n\n // return\n return $html;\n}\n</code></pre>\n\n<p>and then place the shortcode in a text widget or something as <strong>[my_shortcode]</strong></p>\n" }, { "answer_id": 246612, "author": "hashtagerrors", "author_id": 102412, "author_profile": "https://wordpress.stackexchange.com/users/102412", "pm_score": 0, "selected": false, "text": "<p>The best way you could do it is:</p>\n\n<pre><code>[insert_php]\n echo $_REQUEST['code'];\n if ($_REQUEST['code'] == 'aba'){\n\n echo $header = '&lt;h2&gt;HEADER&lt;/h2&gt;';\n\n }\n[/insert_php]\n</code></pre>\n\n<p>or if you have lot of HTML code you can use concatenation. For ex:</p>\n\n<pre><code>[insert_php]\n echo $_REQUEST['code'];\n if ($_REQUEST['code'] == 'aba'){\n\n $header='&lt;h1&gt;';\n $header.='Header';\n $header.='&lt;/h1&gt;';\n echo $header;\n\n }\n[/insert_php]\n</code></pre>\n" }, { "answer_id": 246622, "author": "Victor Casado", "author_id": 107268, "author_profile": "https://wordpress.stackexchange.com/users/107268", "pm_score": 0, "selected": false, "text": "<p>I think the most useful answer is the one provided by tan05. And the simplest but useful the answer from nitingsingh.</p>\n\n<p>Here is another one, a different (and worse than the shortcode solution). Use alternate syntax.</p>\n\n<p>Try with:</p>\n\n<pre><code>[insert_php]\n echo $_REQUEST['code'];\n if ($_REQUEST['code'] == 'aba'):\n[/insert_php]\n\n&lt;h2&gt;HEADER&lt;/h2&gt;\n\n[insert_php] \n endif;\n[/insert_php]\n</code></pre>\n\n<p>Note that instead of using:</p>\n\n<pre><code>if(condition){\n do_something\n}\n</code></pre>\n\n<p>You can use:</p>\n\n<pre><code>if(condition): \n do_domething\nendif;\n</code></pre>\n\n<p>Check out <a href=\"http://php.net/manual/en/control-structures.elseif.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/control-structures.elseif.php</a></p>\n" } ]
2016/11/17
[ "https://wordpress.stackexchange.com/questions/246510", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106943/" ]
I am using a php plugin to insert php in my code. I have a form and I want to make it disappears once it is submitted, but even the most simple condition I am trying to make is not working (he always prints the header): ``` [insert_php] echo $_REQUEST['code']; if ($_REQUEST['code'] == 'aba'){ [/insert_php] <h2>HEADER</h2> [insert_php] } [/insert_php] ``` The php is working normally because if I change it a little it prints what I want: ``` [insert_php] echo $_REQUEST['code']; if ($_REQUEST['code'] == 'aba'){ echo 'example phrase' } [/insert_php] ``` There is anything I am missing ?
I wouldn't recommend writing PHP code in the content this way, e.g. for security reasons. Most likely the shortcode is using `eval()` and you need a valid PHP code snippet in each such call. The PHP documentation has this [warning](http://php.net/manual/en/function.eval.php): > > **Caution** The `eval()` language construct is very dangerous because it > allows execution of arbitrary PHP code. Its use thus is discouraged. > If you have carefully verified that there is no other option than to > use this construct, pay special attention not to pass any user > provided data into it without properly validating it beforehand. > > > You should consider writing your own [shortcode](https://codex.wordpress.org/Shortcode_API) instead, keeping the PHP code away from the users and the content editor.
246,547
<p>I have a page template, which is working nicely. But when I include , it loads the themes CSS and js files, which breaks my page template.</p> <p>However, I still need the wp_head for some plugins to work.</p> <p>Is there a way to stop wp_head from loading any of my theme's CSS &amp; js files? </p> <p>I want the page template to only use its own CSS + js.</p>
[ { "answer_id": 246557, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 0, "selected": false, "text": "<p>There is no clear way to reliably do that (sans hacky approaches like buffering page output).</p>\n\n<p><em>Assuming</em> that everything only ever uses proper WP APIs to queue you could de–queue all resources. A little more harsh way would be to unhook <code>wp_print_styles()</code>, <code>wp_print_scripts()</code>, and <code>wp_print_footer_scrtipts()</code>.</p>\n\n<p>In a nutshell there is no easy way to do this thoroughly and cleanly. You either do something drastic like removing head/footer hooks altogether or you have to micromanage it script by script.</p>\n" }, { "answer_id": 246568, "author": "Megan Rose", "author_id": 84643, "author_profile": "https://wordpress.stackexchange.com/users/84643", "pm_score": 0, "selected": false, "text": "<p>It depends on if the theme is using enqueued scripts/styles or if they're hard coded in the header.</p>\n\n<p>If the CSS &amp; JS are enqueued, you can dequeue them in the specified template:</p>\n\n<pre><code>function wpse_246547_deregister() {\n if ( is_page_template('YOUR-TEMPLATE.php') ) {\n wp_dequeue_script( 'name-of-script' );\n wp_deregister_script( 'name-of-script' );\n wp_dequeue_style( 'name-of-stylesheet' );\n wp_deregister_style( 'name-of-stylesheet' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_246547_deregister', 100 );\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_dequeue_script\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_dequeue_script</a>\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_dequeue_style\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_dequeue_style</a></p>\n\n<p>If the CSS &amp; JS references are hard-coded in the header.php file, you can specify in your template to use a different header file (in this example, it would look for <code>header-alt.php</code>):</p>\n\n<pre><code>get_header( 'alt' );\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_header#Multiple_Headers\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_header#Multiple_Headers</a></p>\n" }, { "answer_id": 246586, "author": "Heinrich Held", "author_id": 107225, "author_profile": "https://wordpress.stackexchange.com/users/107225", "pm_score": 2, "selected": false, "text": "<p>Thank you for your help! This solution works with my theme:</p>\n\n<pre><code>function remove_all_theme_styles() {\nif ( is_page_template('template-landing.php') ) {\n global $wp_styles;\n $wp_styles-&gt;queue = array();\n}\n}\nadd_action('wp_print_styles', 'remove_all_theme_styles', 100);\n</code></pre>\n" }, { "answer_id": 366860, "author": "Ahmer Wpcoder110", "author_id": 180018, "author_profile": "https://wordpress.stackexchange.com/users/180018", "pm_score": 1, "selected": false, "text": "<p>I modified Heinrich Held answer so this will help new people who are looking to remove, deque and de register theme styles and scripts. The following function will remove all the styles registered.</p>\n<pre><code>\nfunction remove_all_theme_styles() {\n if ( is_page_template('trading-dashboard.php') ) {\n global $wp_styles,$wp_scripts;\n foreach( $wp_styles-&gt;queue as $style ) :\n $handle = $wp_styles-&gt;registered[$style]-&gt;handle;\n wp_deregister_style($handle);\n wp_dequeue_style($handle);\n endforeach; \n foreach( $wp_scripts-&gt;queue as $script ) :\n $handle = $wp_scripts-&gt;registered[$script]-&gt;handle;\n wp_dequeue_script($handle);\n wp_deregister_script($handle);\n endforeach;\n }\n }\nadd_action( 'wp_enqueue_scripts', 'remove_all_theme_styles', 100 );\n</code></pre>\n<p>But let's say you don't want to remove your custom style or script then do something like this</p>\n<pre><code>\nfunction remove_all_theme_styles() {\n if ( is_page_template('trading-dashboard.php') ) {\n global $wp_styles,$wp_scripts;\n foreach( $wp_styles-&gt;queue as $style ) :\n if ($wp_styles-&gt;registered[$style]-&gt;handle != 'my-custom-style') {\n $handle = $wp_styles-&gt;registered[$style]-&gt;handle;\n wp_deregister_style($handle);\n wp_dequeue_style($handle);\n }\n endforeach;\n foreach( $wp_scripts-&gt;queue as $script ) :\n if ($wp_scripts-&gt;registered[$script]-&gt;handle != 'my-custom-script') {\n $handle = $wp_scripts-&gt;registered[$script]-&gt;handle;\n wp_dequeue_script($handle);\n wp_deregister_script($handle);\n }\n endforeach;\n }\n }\nadd_action( 'wp_enqueue_scripts', 'remove_all_theme_styles', 100 );\n</code></pre>\n<p>Hope this will help someone!</p>\n" } ]
2016/11/17
[ "https://wordpress.stackexchange.com/questions/246547", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107225/" ]
I have a page template, which is working nicely. But when I include , it loads the themes CSS and js files, which breaks my page template. However, I still need the wp\_head for some plugins to work. Is there a way to stop wp\_head from loading any of my theme's CSS & js files? I want the page template to only use its own CSS + js.
Thank you for your help! This solution works with my theme: ``` function remove_all_theme_styles() { if ( is_page_template('template-landing.php') ) { global $wp_styles; $wp_styles->queue = array(); } } add_action('wp_print_styles', 'remove_all_theme_styles', 100); ```
246,551
<p>I don't think this is the most elegant way of achieving my objective but it's 95% there.</p> <p>I have created a page template and added a post loop to list custom posts based on the a custom field set on the page.</p> <p>I am trying to show a list of associated posts. I have a custom taxonomy 'servicestax' containing values such as 'design' and 'support' I want to show the posts for my custom post type 'Services' with a link to the post.</p> <p>The issue i face is the permalink is output as the current page url and not a post url from the list of custom posts. I don't really understand why this should be as the thumbnail, title and excerpt all appear as expected.</p> <p>The code I have cobbled together is as follows (I have added too much error checking yet!)</p> <pre><code> $key_value = get_field('post_types' ); $custom_terms = get_terms('servicestax'); foreach($custom_terms as $custom_term) { wp_reset_query(); $args = array('post_type' =&gt; 'services', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'servicestax', 'field' =&gt; 'slug', 'terms' =&gt; $custom_term-&gt;slug, ), ), ); if (! empty($key_value)){ if ($custom_term-&gt;slug == $key_value-&gt;slug){ $loop = new WP_Query($args); if($loop-&gt;have_posts()) { while($loop-&gt;have_posts()) : $loop-&gt;the_post(); ?&gt; &lt;div class="listing col-md-8"&gt; &lt;h3&gt;&lt;a href="&lt;?php get_post_permalink()?&gt;"&gt;&lt;?php the_title()?&gt; &lt;/a&gt;&lt;/h3&gt; &lt;div class="col-md-3 col-sm-3 hidden-xs"&gt;&lt;img class=" hidden-xs" src=" &lt;?php the_post_thumbnail_url( 'thumbnail' )?&gt;"/&gt;&lt;/div&gt; &lt;div class="col-md-9 col-sm-9"&gt; &lt;?php the_excerpt() ?&gt; &lt;a href="&lt;?php get_post_permalink()?&gt;"&gt;more information&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; } } } } </code></pre>
[ { "answer_id": 246557, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 0, "selected": false, "text": "<p>There is no clear way to reliably do that (sans hacky approaches like buffering page output).</p>\n\n<p><em>Assuming</em> that everything only ever uses proper WP APIs to queue you could de–queue all resources. A little more harsh way would be to unhook <code>wp_print_styles()</code>, <code>wp_print_scripts()</code>, and <code>wp_print_footer_scrtipts()</code>.</p>\n\n<p>In a nutshell there is no easy way to do this thoroughly and cleanly. You either do something drastic like removing head/footer hooks altogether or you have to micromanage it script by script.</p>\n" }, { "answer_id": 246568, "author": "Megan Rose", "author_id": 84643, "author_profile": "https://wordpress.stackexchange.com/users/84643", "pm_score": 0, "selected": false, "text": "<p>It depends on if the theme is using enqueued scripts/styles or if they're hard coded in the header.</p>\n\n<p>If the CSS &amp; JS are enqueued, you can dequeue them in the specified template:</p>\n\n<pre><code>function wpse_246547_deregister() {\n if ( is_page_template('YOUR-TEMPLATE.php') ) {\n wp_dequeue_script( 'name-of-script' );\n wp_deregister_script( 'name-of-script' );\n wp_dequeue_style( 'name-of-stylesheet' );\n wp_deregister_style( 'name-of-stylesheet' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_246547_deregister', 100 );\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_dequeue_script\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_dequeue_script</a>\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_dequeue_style\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_dequeue_style</a></p>\n\n<p>If the CSS &amp; JS references are hard-coded in the header.php file, you can specify in your template to use a different header file (in this example, it would look for <code>header-alt.php</code>):</p>\n\n<pre><code>get_header( 'alt' );\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_header#Multiple_Headers\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_header#Multiple_Headers</a></p>\n" }, { "answer_id": 246586, "author": "Heinrich Held", "author_id": 107225, "author_profile": "https://wordpress.stackexchange.com/users/107225", "pm_score": 2, "selected": false, "text": "<p>Thank you for your help! This solution works with my theme:</p>\n\n<pre><code>function remove_all_theme_styles() {\nif ( is_page_template('template-landing.php') ) {\n global $wp_styles;\n $wp_styles-&gt;queue = array();\n}\n}\nadd_action('wp_print_styles', 'remove_all_theme_styles', 100);\n</code></pre>\n" }, { "answer_id": 366860, "author": "Ahmer Wpcoder110", "author_id": 180018, "author_profile": "https://wordpress.stackexchange.com/users/180018", "pm_score": 1, "selected": false, "text": "<p>I modified Heinrich Held answer so this will help new people who are looking to remove, deque and de register theme styles and scripts. The following function will remove all the styles registered.</p>\n<pre><code>\nfunction remove_all_theme_styles() {\n if ( is_page_template('trading-dashboard.php') ) {\n global $wp_styles,$wp_scripts;\n foreach( $wp_styles-&gt;queue as $style ) :\n $handle = $wp_styles-&gt;registered[$style]-&gt;handle;\n wp_deregister_style($handle);\n wp_dequeue_style($handle);\n endforeach; \n foreach( $wp_scripts-&gt;queue as $script ) :\n $handle = $wp_scripts-&gt;registered[$script]-&gt;handle;\n wp_dequeue_script($handle);\n wp_deregister_script($handle);\n endforeach;\n }\n }\nadd_action( 'wp_enqueue_scripts', 'remove_all_theme_styles', 100 );\n</code></pre>\n<p>But let's say you don't want to remove your custom style or script then do something like this</p>\n<pre><code>\nfunction remove_all_theme_styles() {\n if ( is_page_template('trading-dashboard.php') ) {\n global $wp_styles,$wp_scripts;\n foreach( $wp_styles-&gt;queue as $style ) :\n if ($wp_styles-&gt;registered[$style]-&gt;handle != 'my-custom-style') {\n $handle = $wp_styles-&gt;registered[$style]-&gt;handle;\n wp_deregister_style($handle);\n wp_dequeue_style($handle);\n }\n endforeach;\n foreach( $wp_scripts-&gt;queue as $script ) :\n if ($wp_scripts-&gt;registered[$script]-&gt;handle != 'my-custom-script') {\n $handle = $wp_scripts-&gt;registered[$script]-&gt;handle;\n wp_dequeue_script($handle);\n wp_deregister_script($handle);\n }\n endforeach;\n }\n }\nadd_action( 'wp_enqueue_scripts', 'remove_all_theme_styles', 100 );\n</code></pre>\n<p>Hope this will help someone!</p>\n" } ]
2016/11/17
[ "https://wordpress.stackexchange.com/questions/246551", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107221/" ]
I don't think this is the most elegant way of achieving my objective but it's 95% there. I have created a page template and added a post loop to list custom posts based on the a custom field set on the page. I am trying to show a list of associated posts. I have a custom taxonomy 'servicestax' containing values such as 'design' and 'support' I want to show the posts for my custom post type 'Services' with a link to the post. The issue i face is the permalink is output as the current page url and not a post url from the list of custom posts. I don't really understand why this should be as the thumbnail, title and excerpt all appear as expected. The code I have cobbled together is as follows (I have added too much error checking yet!) ``` $key_value = get_field('post_types' ); $custom_terms = get_terms('servicestax'); foreach($custom_terms as $custom_term) { wp_reset_query(); $args = array('post_type' => 'services', 'tax_query' => array( array( 'taxonomy' => 'servicestax', 'field' => 'slug', 'terms' => $custom_term->slug, ), ), ); if (! empty($key_value)){ if ($custom_term->slug == $key_value->slug){ $loop = new WP_Query($args); if($loop->have_posts()) { while($loop->have_posts()) : $loop->the_post(); ?> <div class="listing col-md-8"> <h3><a href="<?php get_post_permalink()?>"><?php the_title()?> </a></h3> <div class="col-md-3 col-sm-3 hidden-xs"><img class=" hidden-xs" src=" <?php the_post_thumbnail_url( 'thumbnail' )?>"/></div> <div class="col-md-9 col-sm-9"> <?php the_excerpt() ?> <a href="<?php get_post_permalink()?>">more information</a> </div> </div> <?php endwhile; } } } } ```
Thank you for your help! This solution works with my theme: ``` function remove_all_theme_styles() { if ( is_page_template('template-landing.php') ) { global $wp_styles; $wp_styles->queue = array(); } } add_action('wp_print_styles', 'remove_all_theme_styles', 100); ```
246,563
<p>I've read the documentation on <a href="https://developer.wordpress.org/reference/functions/get_post_permalink/" rel="noreferrer"><code>get_post_permalink()</code></a> and <a href="https://developer.wordpress.org/reference/functions/get_permalink/" rel="noreferrer"><code>get_permalink()</code></a> and don't understand the difference between the two. It might be because I don't understand the purpose of the <code>$leavename</code> and <code>$sample</code> parameters. Can anyone explain those, and when one function would be more useful than the other? Thanks!</p>
[ { "answer_id": 246583, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 2, "selected": false, "text": "<p>Someone else will certainly explain better than me. As I only use <code>get_permalink()</code></p>\n\n<p>They are mostly similar as they both return the post permalink, <code>get_permalink</code> use <code>get_post_permalink</code> (for post_types) and can be filter. It will also be use to retrieve a page link, attachment... where <code>get_post_permalink</code> seems to be dedicated to post_types. </p>\n\n<p>EDIT:</p>\n\n<p>About the use of <code>$leavename</code>, it's look like there is no need for a front-end (and even in the back-end) use as it return the permastructure slug, according to the post type of the link.</p>\n\n<pre><code> echo get_permalink(123, true);\n</code></pre>\n\n<p>Return the rewrite schema for the link, that could be use </p>\n\n<p>A post:</p>\n\n<pre><code> http://example.com/%postname%/\n</code></pre>\n\n<p>A product:</p>\n\n<pre><code> http://example.com/%product%/\n</code></pre>\n\n<p>$leavename is use in the get_permalink() in the $rewritecode array and put as first paramater in the function line 221</p>\n\n<pre><code>$permalink = home_url( str_replace($rewritecode, $rewritereplace, $permalink) );\n</code></pre>\n\n<p>It can be usefull to discover the rewrite slug for a link for a developper (but I think there a better way to do this)</p>\n\n<p>Hope someone will give more details.</p>\n" }, { "answer_id": 247071, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"https://developer.wordpress.org/reference/functions/get_post_permalink/\" rel=\"noreferrer\"><code>get_post_permalink()</code></a> funciton fetches the link to a post depending on its \"permanent\" link plus your custom rewrite rules that changes <code>?p=123</code> into for e.g. <code>my-beautiful-sunday-diary</code>. The <a href=\"https://developer.wordpress.org/reference/functions/get_permalink/\" rel=\"noreferrer\"><code>get_permalink()</code></a> function is more \"basic\" but as well more versatile in what it does: For a <code>post_type</code> of </p>\n\n<ul>\n<li><code>page</code>, it uses <code>get_page_link()</code></li>\n<li><code>attachment</code>, it uses <code>get_attachment_link()</code></li>\n<li><code>post</code>, it uses <code>get_post_link()</code></li>\n</ul>\n\n<p>It also handles the display of <code>term</code>s like <code>category</code> and date permalinks. At the end, it either replaces the \"pretty\" link in your <code>home_url()</code> or just returns the raw link if no custom rewrite rules were assigned. Finally it attaches a generic filter:</p>\n\n<pre><code>/**\n * Filters the permalink for a post.\n *\n * Only applies to posts with post_type of 'post'.\n *\n * @since 1.5.0\n *\n * @param string $permalink The post's permalink.\n * @param WP_Post $post The post in question.\n * @param bool $leavename Whether to keep the post name.\n */\nreturn apply_filters( 'post_link', $permalink, $post, $leavename );\n</code></pre>\n\n<p>Hope that clarifies the topic.</p>\n\n<p>ProTip: If you need to change peramlinks in a plugin, go with the specific filters inside <code>get_attachment_link()</code>, <code>get_post_link()</code>, etc. Only if you are either working on a single site and are not planning to distribute your code or if you are writing a plugin targetting only rewrite stuff, then go with the generic filter above. Else you will nuke every theme authors efforts and start a callback priority race.</p>\n" } ]
2016/11/17
[ "https://wordpress.stackexchange.com/questions/246563", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16/" ]
I've read the documentation on [`get_post_permalink()`](https://developer.wordpress.org/reference/functions/get_post_permalink/) and [`get_permalink()`](https://developer.wordpress.org/reference/functions/get_permalink/) and don't understand the difference between the two. It might be because I don't understand the purpose of the `$leavename` and `$sample` parameters. Can anyone explain those, and when one function would be more useful than the other? Thanks!
The [`get_post_permalink()`](https://developer.wordpress.org/reference/functions/get_post_permalink/) funciton fetches the link to a post depending on its "permanent" link plus your custom rewrite rules that changes `?p=123` into for e.g. `my-beautiful-sunday-diary`. The [`get_permalink()`](https://developer.wordpress.org/reference/functions/get_permalink/) function is more "basic" but as well more versatile in what it does: For a `post_type` of * `page`, it uses `get_page_link()` * `attachment`, it uses `get_attachment_link()` * `post`, it uses `get_post_link()` It also handles the display of `term`s like `category` and date permalinks. At the end, it either replaces the "pretty" link in your `home_url()` or just returns the raw link if no custom rewrite rules were assigned. Finally it attaches a generic filter: ``` /** * Filters the permalink for a post. * * Only applies to posts with post_type of 'post'. * * @since 1.5.0 * * @param string $permalink The post's permalink. * @param WP_Post $post The post in question. * @param bool $leavename Whether to keep the post name. */ return apply_filters( 'post_link', $permalink, $post, $leavename ); ``` Hope that clarifies the topic. ProTip: If you need to change peramlinks in a plugin, go with the specific filters inside `get_attachment_link()`, `get_post_link()`, etc. Only if you are either working on a single site and are not planning to distribute your code or if you are writing a plugin targetting only rewrite stuff, then go with the generic filter above. Else you will nuke every theme authors efforts and start a callback priority race.
246,613
<p>I have a Wordpress site that accepts posts by email and feeds them into specific categories. I just adopted a new theme (Astrid) and while I've been able to customize it with css and child theme, I'm frustrated by the fact that the sidebar is ever present in the category/archive view. Is there a way (perhaps using category.php) to remove the sidebar from all category pages (which for my site would mean all pages except one static "about" page and the homepage itself which shows most recent blog posts).</p> <p>Thanks much!</p>
[ { "answer_id": 246615, "author": "Ranuka", "author_id": 106350, "author_profile": "https://wordpress.stackexchange.com/users/106350", "pm_score": 0, "selected": false, "text": "<p>This solution depend on the theme. Sometimes this solution does not work for your theme.</p>\n\n<ol>\n<li><p>Go to category.php page.</p></li>\n<li><p>Find <code>get_sidebar</code> function.</p></li>\n<li><p>Remove the <code>get_sidebar</code> function including parameters if there.</p></li>\n</ol>\n\n<p>You may need to change some css part also. And if you are not using child theme your customization will be lost when updating the theme. </p>\n" }, { "answer_id": 246616, "author": "Etherplain", "author_id": 107235, "author_profile": "https://wordpress.stackexchange.com/users/107235", "pm_score": 0, "selected": false, "text": "<p>So, in the same way you might go to the store and you can't find that one item your shopping for, then break down and ask someone only to learn it's right behind you.... I figured this out. I cheated, but I found that if you just copy the full width page template into category.php (which I had to create) and just change one line of code, it does the job. Here's the full php if it helps anyone.</p>\n\n<pre><code> &lt;?php\n\n/*\n\nTemplate Name: Full width\n\n*/\n get_header();\n?&gt;\n\n\n\n &lt;div id=\"primary\" class=\"content-area fullwidth\"&gt;\n &lt;main id=\"main\" class=\"site-main\" role=\"main\"&gt;\n\n &lt;?php while ( have_posts() ) : the_post(); ?&gt;\n\n &lt;?php get_template_part( 'template-parts/content', 'page' ); ?&gt;\n\n &lt;?php\n\n if ( comments_open() || '0' != get_comments_number() ) :\n\n comments_template();\n\n endif;\n ?&gt;\n\n &lt;?php endwhile; // end of the loop. ?&gt;\n\n\n &lt;/main&gt;&lt;!-- #main --&gt;\n &lt;/div&gt;&lt;!-- #primary --&gt;\n\n&lt;?php get_footer(); ?&gt;\n</code></pre>\n\n<p>Only thing you need to change is here. Change page to category: </p>\n\n<pre><code>&lt;?php get_template_part( 'template-parts/content', 'category' ); ?&gt;\n</code></pre>\n\n<p>That said, I'm sure there's an easier way to address this problem. One way may be to display categories on a specific page (where the theme's page templates will come into play), instead of redirecting to the category like I do.</p>\n" }, { "answer_id": 282733, "author": "Steven Johnson", "author_id": 129400, "author_profile": "https://wordpress.stackexchange.com/users/129400", "pm_score": 0, "selected": false, "text": "<p>Your provided example only works because the new template that you've created is hooked to content-category.php, which doesn't exist by default within the Astrid Theme.</p>\n\n<p>I've only taken a brief scan of the code for Astrid, but it looks like there's only a single sidebar that's called -- located in <strong>index.php</strong>.</p>\n\n<p>If you're trying to avoid the sidebar on specifically your <em>Archives</em> and <em>Categories</em> pages, open index.php and you should see the following:</p>\n\n<pre><code>&lt;?php\n/**\n* The main template file.\n*\n* This is the most generic template file in a WordPress theme\n* and one of the two required files for a theme (the other being style.css).\n* It is used to display a page when nothing more specific matches a query.\n* E.g., it puts together the home page when no home.php file exists.\n*\n* @link https://codex.wordpress.org/Template_Hierarchy\n*\n* @package Astrid\n*/\n\nget_header(); ?&gt;\n\n&lt;div id=\"primary\" class=\"content-area\"&gt;\n &lt;main id=\"main\" class=\"site-main\" role=\"main\"&gt;\n\n &lt;?php\n if ( have_posts() ) :\n\n if ( is_home() &amp;&amp; ! is_front_page() ) : ?&gt;\n &lt;header&gt;\n &lt;h1 class=\"page-title screen-reader-text\"&gt;&lt;?php single_post_title(); ?&gt;&lt;/h1&gt;\n &lt;/header&gt;\n\n &lt;?php\n endif;\n\n /* Start the Loop */\n while ( have_posts() ) : the_post();\n\n /*\n * Include the Post-Format-specific template for the content.\n * If you want to override this in a child theme, then include a file\n * called content-___.php (where ___ is the Post Format name) and that will be used instead.\n */\n get_template_part( 'template-parts/content', get_post_format() );\n\n endwhile;\n\n the_posts_navigation();\n\n else :\n\n get_template_part( 'template-parts/content', 'none' );\n\n endif; ?&gt;\n\n &lt;/main&gt;&lt;!-- #main --&gt;\n&lt;/div&gt;&lt;!-- #primary --&gt;\n\n&lt;?php\nget_sidebar();\nget_footer();\n</code></pre>\n\n<p>At the bottom of index.php, <strong>get_sidebar();</strong> is called with no condition as to when. </p>\n\n<p>If I understand your question correctly, the simplest resolution would be to wrap the <em>get_sidebar()</em> method in a conditional statement as follows:</p>\n\n<pre><code> if( !is_category() &amp;&amp; !is_archive() ) {\n get_sidebar();\n}\n</code></pre>\n" }, { "answer_id": 288967, "author": "Jignesh Patel", "author_id": 111556, "author_profile": "https://wordpress.stackexchange.com/users/111556", "pm_score": 1, "selected": false, "text": "<p>category page flow (bottom to top) is like this:</p>\n\n<pre><code>category-slug.php\ncategory-ID.php\ncategory.php\narchive.php\nindex.php\n</code></pre>\n\n<p>so you can not create compulsory <strong>category.php</strong>. open your current theme <strong>archive.php</strong>. and edit this code.</p>\n\n<pre><code>&lt;?php \n if( !is_category() ){\n get_sidebar();\n }\n?&gt;\n</code></pre>\n" } ]
2016/11/18
[ "https://wordpress.stackexchange.com/questions/246613", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107235/" ]
I have a Wordpress site that accepts posts by email and feeds them into specific categories. I just adopted a new theme (Astrid) and while I've been able to customize it with css and child theme, I'm frustrated by the fact that the sidebar is ever present in the category/archive view. Is there a way (perhaps using category.php) to remove the sidebar from all category pages (which for my site would mean all pages except one static "about" page and the homepage itself which shows most recent blog posts). Thanks much!
category page flow (bottom to top) is like this: ``` category-slug.php category-ID.php category.php archive.php index.php ``` so you can not create compulsory **category.php**. open your current theme **archive.php**. and edit this code. ``` <?php if( !is_category() ){ get_sidebar(); } ?> ```
246,632
<p>I'm making a plugin to register participations on a contest. I am using Magic Fields. On my development server, when I put an entry as a normal user all the data is saved on db and it shows in backend. everytime I try to edti fields as admin, it don't save and send me to "wp-admin/edit.php"</p> <p>Here's my saving function</p> <pre><code> add_action('save_post', 'add_fields_contest', 10, 2 ); function add_fields_contest( $id, $post ) { require_once(ABSPATH . 'wp-includes/pluggable.php'); if ( $post-&gt;post_type == 'contest' ) { update_post_meta( $id, 'userid', $_POST['userid'] ); update_post_meta( $id, 'title', $_POST['title'] ); update_post_meta( $id, 'name', $_POST['name'] ); update_post_meta( $id, 'age', $_POST['age'] ); } } </code></pre> <p>All fields exist, I have a metabox created and I really don't know why this isn't saving.</p>
[ { "answer_id": 246615, "author": "Ranuka", "author_id": 106350, "author_profile": "https://wordpress.stackexchange.com/users/106350", "pm_score": 0, "selected": false, "text": "<p>This solution depend on the theme. Sometimes this solution does not work for your theme.</p>\n\n<ol>\n<li><p>Go to category.php page.</p></li>\n<li><p>Find <code>get_sidebar</code> function.</p></li>\n<li><p>Remove the <code>get_sidebar</code> function including parameters if there.</p></li>\n</ol>\n\n<p>You may need to change some css part also. And if you are not using child theme your customization will be lost when updating the theme. </p>\n" }, { "answer_id": 246616, "author": "Etherplain", "author_id": 107235, "author_profile": "https://wordpress.stackexchange.com/users/107235", "pm_score": 0, "selected": false, "text": "<p>So, in the same way you might go to the store and you can't find that one item your shopping for, then break down and ask someone only to learn it's right behind you.... I figured this out. I cheated, but I found that if you just copy the full width page template into category.php (which I had to create) and just change one line of code, it does the job. Here's the full php if it helps anyone.</p>\n\n<pre><code> &lt;?php\n\n/*\n\nTemplate Name: Full width\n\n*/\n get_header();\n?&gt;\n\n\n\n &lt;div id=\"primary\" class=\"content-area fullwidth\"&gt;\n &lt;main id=\"main\" class=\"site-main\" role=\"main\"&gt;\n\n &lt;?php while ( have_posts() ) : the_post(); ?&gt;\n\n &lt;?php get_template_part( 'template-parts/content', 'page' ); ?&gt;\n\n &lt;?php\n\n if ( comments_open() || '0' != get_comments_number() ) :\n\n comments_template();\n\n endif;\n ?&gt;\n\n &lt;?php endwhile; // end of the loop. ?&gt;\n\n\n &lt;/main&gt;&lt;!-- #main --&gt;\n &lt;/div&gt;&lt;!-- #primary --&gt;\n\n&lt;?php get_footer(); ?&gt;\n</code></pre>\n\n<p>Only thing you need to change is here. Change page to category: </p>\n\n<pre><code>&lt;?php get_template_part( 'template-parts/content', 'category' ); ?&gt;\n</code></pre>\n\n<p>That said, I'm sure there's an easier way to address this problem. One way may be to display categories on a specific page (where the theme's page templates will come into play), instead of redirecting to the category like I do.</p>\n" }, { "answer_id": 282733, "author": "Steven Johnson", "author_id": 129400, "author_profile": "https://wordpress.stackexchange.com/users/129400", "pm_score": 0, "selected": false, "text": "<p>Your provided example only works because the new template that you've created is hooked to content-category.php, which doesn't exist by default within the Astrid Theme.</p>\n\n<p>I've only taken a brief scan of the code for Astrid, but it looks like there's only a single sidebar that's called -- located in <strong>index.php</strong>.</p>\n\n<p>If you're trying to avoid the sidebar on specifically your <em>Archives</em> and <em>Categories</em> pages, open index.php and you should see the following:</p>\n\n<pre><code>&lt;?php\n/**\n* The main template file.\n*\n* This is the most generic template file in a WordPress theme\n* and one of the two required files for a theme (the other being style.css).\n* It is used to display a page when nothing more specific matches a query.\n* E.g., it puts together the home page when no home.php file exists.\n*\n* @link https://codex.wordpress.org/Template_Hierarchy\n*\n* @package Astrid\n*/\n\nget_header(); ?&gt;\n\n&lt;div id=\"primary\" class=\"content-area\"&gt;\n &lt;main id=\"main\" class=\"site-main\" role=\"main\"&gt;\n\n &lt;?php\n if ( have_posts() ) :\n\n if ( is_home() &amp;&amp; ! is_front_page() ) : ?&gt;\n &lt;header&gt;\n &lt;h1 class=\"page-title screen-reader-text\"&gt;&lt;?php single_post_title(); ?&gt;&lt;/h1&gt;\n &lt;/header&gt;\n\n &lt;?php\n endif;\n\n /* Start the Loop */\n while ( have_posts() ) : the_post();\n\n /*\n * Include the Post-Format-specific template for the content.\n * If you want to override this in a child theme, then include a file\n * called content-___.php (where ___ is the Post Format name) and that will be used instead.\n */\n get_template_part( 'template-parts/content', get_post_format() );\n\n endwhile;\n\n the_posts_navigation();\n\n else :\n\n get_template_part( 'template-parts/content', 'none' );\n\n endif; ?&gt;\n\n &lt;/main&gt;&lt;!-- #main --&gt;\n&lt;/div&gt;&lt;!-- #primary --&gt;\n\n&lt;?php\nget_sidebar();\nget_footer();\n</code></pre>\n\n<p>At the bottom of index.php, <strong>get_sidebar();</strong> is called with no condition as to when. </p>\n\n<p>If I understand your question correctly, the simplest resolution would be to wrap the <em>get_sidebar()</em> method in a conditional statement as follows:</p>\n\n<pre><code> if( !is_category() &amp;&amp; !is_archive() ) {\n get_sidebar();\n}\n</code></pre>\n" }, { "answer_id": 288967, "author": "Jignesh Patel", "author_id": 111556, "author_profile": "https://wordpress.stackexchange.com/users/111556", "pm_score": 1, "selected": false, "text": "<p>category page flow (bottom to top) is like this:</p>\n\n<pre><code>category-slug.php\ncategory-ID.php\ncategory.php\narchive.php\nindex.php\n</code></pre>\n\n<p>so you can not create compulsory <strong>category.php</strong>. open your current theme <strong>archive.php</strong>. and edit this code.</p>\n\n<pre><code>&lt;?php \n if( !is_category() ){\n get_sidebar();\n }\n?&gt;\n</code></pre>\n" } ]
2016/11/18
[ "https://wordpress.stackexchange.com/questions/246632", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102510/" ]
I'm making a plugin to register participations on a contest. I am using Magic Fields. On my development server, when I put an entry as a normal user all the data is saved on db and it shows in backend. everytime I try to edti fields as admin, it don't save and send me to "wp-admin/edit.php" Here's my saving function ``` add_action('save_post', 'add_fields_contest', 10, 2 ); function add_fields_contest( $id, $post ) { require_once(ABSPATH . 'wp-includes/pluggable.php'); if ( $post->post_type == 'contest' ) { update_post_meta( $id, 'userid', $_POST['userid'] ); update_post_meta( $id, 'title', $_POST['title'] ); update_post_meta( $id, 'name', $_POST['name'] ); update_post_meta( $id, 'age', $_POST['age'] ); } } ``` All fields exist, I have a metabox created and I really don't know why this isn't saving.
category page flow (bottom to top) is like this: ``` category-slug.php category-ID.php category.php archive.php index.php ``` so you can not create compulsory **category.php**. open your current theme **archive.php**. and edit this code. ``` <?php if( !is_category() ){ get_sidebar(); } ?> ```
246,662
<p>I use conditional code to apply a css highlight to the menu item of a page currently being viewed.</p> <p><code>&lt;li&lt;?php if ( is_page('channels') || '2704' == $post-&gt;post_parent ) { echo " class=\"current\""; } // the page is 'channels', or the parent of the page is 'channels'?&gt;&gt;&lt;a href="/programs/channels/"&gt;Channels&lt;/a&gt;&lt;/li&gt;</code></p> <p>I need to also apply it to all pages below that parent.</p>
[ { "answer_id": 246615, "author": "Ranuka", "author_id": 106350, "author_profile": "https://wordpress.stackexchange.com/users/106350", "pm_score": 0, "selected": false, "text": "<p>This solution depend on the theme. Sometimes this solution does not work for your theme.</p>\n\n<ol>\n<li><p>Go to category.php page.</p></li>\n<li><p>Find <code>get_sidebar</code> function.</p></li>\n<li><p>Remove the <code>get_sidebar</code> function including parameters if there.</p></li>\n</ol>\n\n<p>You may need to change some css part also. And if you are not using child theme your customization will be lost when updating the theme. </p>\n" }, { "answer_id": 246616, "author": "Etherplain", "author_id": 107235, "author_profile": "https://wordpress.stackexchange.com/users/107235", "pm_score": 0, "selected": false, "text": "<p>So, in the same way you might go to the store and you can't find that one item your shopping for, then break down and ask someone only to learn it's right behind you.... I figured this out. I cheated, but I found that if you just copy the full width page template into category.php (which I had to create) and just change one line of code, it does the job. Here's the full php if it helps anyone.</p>\n\n<pre><code> &lt;?php\n\n/*\n\nTemplate Name: Full width\n\n*/\n get_header();\n?&gt;\n\n\n\n &lt;div id=\"primary\" class=\"content-area fullwidth\"&gt;\n &lt;main id=\"main\" class=\"site-main\" role=\"main\"&gt;\n\n &lt;?php while ( have_posts() ) : the_post(); ?&gt;\n\n &lt;?php get_template_part( 'template-parts/content', 'page' ); ?&gt;\n\n &lt;?php\n\n if ( comments_open() || '0' != get_comments_number() ) :\n\n comments_template();\n\n endif;\n ?&gt;\n\n &lt;?php endwhile; // end of the loop. ?&gt;\n\n\n &lt;/main&gt;&lt;!-- #main --&gt;\n &lt;/div&gt;&lt;!-- #primary --&gt;\n\n&lt;?php get_footer(); ?&gt;\n</code></pre>\n\n<p>Only thing you need to change is here. Change page to category: </p>\n\n<pre><code>&lt;?php get_template_part( 'template-parts/content', 'category' ); ?&gt;\n</code></pre>\n\n<p>That said, I'm sure there's an easier way to address this problem. One way may be to display categories on a specific page (where the theme's page templates will come into play), instead of redirecting to the category like I do.</p>\n" }, { "answer_id": 282733, "author": "Steven Johnson", "author_id": 129400, "author_profile": "https://wordpress.stackexchange.com/users/129400", "pm_score": 0, "selected": false, "text": "<p>Your provided example only works because the new template that you've created is hooked to content-category.php, which doesn't exist by default within the Astrid Theme.</p>\n\n<p>I've only taken a brief scan of the code for Astrid, but it looks like there's only a single sidebar that's called -- located in <strong>index.php</strong>.</p>\n\n<p>If you're trying to avoid the sidebar on specifically your <em>Archives</em> and <em>Categories</em> pages, open index.php and you should see the following:</p>\n\n<pre><code>&lt;?php\n/**\n* The main template file.\n*\n* This is the most generic template file in a WordPress theme\n* and one of the two required files for a theme (the other being style.css).\n* It is used to display a page when nothing more specific matches a query.\n* E.g., it puts together the home page when no home.php file exists.\n*\n* @link https://codex.wordpress.org/Template_Hierarchy\n*\n* @package Astrid\n*/\n\nget_header(); ?&gt;\n\n&lt;div id=\"primary\" class=\"content-area\"&gt;\n &lt;main id=\"main\" class=\"site-main\" role=\"main\"&gt;\n\n &lt;?php\n if ( have_posts() ) :\n\n if ( is_home() &amp;&amp; ! is_front_page() ) : ?&gt;\n &lt;header&gt;\n &lt;h1 class=\"page-title screen-reader-text\"&gt;&lt;?php single_post_title(); ?&gt;&lt;/h1&gt;\n &lt;/header&gt;\n\n &lt;?php\n endif;\n\n /* Start the Loop */\n while ( have_posts() ) : the_post();\n\n /*\n * Include the Post-Format-specific template for the content.\n * If you want to override this in a child theme, then include a file\n * called content-___.php (where ___ is the Post Format name) and that will be used instead.\n */\n get_template_part( 'template-parts/content', get_post_format() );\n\n endwhile;\n\n the_posts_navigation();\n\n else :\n\n get_template_part( 'template-parts/content', 'none' );\n\n endif; ?&gt;\n\n &lt;/main&gt;&lt;!-- #main --&gt;\n&lt;/div&gt;&lt;!-- #primary --&gt;\n\n&lt;?php\nget_sidebar();\nget_footer();\n</code></pre>\n\n<p>At the bottom of index.php, <strong>get_sidebar();</strong> is called with no condition as to when. </p>\n\n<p>If I understand your question correctly, the simplest resolution would be to wrap the <em>get_sidebar()</em> method in a conditional statement as follows:</p>\n\n<pre><code> if( !is_category() &amp;&amp; !is_archive() ) {\n get_sidebar();\n}\n</code></pre>\n" }, { "answer_id": 288967, "author": "Jignesh Patel", "author_id": 111556, "author_profile": "https://wordpress.stackexchange.com/users/111556", "pm_score": 1, "selected": false, "text": "<p>category page flow (bottom to top) is like this:</p>\n\n<pre><code>category-slug.php\ncategory-ID.php\ncategory.php\narchive.php\nindex.php\n</code></pre>\n\n<p>so you can not create compulsory <strong>category.php</strong>. open your current theme <strong>archive.php</strong>. and edit this code.</p>\n\n<pre><code>&lt;?php \n if( !is_category() ){\n get_sidebar();\n }\n?&gt;\n</code></pre>\n" } ]
2016/11/18
[ "https://wordpress.stackexchange.com/questions/246662", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103213/" ]
I use conditional code to apply a css highlight to the menu item of a page currently being viewed. `<li<?php if ( is_page('channels') || '2704' == $post->post_parent ) { echo " class=\"current\""; } // the page is 'channels', or the parent of the page is 'channels'?>><a href="/programs/channels/">Channels</a></li>` I need to also apply it to all pages below that parent.
category page flow (bottom to top) is like this: ``` category-slug.php category-ID.php category.php archive.php index.php ``` so you can not create compulsory **category.php**. open your current theme **archive.php**. and edit this code. ``` <?php if( !is_category() ){ get_sidebar(); } ?> ```
246,684
<p>I've got a lot of post meta keys that I no longer use, and I'm trying to work out how to delete them so they no longer show in the custom fields list in the admin panel.</p> <p><a href="https://i.stack.imgur.com/F85hi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F85hi.png" alt="enter image description here"></a></p> <p>This code will delete the post meta values:</p> <pre><code>function hp_batch_delete_post_meta(){ // get array of all post ids $post_ids = get_posts( array( 'numberposts' =&gt; -1, 'fields' =&gt; 'ids', 'post_type' =&gt; array('ad_upload','post', 'page'), 'post_status' =&gt; array('publish', 'auto-draft', 'trash', 'pending', 'draft'), ) ); // remove post meta for each post foreach( $post_ids as $post_id ) { delete_post_meta($post_id, 'my_postmeta_key_1'); delete_post_meta($post_id, 'my_postmeta_key_2'); delete_post_meta($post_id, 'my_postmeta_key_3'); } } add_action('init', 'hp_batch_delete_post_meta'); </code></pre> <p>But I would like to completely remove the meta keys too so they don't show in that admin list.</p> <p>Any help appreciated.</p>
[ { "answer_id": 246706, "author": "Ranuka", "author_id": 106350, "author_profile": "https://wordpress.stackexchange.com/users/106350", "pm_score": 3, "selected": true, "text": "<p>I found this from just a Google search (<a href=\"https://www.iftekhar.net/how-to-delete-unnecessary-post-metadata-from-wordpress/\" rel=\"nofollow noreferrer\">Source</a>)</p>\n\n<p>You have to change met value keys as you want. However, it is highly recommend to take a <strong>DB backup</strong> before running this code.</p>\n\n<pre><code>&lt;?php\nfunction delete_useless_post_meta() {\n global $wpdb;\n $table = $wpdb-&gt;prefix.'postmeta';\n $wpdb-&gt;delete ($table, array('meta_key' =&gt; '_edit_last'));\n $wpdb-&gt;delete ($table, array('meta_key' =&gt; '_edit_lock'));\n $wpdb-&gt;delete ($table, array('meta_key' =&gt; '_wp_old_slug')); }\nadd_action('wp_logout','delete_useless_post_meta');\n?&gt;\n</code></pre>\n" }, { "answer_id": 284624, "author": "Chris Rae", "author_id": 37384, "author_profile": "https://wordpress.stackexchange.com/users/37384", "pm_score": 3, "selected": false, "text": "<p>If you want to delete keys with a wildcard criteria of some sort (as I did) then you can do this directly in SQL.</p>\n\n<pre><code>DELETE FROM `wp_postmeta` WHERE `meta_key` LIKE 'weather_%'\n</code></pre>\n" }, { "answer_id": 363568, "author": "jeremyescott", "author_id": 114804, "author_profile": "https://wordpress.stackexchange.com/users/114804", "pm_score": 3, "selected": false, "text": "<p>This is quite an old post, but there is a much better way to do this.</p>\n\n<p>WordPress core has a function where you can delete all meta data by a key.</p>\n\n<pre><code>delete_metadata( string $meta_type, int $object_id, string $meta_key, mixed $meta_value = '', bool $delete_all = false );\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/delete_metadata/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/delete_metadata/</a></p>\n\n<p>Use it this way:</p>\n\n<pre><code>delete_metadata( 'post', 0, 'meta_key_to_delete', false, true );\n</code></pre>\n\n<p>This would apply to all post types, published status, etc. So to delete the examples meta keys as above:</p>\n\n<pre><code>$deletable = array( 'my_postmeta_key_1', 'my_postmeta_key_2', 'my_postmeta_key_3' );\nforeach( $deleteable as $to_delete ) {\n delete_metadata( 'post', 0, $to_delete, false, true );\n}\n</code></pre>\n" } ]
2016/11/18
[ "https://wordpress.stackexchange.com/questions/246684", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88767/" ]
I've got a lot of post meta keys that I no longer use, and I'm trying to work out how to delete them so they no longer show in the custom fields list in the admin panel. [![enter image description here](https://i.stack.imgur.com/F85hi.png)](https://i.stack.imgur.com/F85hi.png) This code will delete the post meta values: ``` function hp_batch_delete_post_meta(){ // get array of all post ids $post_ids = get_posts( array( 'numberposts' => -1, 'fields' => 'ids', 'post_type' => array('ad_upload','post', 'page'), 'post_status' => array('publish', 'auto-draft', 'trash', 'pending', 'draft'), ) ); // remove post meta for each post foreach( $post_ids as $post_id ) { delete_post_meta($post_id, 'my_postmeta_key_1'); delete_post_meta($post_id, 'my_postmeta_key_2'); delete_post_meta($post_id, 'my_postmeta_key_3'); } } add_action('init', 'hp_batch_delete_post_meta'); ``` But I would like to completely remove the meta keys too so they don't show in that admin list. Any help appreciated.
I found this from just a Google search ([Source](https://www.iftekhar.net/how-to-delete-unnecessary-post-metadata-from-wordpress/)) You have to change met value keys as you want. However, it is highly recommend to take a **DB backup** before running this code. ``` <?php function delete_useless_post_meta() { global $wpdb; $table = $wpdb->prefix.'postmeta'; $wpdb->delete ($table, array('meta_key' => '_edit_last')); $wpdb->delete ($table, array('meta_key' => '_edit_lock')); $wpdb->delete ($table, array('meta_key' => '_wp_old_slug')); } add_action('wp_logout','delete_useless_post_meta'); ?> ```
246,716
<p>I started a <a href="http://meta-game.org/" rel="nofollow noreferrer">wordpress</a> site about games, and I'd like to setup a workflow to allow php devs to work on the backend without fear of breaking something on the main site. How can I modify plugins so they don't affect the main site?</p> <p>I can run a server locally, and make my modifications with that, but this would mean that everyone working on the site would have to setup their own local servers, which could create quite a bit of overhead.</p> <p>So, again, my question is: how can I modify plugins so they don't affect the main site?</p>
[ { "answer_id": 246706, "author": "Ranuka", "author_id": 106350, "author_profile": "https://wordpress.stackexchange.com/users/106350", "pm_score": 3, "selected": true, "text": "<p>I found this from just a Google search (<a href=\"https://www.iftekhar.net/how-to-delete-unnecessary-post-metadata-from-wordpress/\" rel=\"nofollow noreferrer\">Source</a>)</p>\n\n<p>You have to change met value keys as you want. However, it is highly recommend to take a <strong>DB backup</strong> before running this code.</p>\n\n<pre><code>&lt;?php\nfunction delete_useless_post_meta() {\n global $wpdb;\n $table = $wpdb-&gt;prefix.'postmeta';\n $wpdb-&gt;delete ($table, array('meta_key' =&gt; '_edit_last'));\n $wpdb-&gt;delete ($table, array('meta_key' =&gt; '_edit_lock'));\n $wpdb-&gt;delete ($table, array('meta_key' =&gt; '_wp_old_slug')); }\nadd_action('wp_logout','delete_useless_post_meta');\n?&gt;\n</code></pre>\n" }, { "answer_id": 284624, "author": "Chris Rae", "author_id": 37384, "author_profile": "https://wordpress.stackexchange.com/users/37384", "pm_score": 3, "selected": false, "text": "<p>If you want to delete keys with a wildcard criteria of some sort (as I did) then you can do this directly in SQL.</p>\n\n<pre><code>DELETE FROM `wp_postmeta` WHERE `meta_key` LIKE 'weather_%'\n</code></pre>\n" }, { "answer_id": 363568, "author": "jeremyescott", "author_id": 114804, "author_profile": "https://wordpress.stackexchange.com/users/114804", "pm_score": 3, "selected": false, "text": "<p>This is quite an old post, but there is a much better way to do this.</p>\n\n<p>WordPress core has a function where you can delete all meta data by a key.</p>\n\n<pre><code>delete_metadata( string $meta_type, int $object_id, string $meta_key, mixed $meta_value = '', bool $delete_all = false );\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/delete_metadata/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/delete_metadata/</a></p>\n\n<p>Use it this way:</p>\n\n<pre><code>delete_metadata( 'post', 0, 'meta_key_to_delete', false, true );\n</code></pre>\n\n<p>This would apply to all post types, published status, etc. So to delete the examples meta keys as above:</p>\n\n<pre><code>$deletable = array( 'my_postmeta_key_1', 'my_postmeta_key_2', 'my_postmeta_key_3' );\nforeach( $deleteable as $to_delete ) {\n delete_metadata( 'post', 0, $to_delete, false, true );\n}\n</code></pre>\n" } ]
2016/11/19
[ "https://wordpress.stackexchange.com/questions/246716", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107325/" ]
I started a [wordpress](http://meta-game.org/) site about games, and I'd like to setup a workflow to allow php devs to work on the backend without fear of breaking something on the main site. How can I modify plugins so they don't affect the main site? I can run a server locally, and make my modifications with that, but this would mean that everyone working on the site would have to setup their own local servers, which could create quite a bit of overhead. So, again, my question is: how can I modify plugins so they don't affect the main site?
I found this from just a Google search ([Source](https://www.iftekhar.net/how-to-delete-unnecessary-post-metadata-from-wordpress/)) You have to change met value keys as you want. However, it is highly recommend to take a **DB backup** before running this code. ``` <?php function delete_useless_post_meta() { global $wpdb; $table = $wpdb->prefix.'postmeta'; $wpdb->delete ($table, array('meta_key' => '_edit_last')); $wpdb->delete ($table, array('meta_key' => '_edit_lock')); $wpdb->delete ($table, array('meta_key' => '_wp_old_slug')); } add_action('wp_logout','delete_useless_post_meta'); ?> ```
246,730
<p>I have a website which the post's contents are dynamically generated AFTER a post is published. </p> <p>I'm using this code to generate the content i want:</p> <p><code>add_action( 'publish_post', 'generate_content'); function generate_content($post){ //some code here }</code></p> <p>This process can sometimes take up to 5 minutes, while the post is instantly published (I already set the php timeout to 600 seconds).</p> <p>I want to schedule the post for when the function has finished it's task, or to save the post as draft and automatically publish it when it's ready.</p> <p>Is there a way to achieve this? Any help is appreciated.</p>
[ { "answer_id": 246743, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/wp_publish_post\" rel=\"nofollow noreferrer\"><code>wp_publish_post( $post_id)</code></a> to change the post's status. And consider another hook like <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\"><code>'save_post'</code></a> instead of <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/publish_post\" rel=\"nofollow noreferrer\"><code>'publish_post'</code></a> to kick off the process.</p>\n" }, { "answer_id": 246761, "author": "Ashok Kumar Nath", "author_id": 43284, "author_profile": "https://wordpress.stackexchange.com/users/43284", "pm_score": 2, "selected": true, "text": "<p>There might be two ways:</p>\n\n<pre><code>add_action( 'draft_post', 'wpse_246730_my_function' );\nfunction wpse_246730_my_function( $post_id, $post )\n{\n // Do your things\n\n // Just to stay safe\n remove_action( 'draft_post', 'wpse_246730_my_function' );\n wp_publish_post( $post_id );\n add_action( 'draft_post', 'wpse_246730_my_function' );\n}\n</code></pre>\n\n<p>Or make the post future status, and set a time after 10 or 20 mins to publish. Then use the following code:</p>\n\n<pre><code>add_action( 'future_post', 'wpse_246730_my_function' );\nfunction wpse_246730_my_function( $post_id, $post )\n{\n // Do your things\n}\n</code></pre>\n" }, { "answer_id": 246791, "author": "Sam Miller", "author_id": 84968, "author_profile": "https://wordpress.stackexchange.com/users/84968", "pm_score": 0, "selected": false, "text": "<p>This will let you run code once a post has been created and should run instantly. So if the new status of the post is publish and was any other status before like draft or no status this will run.</p>\n\n<pre><code>function some_function( $new, $old, $post ) {\n if ( ( $new == 'publish' ) &amp;&amp; ( $old != 'publish' ) &amp;&amp; ( $post-&gt;post_type == 'post' ) ) {\n //Run code here\n\n } else {\n return;\n }\n}\nadd_action( 'transition_post_status', 'some_function', 10, 3 );\n</code></pre>\n" } ]
2016/11/19
[ "https://wordpress.stackexchange.com/questions/246730", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94498/" ]
I have a website which the post's contents are dynamically generated AFTER a post is published. I'm using this code to generate the content i want: `add_action( 'publish_post', 'generate_content'); function generate_content($post){ //some code here }` This process can sometimes take up to 5 minutes, while the post is instantly published (I already set the php timeout to 600 seconds). I want to schedule the post for when the function has finished it's task, or to save the post as draft and automatically publish it when it's ready. Is there a way to achieve this? Any help is appreciated.
There might be two ways: ``` add_action( 'draft_post', 'wpse_246730_my_function' ); function wpse_246730_my_function( $post_id, $post ) { // Do your things // Just to stay safe remove_action( 'draft_post', 'wpse_246730_my_function' ); wp_publish_post( $post_id ); add_action( 'draft_post', 'wpse_246730_my_function' ); } ``` Or make the post future status, and set a time after 10 or 20 mins to publish. Then use the following code: ``` add_action( 'future_post', 'wpse_246730_my_function' ); function wpse_246730_my_function( $post_id, $post ) { // Do your things } ```
246,742
<p>I am using <a href="https://github.com/sbrajesh/multisite-global-terms/blob/master/mu-global-terms.php" rel="nofollow noreferrer">this function</a> to make categories and tags global on my multisite installation.</p> <p>An unfortunate side effect of global categories/tags is that it displays categories for posts across all sites. This creates two undesirable problems:</p> <ol> <li>It shows categories/tags that the current blog has no posts for, linking to an archive with a 'not found' message.</li> <li>For count, WordPress looks at all of the blogs in the network, finds the highest total for each category/tag from all blogs within the network and displays that number.</li> </ol> <p>When I display categories or tags in a dropdown on an individual site, I only want categories from the current blog_id to show in the list with the count from the number of corresponding posts in the current blog.</p> <p>I have tried to limit the posts in a category dropdown with meta_query, but it's not working for me:</p> <pre><code>&lt;form id="category-select" class="category-select" action="&lt;?php echo esc_url( home_url( '/' ) ); ?&gt;" method="get"&gt; $blog_id = get_current_blog_id(); $args = array( 'show_option_none' =&gt; __( 'Select Category' ), 'show_count' =&gt; 1, 'orderby' =&gt; 'name', 'echo' =&gt; 0, 'meta_query' =&gt; array( 'key' =&gt; 'blog_id', 'value' =&gt; $blog_id, 'compare' =&gt; '=') ); $select = wp_dropdown_categories( $args ); $replace = "&lt;select$1 onchange='return this.form.submit()'&gt;"; $select = preg_replace( '#&lt;select([^&gt;]*)&gt;#', $replace, $select ); &lt;noscript&gt; &lt;input type="submit" value="View" /&gt; &lt;/noscript&gt; &lt;/form&gt; </code></pre> <p>Any way to modify this meta_query parameter or tackle this from another angle?</p>
[ { "answer_id": 246743, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/wp_publish_post\" rel=\"nofollow noreferrer\"><code>wp_publish_post( $post_id)</code></a> to change the post's status. And consider another hook like <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\"><code>'save_post'</code></a> instead of <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/publish_post\" rel=\"nofollow noreferrer\"><code>'publish_post'</code></a> to kick off the process.</p>\n" }, { "answer_id": 246761, "author": "Ashok Kumar Nath", "author_id": 43284, "author_profile": "https://wordpress.stackexchange.com/users/43284", "pm_score": 2, "selected": true, "text": "<p>There might be two ways:</p>\n\n<pre><code>add_action( 'draft_post', 'wpse_246730_my_function' );\nfunction wpse_246730_my_function( $post_id, $post )\n{\n // Do your things\n\n // Just to stay safe\n remove_action( 'draft_post', 'wpse_246730_my_function' );\n wp_publish_post( $post_id );\n add_action( 'draft_post', 'wpse_246730_my_function' );\n}\n</code></pre>\n\n<p>Or make the post future status, and set a time after 10 or 20 mins to publish. Then use the following code:</p>\n\n<pre><code>add_action( 'future_post', 'wpse_246730_my_function' );\nfunction wpse_246730_my_function( $post_id, $post )\n{\n // Do your things\n}\n</code></pre>\n" }, { "answer_id": 246791, "author": "Sam Miller", "author_id": 84968, "author_profile": "https://wordpress.stackexchange.com/users/84968", "pm_score": 0, "selected": false, "text": "<p>This will let you run code once a post has been created and should run instantly. So if the new status of the post is publish and was any other status before like draft or no status this will run.</p>\n\n<pre><code>function some_function( $new, $old, $post ) {\n if ( ( $new == 'publish' ) &amp;&amp; ( $old != 'publish' ) &amp;&amp; ( $post-&gt;post_type == 'post' ) ) {\n //Run code here\n\n } else {\n return;\n }\n}\nadd_action( 'transition_post_status', 'some_function', 10, 3 );\n</code></pre>\n" } ]
2016/11/19
[ "https://wordpress.stackexchange.com/questions/246742", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107070/" ]
I am using [this function](https://github.com/sbrajesh/multisite-global-terms/blob/master/mu-global-terms.php) to make categories and tags global on my multisite installation. An unfortunate side effect of global categories/tags is that it displays categories for posts across all sites. This creates two undesirable problems: 1. It shows categories/tags that the current blog has no posts for, linking to an archive with a 'not found' message. 2. For count, WordPress looks at all of the blogs in the network, finds the highest total for each category/tag from all blogs within the network and displays that number. When I display categories or tags in a dropdown on an individual site, I only want categories from the current blog\_id to show in the list with the count from the number of corresponding posts in the current blog. I have tried to limit the posts in a category dropdown with meta\_query, but it's not working for me: ``` <form id="category-select" class="category-select" action="<?php echo esc_url( home_url( '/' ) ); ?>" method="get"> $blog_id = get_current_blog_id(); $args = array( 'show_option_none' => __( 'Select Category' ), 'show_count' => 1, 'orderby' => 'name', 'echo' => 0, 'meta_query' => array( 'key' => 'blog_id', 'value' => $blog_id, 'compare' => '=') ); $select = wp_dropdown_categories( $args ); $replace = "<select$1 onchange='return this.form.submit()'>"; $select = preg_replace( '#<select([^>]*)>#', $replace, $select ); <noscript> <input type="submit" value="View" /> </noscript> </form> ``` Any way to modify this meta\_query parameter or tackle this from another angle?
There might be two ways: ``` add_action( 'draft_post', 'wpse_246730_my_function' ); function wpse_246730_my_function( $post_id, $post ) { // Do your things // Just to stay safe remove_action( 'draft_post', 'wpse_246730_my_function' ); wp_publish_post( $post_id ); add_action( 'draft_post', 'wpse_246730_my_function' ); } ``` Or make the post future status, and set a time after 10 or 20 mins to publish. Then use the following code: ``` add_action( 'future_post', 'wpse_246730_my_function' ); function wpse_246730_my_function( $post_id, $post ) { // Do your things } ```
246,746
<p>I have a WordPress site using the following criteria from a plugin called MyCRED to determine whether to display content to the user, however that include consists of shortcodes and other non-PHP content. Is there a way to tell PHP 'treat this as if it is not PHP'? Shortcodes are key.</p> <pre><code>$minimum = 100; if ( is_user_logged_in() &amp;&amp; ( function_exists( 'mycred_get_users_cred' ) &amp;&amp; mycred_get_users_cred( get_current_user_id() ) &gt;= $minimum ) ) { } </code></pre>
[ { "answer_id": 246743, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/wp_publish_post\" rel=\"nofollow noreferrer\"><code>wp_publish_post( $post_id)</code></a> to change the post's status. And consider another hook like <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\"><code>'save_post'</code></a> instead of <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/publish_post\" rel=\"nofollow noreferrer\"><code>'publish_post'</code></a> to kick off the process.</p>\n" }, { "answer_id": 246761, "author": "Ashok Kumar Nath", "author_id": 43284, "author_profile": "https://wordpress.stackexchange.com/users/43284", "pm_score": 2, "selected": true, "text": "<p>There might be two ways:</p>\n\n<pre><code>add_action( 'draft_post', 'wpse_246730_my_function' );\nfunction wpse_246730_my_function( $post_id, $post )\n{\n // Do your things\n\n // Just to stay safe\n remove_action( 'draft_post', 'wpse_246730_my_function' );\n wp_publish_post( $post_id );\n add_action( 'draft_post', 'wpse_246730_my_function' );\n}\n</code></pre>\n\n<p>Or make the post future status, and set a time after 10 or 20 mins to publish. Then use the following code:</p>\n\n<pre><code>add_action( 'future_post', 'wpse_246730_my_function' );\nfunction wpse_246730_my_function( $post_id, $post )\n{\n // Do your things\n}\n</code></pre>\n" }, { "answer_id": 246791, "author": "Sam Miller", "author_id": 84968, "author_profile": "https://wordpress.stackexchange.com/users/84968", "pm_score": 0, "selected": false, "text": "<p>This will let you run code once a post has been created and should run instantly. So if the new status of the post is publish and was any other status before like draft or no status this will run.</p>\n\n<pre><code>function some_function( $new, $old, $post ) {\n if ( ( $new == 'publish' ) &amp;&amp; ( $old != 'publish' ) &amp;&amp; ( $post-&gt;post_type == 'post' ) ) {\n //Run code here\n\n } else {\n return;\n }\n}\nadd_action( 'transition_post_status', 'some_function', 10, 3 );\n</code></pre>\n" } ]
2016/11/19
[ "https://wordpress.stackexchange.com/questions/246746", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/96983/" ]
I have a WordPress site using the following criteria from a plugin called MyCRED to determine whether to display content to the user, however that include consists of shortcodes and other non-PHP content. Is there a way to tell PHP 'treat this as if it is not PHP'? Shortcodes are key. ``` $minimum = 100; if ( is_user_logged_in() && ( function_exists( 'mycred_get_users_cred' ) && mycred_get_users_cred( get_current_user_id() ) >= $minimum ) ) { } ```
There might be two ways: ``` add_action( 'draft_post', 'wpse_246730_my_function' ); function wpse_246730_my_function( $post_id, $post ) { // Do your things // Just to stay safe remove_action( 'draft_post', 'wpse_246730_my_function' ); wp_publish_post( $post_id ); add_action( 'draft_post', 'wpse_246730_my_function' ); } ``` Or make the post future status, and set a time after 10 or 20 mins to publish. Then use the following code: ``` add_action( 'future_post', 'wpse_246730_my_function' ); function wpse_246730_my_function( $post_id, $post ) { // Do your things } ```
246,750
<p>I have a code which shows categories list with images. Im using plugin to attach image to category.</p> <p>Working code is:</p> <pre><code>&lt;?php $args=array( 'orderby' =&gt; 'name', 'order' =&gt; 'ASC', ) ?&gt; &lt;?php foreach (get_categories( $args ) as $cat) : ?&gt; &lt;h3&gt;&lt;a href="&lt;?php echo get_category_link($cat-&gt;term_id); ?&gt;"&gt;&lt;?php echo $cat-&gt;cat_name; ?&gt;&lt;/a&gt;&lt;/h3&gt; &lt;a href="&lt;?php echo get_category_link($cat-&gt;term_id); ?&gt;"&gt;&lt;img src="&lt;?php echo z_taxonomy_image_url($cat-&gt;term_id); ?&gt;" /&gt;&lt;/a&gt; &lt;?php endforeach; ?&gt; </code></pre> <p>Problem is theres a lot of categories. I want to separate them by year (just add a line or text or something). Is it even possible? I know that categories dont store date. Posts are posted only in categories of current year so maybe this could help?</p>
[ { "answer_id": 246769, "author": "Ranuka", "author_id": 106350, "author_profile": "https://wordpress.stackexchange.com/users/106350", "pm_score": 1, "selected": false, "text": "<p>I don't know what is the purpose of having each each categories for every month because WordPress has monthly archive. You can use it.</p>\n\n<p>However, it is possible that what you are going to do.</p>\n\n<p>I can't write the code here because of lack of time. But I can give a guide to develop it.</p>\n\n<p>Read the comments in code section.</p>\n\n<pre><code>&lt;?php\n$args=array(\n 'orderby' =&gt; 'name',\n 'order' =&gt; 'ASC',\n)\n\n$year=\"\" // Assign a oldest year for this. If your first post is published in 2011, $year=2011\n?&gt;\n\n&lt;?php foreach (get_categories( $args ) as $cat) : \n $cat_post_id=\"\"; //Get the latest post id of current category and assign it to \n $cat_post_publish_year=\"\"; //Then find the post date of that post and assign the YEAR of that date (Only the year)\n\n if($year!==$cat_post_publish_year)\n {\n echo \"&lt;hr&gt;\";// Write anything to separate it.\n $year=$cat_post_publish_year;\n }\n\n\n?&gt;\n\n &lt;h3&gt;&lt;a href=\"&lt;?php echo get_category_link($cat-&gt;term_id); ?&gt;\"&gt;&lt;?php echo $cat-&gt;cat_name; ?&gt;&lt;/a&gt;&lt;/h3&gt;\n &lt;a href=\"&lt;?php echo get_category_link($cat-&gt;term_id); ?&gt;\"&gt;&lt;img src=\"&lt;?php echo z_taxonomy_image_url($cat-&gt;term_id); ?&gt;\" /&gt;&lt;/a&gt;\n\n&lt;?php endforeach; ?&gt;\n</code></pre>\n" }, { "answer_id": 246815, "author": "th3rion", "author_id": 40822, "author_profile": "https://wordpress.stackexchange.com/users/40822", "pm_score": 1, "selected": true, "text": "<p>Here is full working code. Im not php developer, so there are probably some things that could and should be corrected but it works. </p>\n\n<pre><code> &lt;?php \n\n $args=array('orderby' =&gt; 'ID', 'order' =&gt; 'DESC');\n $year=\"2005\";\n\n foreach (get_categories( $args ) as $cat) : \n\n $post_ids = get_posts(array(\n 'posts_per_page' =&gt; 1, \n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'category',\n 'field' =&gt; 'id',\n 'terms' =&gt; $cat,\n ),\n ),\n 'fields' =&gt; 'ids', \n ));\n\n $cat_post_id=$post_ids[array_rand($post_ids)];\n $cat_post_publish_year=get_the_date( 'Y', $cat_post_id);\n\n if($year!==$cat_post_publish_year)\n {\n\n ?&gt; \n &lt;div style=\"display: block; clear: both; width: 100%; height: 20px; border-top: 1px solid #fff;\"&gt;&lt;/div&gt;\n\n &lt;?php\n\n $year=$cat_post_publish_year; }\n\n ?&gt;\n &lt;div style=\"float: left;\"&gt;\n\n &lt;a href=\"&lt;?php echo get_category_link($cat-&gt;term_id); ?&gt;\"&gt;&lt;img src=\"&lt;?php echo z_taxonomy_image_url($cat-&gt;term_id); ?&gt;\" /&gt;&lt;/a&gt;\n &lt;h3&gt;&lt;a href=\"&lt;?php echo get_category_link($cat-&gt;term_id); ?&gt;\"&gt;&lt;?php echo $cat-&gt;cat_name; ?&gt;&lt;/a&gt;&lt;/h3&gt;\n\n &lt;/div&gt;\n\n &lt;?php endforeach; ?&gt;\n</code></pre>\n" } ]
2016/11/19
[ "https://wordpress.stackexchange.com/questions/246750", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40822/" ]
I have a code which shows categories list with images. Im using plugin to attach image to category. Working code is: ``` <?php $args=array( 'orderby' => 'name', 'order' => 'ASC', ) ?> <?php foreach (get_categories( $args ) as $cat) : ?> <h3><a href="<?php echo get_category_link($cat->term_id); ?>"><?php echo $cat->cat_name; ?></a></h3> <a href="<?php echo get_category_link($cat->term_id); ?>"><img src="<?php echo z_taxonomy_image_url($cat->term_id); ?>" /></a> <?php endforeach; ?> ``` Problem is theres a lot of categories. I want to separate them by year (just add a line or text or something). Is it even possible? I know that categories dont store date. Posts are posted only in categories of current year so maybe this could help?
Here is full working code. Im not php developer, so there are probably some things that could and should be corrected but it works. ``` <?php $args=array('orderby' => 'ID', 'order' => 'DESC'); $year="2005"; foreach (get_categories( $args ) as $cat) : $post_ids = get_posts(array( 'posts_per_page' => 1, 'tax_query' => array( array( 'taxonomy' => 'category', 'field' => 'id', 'terms' => $cat, ), ), 'fields' => 'ids', )); $cat_post_id=$post_ids[array_rand($post_ids)]; $cat_post_publish_year=get_the_date( 'Y', $cat_post_id); if($year!==$cat_post_publish_year) { ?> <div style="display: block; clear: both; width: 100%; height: 20px; border-top: 1px solid #fff;"></div> <?php $year=$cat_post_publish_year; } ?> <div style="float: left;"> <a href="<?php echo get_category_link($cat->term_id); ?>"><img src="<?php echo z_taxonomy_image_url($cat->term_id); ?>" /></a> <h3><a href="<?php echo get_category_link($cat->term_id); ?>"><?php echo $cat->cat_name; ?></a></h3> </div> <?php endforeach; ?> ```
246,768
<p>I have a following code for the custom post type, and I want to display the content of it inside the loop.</p> <pre><code> $args = array( 'post_type' =&gt; 'gallery', 'posts_per_page' =&gt; -1, 'paged' =&gt; $paged, 'supress_filters' =&gt; false, ); // Tax query if ( $gallery_filter_parent ) { $args['tax_query'] = array( array( 'taxonomy' =&gt; 'gallery_cats', 'field' =&gt; 'id', 'terms' =&gt; $gallery_filter_parent ) ); } // Get post type ==&gt; gallery query_posts( $args ); // Loop through gallery items while ( have_posts() ) : the_post(); get_template_part( 'loop', 'gallery' ); endwhile; ?&gt; </code></pre>
[ { "answer_id": 246770, "author": "elicohenator", "author_id": 98507, "author_profile": "https://wordpress.stackexchange.com/users/98507", "pm_score": 0, "selected": false, "text": "<p>have you tried using this?</p>\n\n<pre><code>&lt;?php the_content() ?&gt;\n</code></pre>\n\n<p>also, you're code assumes there is a template part called 'gallery content'. does the file exists?</p>\n\n<p>simple testing method would be: </p>\n\n<pre><code>// Loop through gallery items\n while ( have_posts() ) : the_post(); ?&gt;\n &lt;h1&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt;\n &lt;div&gt;&lt;?php the_content(); ?&gt;&lt;/div&gt;\n &lt;?php endwhile; ?&gt;\n</code></pre>\n" }, { "answer_id": 246790, "author": "Sahriar Saikat", "author_id": 69365, "author_profile": "https://wordpress.stackexchange.com/users/69365", "pm_score": 0, "selected": false, "text": "<p>Your code requires following things</p>\n\n<ul>\n<li>loop-gallery.php (solution: simply copy and pest+rename loop-content.php into loop-gallery.php, it really varies from theme to theme. Different theme have different structure, if you are using a free theme from Wordpress directory, tell the name)</li>\n<li>A <a href=\"https://codex.wordpress.org/Taxonomies\" rel=\"nofollow noreferrer\">custom taxonomy</a> named <strong>gallery_cats</strong>.</li>\n<li>change post_per_page value into 10 (number of posts you want to be displayed.)</li>\n</ul>\n" }, { "answer_id": 285310, "author": "Kristian Kalvå", "author_id": 97184, "author_profile": "https://wordpress.stackexchange.com/users/97184", "pm_score": 1, "selected": false, "text": "<p>What do you have in loop-gallery.php? That's the file which will show the content of the gallery post.</p>\n\n<p>If you haven't created a loop-gallery.php, you should create a file with that name and put it in the root theme folder. In that file you could put something like the following to show the content:</p>\n\n<pre><code>&lt;div&gt;\n &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt;\n &lt;div&gt;&lt;?php the_content(); ?&gt;&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>You could obviously put something more complex in that file, if you however don't need more than that and you're not reusing the snippet elsewhere in your theme you could simply do the following change to your code to get the same result:</p>\n\n<pre><code>while ( have_posts() ) : the_post();\n &lt;div&gt;\n &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt;\n &lt;div&gt;&lt;?php the_content(); ?&gt;&lt;/div&gt;\n &lt;/div&gt;\n&lt;?php endwhile; ?&gt;\n</code></pre>\n\n<p>Also, have you recently registered your custom post type? If so you may have to reset your permalinks (although that shouldn't have anything to do with this specfic use case. To reset your permalinks, simply visit Settings > Permalinks and hit save. That will resave the permalinks on your site, including the new permalinks for the custom post type.</p>\n" } ]
2016/11/20
[ "https://wordpress.stackexchange.com/questions/246768", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93692/" ]
I have a following code for the custom post type, and I want to display the content of it inside the loop. ``` $args = array( 'post_type' => 'gallery', 'posts_per_page' => -1, 'paged' => $paged, 'supress_filters' => false, ); // Tax query if ( $gallery_filter_parent ) { $args['tax_query'] = array( array( 'taxonomy' => 'gallery_cats', 'field' => 'id', 'terms' => $gallery_filter_parent ) ); } // Get post type ==> gallery query_posts( $args ); // Loop through gallery items while ( have_posts() ) : the_post(); get_template_part( 'loop', 'gallery' ); endwhile; ?> ```
What do you have in loop-gallery.php? That's the file which will show the content of the gallery post. If you haven't created a loop-gallery.php, you should create a file with that name and put it in the root theme folder. In that file you could put something like the following to show the content: ``` <div> <h2><?php the_title(); ?></h2> <div><?php the_content(); ?></div> </div> ``` You could obviously put something more complex in that file, if you however don't need more than that and you're not reusing the snippet elsewhere in your theme you could simply do the following change to your code to get the same result: ``` while ( have_posts() ) : the_post(); <div> <h2><?php the_title(); ?></h2> <div><?php the_content(); ?></div> </div> <?php endwhile; ?> ``` Also, have you recently registered your custom post type? If so you may have to reset your permalinks (although that shouldn't have anything to do with this specfic use case. To reset your permalinks, simply visit Settings > Permalinks and hit save. That will resave the permalinks on your site, including the new permalinks for the custom post type.
246,785
<p>I want to show font awesome icon (installed) on the left side of the WordPress widget title. I found this shortcode that should do the work.</p> <pre><code>add_filter( 'widget_title', 'do_shortcode' ); add_shortcode( 'icon', 'shortcode_fa' ); function shortcode_fa($attr, $content ) { return '&lt;i class="fa fa-'. $content . '"&gt;&lt;/i&gt;'; } </code></pre> <p>After adding this in <code>functions.php</code>, I should be able to add a gear icon in the widget title with below code from <strong>Appearence>Widget</strong></p> <pre><code>[icon]cog[icon] </code></pre> <p>But it is not working.</p>
[ { "answer_id": 246796, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": true, "text": "<p>I checked your code in my install. It works, except that you made a typo (missing backslash):</p>\n\n<pre><code>[icon]cog[/icon]\n</code></pre>\n\n<p>Few notes:</p>\n\n<ul>\n<li><p>You must make sure to <strong>enqueue</strong> the <em>Font Awsesome</em> stylesheet.</p></li>\n<li><p>You must <strong>close the shortcode</strong>, like: <code>[icon]cog[/icon]</code></p></li>\n<li><p>Remember to <strong>escape</strong> the class name with <code>esc_attr()</code>.</p></li>\n<li><p>Another shortcode idea: <code>[fa icon=\"cog\"]</code></p></li>\n</ul>\n" }, { "answer_id": 391972, "author": "Jared Chu", "author_id": 106820, "author_profile": "https://wordpress.stackexchange.com/users/106820", "pm_score": 0, "selected": false, "text": "<p><strong>Full working code here!</strong></p>\n<p>Add this to <code>functions.php</code>:</p>\n<pre><code>add_filter( 'widget_title', 'do_shortcode' );\nadd_shortcode( 'fa', 'shortcode_fa' );\nfunction shortcode_fa($attr, $content ) {\n $icon = $attr['icon'];\n return &quot;&lt;i class='fa fa-$icon'&gt;&lt;/i&gt;&quot;;\n}\n</code></pre>\n<p>Add shortcode to widget title:</p>\n<pre><code>[fa icon=copyright] Widget title text\n</code></pre>\n<p>Result:</p>\n<p><a href=\"https://i.stack.imgur.com/LKVKr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LKVKr.png\" alt=\"enter image description here\" /></a></p>\n" } ]
2016/11/20
[ "https://wordpress.stackexchange.com/questions/246785", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69365/" ]
I want to show font awesome icon (installed) on the left side of the WordPress widget title. I found this shortcode that should do the work. ``` add_filter( 'widget_title', 'do_shortcode' ); add_shortcode( 'icon', 'shortcode_fa' ); function shortcode_fa($attr, $content ) { return '<i class="fa fa-'. $content . '"></i>'; } ``` After adding this in `functions.php`, I should be able to add a gear icon in the widget title with below code from **Appearence>Widget** ``` [icon]cog[icon] ``` But it is not working.
I checked your code in my install. It works, except that you made a typo (missing backslash): ``` [icon]cog[/icon] ``` Few notes: * You must make sure to **enqueue** the *Font Awsesome* stylesheet. * You must **close the shortcode**, like: `[icon]cog[/icon]` * Remember to **escape** the class name with `esc_attr()`. * Another shortcode idea: `[fa icon="cog"]`
246,809
<p>Given an array of Post objects, how might one initialize <a href="https://codex.wordpress.org/The_Loop" rel="nofollow noreferrer">The Loop</a> so that the common Loop functions could be used:</p> <pre><code>$posts = array( /* WP_Post, WP_Post, ... */); while ( have_posts() ) { the_post(); the_title(); } </code></pre> <p>I am aware that I could simply loop over the array elements and pass to each function the ID of each element, however for reasons beyond my control using the actual Wordpress Loop is preferred here.</p> <p>The array is provided from a function that I cannot alter. For purposes of discussion it might as well have come from <a href="http://php.net/manual/en/function.unserialize.php" rel="nofollow noreferrer">unserialize()</a>.</p>
[ { "answer_id": 246811, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 0, "selected": false, "text": "<p>You need to change the whole clause. </p>\n\n<pre><code> while ( $posts-&gt;have_posts() ) {\n the_post();\n the_title();\n }\n</code></pre>\n\n<p>BUT, it can't work because this one is good if <code>$posts</code> comes from a new WP_Query().</p>\n\n<p>To loop through the <code>$posts</code> array, you can do as follow</p>\n\n<pre><code> foreach($posts as $post){\n echo $post-&gt;post_title;\n if($post-&gt;ID != 123){\n echo $post-&gt;post_content;\n }\n\n }\n</code></pre>\n\n<p>You write that you can have control on the query, search in the source code of the plugin for <code>apply_filters</code> , maybe there a way to filter these datas.</p>\n\n<p>Hope it helps !</p>\n" }, { "answer_id": 246812, "author": "DrLightman", "author_id": 4053, "author_profile": "https://wordpress.stackexchange.com/users/4053", "pm_score": 3, "selected": true, "text": "<p>I'm using this in one of my custom widgets:</p>\n\n<pre><code>global $post;\n$posts = array( /* WP_Post, WP_Post, ... */);\nwhile (list($i, $post) = each($posts)) :\n setup_postdata($post);\n // use the template tags below here\n if(has_post_thumbnail()):\n ?&gt;&lt;div class=\"featured_image_wrap\"&gt;&lt;?php\n the_post_thumbnail();\n ?&gt;&lt;/div&gt;&lt;?php\n endif;\n the_title();\nendwhile;\n// don't forget to restore the main queried object after the loop!\nwp_reset_postdata();\n</code></pre>\n" } ]
2016/11/20
[ "https://wordpress.stackexchange.com/questions/246809", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/34330/" ]
Given an array of Post objects, how might one initialize [The Loop](https://codex.wordpress.org/The_Loop) so that the common Loop functions could be used: ``` $posts = array( /* WP_Post, WP_Post, ... */); while ( have_posts() ) { the_post(); the_title(); } ``` I am aware that I could simply loop over the array elements and pass to each function the ID of each element, however for reasons beyond my control using the actual Wordpress Loop is preferred here. The array is provided from a function that I cannot alter. For purposes of discussion it might as well have come from [unserialize()](http://php.net/manual/en/function.unserialize.php).
I'm using this in one of my custom widgets: ``` global $post; $posts = array( /* WP_Post, WP_Post, ... */); while (list($i, $post) = each($posts)) : setup_postdata($post); // use the template tags below here if(has_post_thumbnail()): ?><div class="featured_image_wrap"><?php the_post_thumbnail(); ?></div><?php endif; the_title(); endwhile; // don't forget to restore the main queried object after the loop! wp_reset_postdata(); ```
246,834
<p>I am trying to list the name of the moderators (users with editor role) that publish pending posts. I created a dashboard widget that shows the latest 10 published posts and the author, but I have problems getting the user that published it. I thought <code>the_modified_author</code> might be it, but I'm not sure if there's <strong>a better way to tell who published the post?</strong> Either way, my method isn't working. Here's my code so far:</p> <pre><code>function dashboard_widget_function() { $args = array( 'post_status' =&gt; 'publish', 'numberposts' =&gt; '10', 'post_type' =&gt; 'post'); $recent_posts = wp_get_recent_posts( $args ); echo '&lt;table&gt;&lt;tr&gt;     &lt;th&gt;Post Title&lt;/th&gt;     &lt;th&gt;Author&lt;/th&gt;     &lt;th&gt;Moderated by&lt;/th&gt;&lt;/tr&gt;'; foreach( $recent_posts as $recent ){ $post_author = get_user_by( 'id', $recent['post_author'] ); echo '&lt;tr&gt;&lt;td&gt;&lt;a href="' . get_permalink($recent["ID"]) . '" title="Read: '.esc_attr($recent["post_title"]).'" &gt;' . $recent["post_title"].'&lt;/a&gt;&lt;/td&gt;'; echo '&lt;td&gt;'. $post_author-&gt;display_name .'&lt;/td&gt;'; echo '&lt;td&gt;'.get_the_modified_author().'&lt;/td&gt;&lt;/tr&gt;'; } echo '&lt;/table&gt;'; } </code></pre>
[ { "answer_id": 246844, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>We could save the id of the user that last published a post, as the value of the <code>_wpse_user_last_published</code> post meta key, with:</p>\n\n<pre><code>add_action( 'transition_post_status', function( $new_status, $old_status, $post )\n{\n if( \n $new_status !== $old_status \n &amp;&amp; 'publish' === $new_status \n &amp;&amp; 'post' === get_post_type( $post ) \n )\n update_post_meta( $post-&gt;ID, '_wpse_user_last_published', get_current_user_id() );\n\n}, 10, 3 );\n</code></pre>\n\n<p>Then you could fetch this info when you list your posts.</p>\n\n<p>For more detail and faster search, it might be better to create a custom log table.</p>\n" }, { "answer_id": 246845, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<p>The reason that <code>get_the_modified_author()</code> is not working is that it relies on being used within the WordPress loop. <code>wp_get_recent_posts()</code> does not set up a global post object. Here is a complete example based on your original code that replaces <code>get_the_modified_author()</code> with some simple code to get the name of the last person who edited the post (which is essentially what <code>get_the_modified_author()</code> does):</p>\n\n<pre><code>/**\n * Add a widget to the dashboard.\n *\n * This function is hooked into the 'wp_dashboard_setup' action below.\n */\nfunction example_add_dashboard_widgets() {\n wp_add_dashboard_widget(\n 'example_dashboard_widget', // Widget slug.\n 'Example Dashboard Widget', // Title.\n 'example_dashboard_widget_function' // Display function.\n ); \n}\nadd_action( 'wp_dashboard_setup', 'example_add_dashboard_widgets' );\n\nfunction example_dashboard_widget_function() {\n $items_to_show = 10;\n $counter = 0;\n $recent_posts = wp_get_recent_posts( [\n 'post_status' =&gt; 'publish',\n 'numberposts' =&gt; '50', // More than we want, but tries to ensure we have enough items to display.\n 'post_type' =&gt; 'post'\n ] );\n\n echo '&lt;table&gt;\n &lt;tr&gt;\n &lt;th&gt;Post Title&lt;/th&gt;\n &lt;th&gt;Author&lt;/th&gt;\n &lt;th&gt;Moderated by&lt;/th&gt;\n &lt;/tr&gt;';\n\n foreach ( $recent_posts as $recent ) {\n $post_author = get_user_by( 'id', $recent['post_author'] );\n $last_user_id = get_post_meta( $recent['ID'], '_edit_last', true );\n $last_user = get_userdata( $last_user_id );\n\n // Bail out of the loop if we've shown enough items.\n if ( $counter &gt;= $items_to_show ) {\n break;\n }\n\n // Skip display of items where the author is the same as the moderator:\n if ( $post_author-&gt;display_name === $last_user-&gt;display_name ) {\n continue;\n }\n\n echo '&lt;tr&gt;&lt;td&gt;&lt;a href=\"' . get_permalink( $recent['ID'] ) . '\" title=\"Read: ' . \n esc_attr( $recent['post_title'] ).'\" &gt;' . $recent['post_title'].'&lt;/a&gt;&lt;/td&gt;';\n echo '&lt;td&gt;'. esc_html( $post_author-&gt;display_name ) .'&lt;/td&gt;';\n\n echo '&lt;td&gt;'. esc_html( $last_user-&gt;display_name ) .'&lt;/td&gt;&lt;/tr&gt;';\n\n $counter++;\n }\n echo '&lt;/table&gt;';\n}\n</code></pre>\n\n<p><strong>Edit based on feedback from comment:</strong> This code skips the display of items where <code>$post_author-&gt;display_name === $last_user-&gt;display_name</code>. It's not the most efficient code though, since we're querying more items than needed. This is done because we'll skip some items and we want to (try) to ensure that there are at least 10 items to display (<code>$items_to_show</code> = 10).</p>\n" } ]
2016/11/20
[ "https://wordpress.stackexchange.com/questions/246834", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77283/" ]
I am trying to list the name of the moderators (users with editor role) that publish pending posts. I created a dashboard widget that shows the latest 10 published posts and the author, but I have problems getting the user that published it. I thought `the_modified_author` might be it, but I'm not sure if there's **a better way to tell who published the post?** Either way, my method isn't working. Here's my code so far: ``` function dashboard_widget_function() { $args = array( 'post_status' => 'publish', 'numberposts' => '10', 'post_type' => 'post'); $recent_posts = wp_get_recent_posts( $args ); echo '<table><tr>     <th>Post Title</th>     <th>Author</th>     <th>Moderated by</th></tr>'; foreach( $recent_posts as $recent ){ $post_author = get_user_by( 'id', $recent['post_author'] ); echo '<tr><td><a href="' . get_permalink($recent["ID"]) . '" title="Read: '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a></td>'; echo '<td>'. $post_author->display_name .'</td>'; echo '<td>'.get_the_modified_author().'</td></tr>'; } echo '</table>'; } ```
The reason that `get_the_modified_author()` is not working is that it relies on being used within the WordPress loop. `wp_get_recent_posts()` does not set up a global post object. Here is a complete example based on your original code that replaces `get_the_modified_author()` with some simple code to get the name of the last person who edited the post (which is essentially what `get_the_modified_author()` does): ``` /** * Add a widget to the dashboard. * * This function is hooked into the 'wp_dashboard_setup' action below. */ function example_add_dashboard_widgets() { wp_add_dashboard_widget( 'example_dashboard_widget', // Widget slug. 'Example Dashboard Widget', // Title. 'example_dashboard_widget_function' // Display function. ); } add_action( 'wp_dashboard_setup', 'example_add_dashboard_widgets' ); function example_dashboard_widget_function() { $items_to_show = 10; $counter = 0; $recent_posts = wp_get_recent_posts( [ 'post_status' => 'publish', 'numberposts' => '50', // More than we want, but tries to ensure we have enough items to display. 'post_type' => 'post' ] ); echo '<table> <tr> <th>Post Title</th> <th>Author</th> <th>Moderated by</th> </tr>'; foreach ( $recent_posts as $recent ) { $post_author = get_user_by( 'id', $recent['post_author'] ); $last_user_id = get_post_meta( $recent['ID'], '_edit_last', true ); $last_user = get_userdata( $last_user_id ); // Bail out of the loop if we've shown enough items. if ( $counter >= $items_to_show ) { break; } // Skip display of items where the author is the same as the moderator: if ( $post_author->display_name === $last_user->display_name ) { continue; } echo '<tr><td><a href="' . get_permalink( $recent['ID'] ) . '" title="Read: ' . esc_attr( $recent['post_title'] ).'" >' . $recent['post_title'].'</a></td>'; echo '<td>'. esc_html( $post_author->display_name ) .'</td>'; echo '<td>'. esc_html( $last_user->display_name ) .'</td></tr>'; $counter++; } echo '</table>'; } ``` **Edit based on feedback from comment:** This code skips the display of items where `$post_author->display_name === $last_user->display_name`. It's not the most efficient code though, since we're querying more items than needed. This is done because we'll skip some items and we want to (try) to ensure that there are at least 10 items to display (`$items_to_show` = 10).
246,859
<p>So I have a main domain site called: site.com and I recently bought wildcard SSL to try and get the main domain and all its sub-domains to be encrypted and be force all files to use https. After signing up for the service the certificate covers all domains like: *.site.com but all my subdomains have their own name like site2.com site3.com siteN.com etc. I can get https if i use site2.site.com but I need it to be site2.com with https. I've installed HTTPS plugin and if I put site2.site.com as the certificate root it works but the URL is then site2.site.com. Is there a way I can force https through site2.com? My .htaccess file for both main domains and sub-domains is:</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 SetEnvIfNoCase User-Agent "^libwww-perl*" block_bad_bots Deny from env=block_bad_bots </code></pre> <p><strong>EXTRA NOTE</strong>: I dont have access to the vhost files so I cant create virtual hosts</p>
[ { "answer_id": 246844, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>We could save the id of the user that last published a post, as the value of the <code>_wpse_user_last_published</code> post meta key, with:</p>\n\n<pre><code>add_action( 'transition_post_status', function( $new_status, $old_status, $post )\n{\n if( \n $new_status !== $old_status \n &amp;&amp; 'publish' === $new_status \n &amp;&amp; 'post' === get_post_type( $post ) \n )\n update_post_meta( $post-&gt;ID, '_wpse_user_last_published', get_current_user_id() );\n\n}, 10, 3 );\n</code></pre>\n\n<p>Then you could fetch this info when you list your posts.</p>\n\n<p>For more detail and faster search, it might be better to create a custom log table.</p>\n" }, { "answer_id": 246845, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<p>The reason that <code>get_the_modified_author()</code> is not working is that it relies on being used within the WordPress loop. <code>wp_get_recent_posts()</code> does not set up a global post object. Here is a complete example based on your original code that replaces <code>get_the_modified_author()</code> with some simple code to get the name of the last person who edited the post (which is essentially what <code>get_the_modified_author()</code> does):</p>\n\n<pre><code>/**\n * Add a widget to the dashboard.\n *\n * This function is hooked into the 'wp_dashboard_setup' action below.\n */\nfunction example_add_dashboard_widgets() {\n wp_add_dashboard_widget(\n 'example_dashboard_widget', // Widget slug.\n 'Example Dashboard Widget', // Title.\n 'example_dashboard_widget_function' // Display function.\n ); \n}\nadd_action( 'wp_dashboard_setup', 'example_add_dashboard_widgets' );\n\nfunction example_dashboard_widget_function() {\n $items_to_show = 10;\n $counter = 0;\n $recent_posts = wp_get_recent_posts( [\n 'post_status' =&gt; 'publish',\n 'numberposts' =&gt; '50', // More than we want, but tries to ensure we have enough items to display.\n 'post_type' =&gt; 'post'\n ] );\n\n echo '&lt;table&gt;\n &lt;tr&gt;\n &lt;th&gt;Post Title&lt;/th&gt;\n &lt;th&gt;Author&lt;/th&gt;\n &lt;th&gt;Moderated by&lt;/th&gt;\n &lt;/tr&gt;';\n\n foreach ( $recent_posts as $recent ) {\n $post_author = get_user_by( 'id', $recent['post_author'] );\n $last_user_id = get_post_meta( $recent['ID'], '_edit_last', true );\n $last_user = get_userdata( $last_user_id );\n\n // Bail out of the loop if we've shown enough items.\n if ( $counter &gt;= $items_to_show ) {\n break;\n }\n\n // Skip display of items where the author is the same as the moderator:\n if ( $post_author-&gt;display_name === $last_user-&gt;display_name ) {\n continue;\n }\n\n echo '&lt;tr&gt;&lt;td&gt;&lt;a href=\"' . get_permalink( $recent['ID'] ) . '\" title=\"Read: ' . \n esc_attr( $recent['post_title'] ).'\" &gt;' . $recent['post_title'].'&lt;/a&gt;&lt;/td&gt;';\n echo '&lt;td&gt;'. esc_html( $post_author-&gt;display_name ) .'&lt;/td&gt;';\n\n echo '&lt;td&gt;'. esc_html( $last_user-&gt;display_name ) .'&lt;/td&gt;&lt;/tr&gt;';\n\n $counter++;\n }\n echo '&lt;/table&gt;';\n}\n</code></pre>\n\n<p><strong>Edit based on feedback from comment:</strong> This code skips the display of items where <code>$post_author-&gt;display_name === $last_user-&gt;display_name</code>. It's not the most efficient code though, since we're querying more items than needed. This is done because we'll skip some items and we want to (try) to ensure that there are at least 10 items to display (<code>$items_to_show</code> = 10).</p>\n" } ]
2016/11/21
[ "https://wordpress.stackexchange.com/questions/246859", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93537/" ]
So I have a main domain site called: site.com and I recently bought wildcard SSL to try and get the main domain and all its sub-domains to be encrypted and be force all files to use https. After signing up for the service the certificate covers all domains like: \*.site.com but all my subdomains have their own name like site2.com site3.com siteN.com etc. I can get https if i use site2.site.com but I need it to be site2.com with https. I've installed HTTPS plugin and if I put site2.site.com as the certificate root it works but the URL is then site2.site.com. Is there a way I can force https through site2.com? My .htaccess file for both main domains and sub-domains is: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress SetEnvIfNoCase User-Agent "^libwww-perl*" block_bad_bots Deny from env=block_bad_bots ``` **EXTRA NOTE**: I dont have access to the vhost files so I cant create virtual hosts
The reason that `get_the_modified_author()` is not working is that it relies on being used within the WordPress loop. `wp_get_recent_posts()` does not set up a global post object. Here is a complete example based on your original code that replaces `get_the_modified_author()` with some simple code to get the name of the last person who edited the post (which is essentially what `get_the_modified_author()` does): ``` /** * Add a widget to the dashboard. * * This function is hooked into the 'wp_dashboard_setup' action below. */ function example_add_dashboard_widgets() { wp_add_dashboard_widget( 'example_dashboard_widget', // Widget slug. 'Example Dashboard Widget', // Title. 'example_dashboard_widget_function' // Display function. ); } add_action( 'wp_dashboard_setup', 'example_add_dashboard_widgets' ); function example_dashboard_widget_function() { $items_to_show = 10; $counter = 0; $recent_posts = wp_get_recent_posts( [ 'post_status' => 'publish', 'numberposts' => '50', // More than we want, but tries to ensure we have enough items to display. 'post_type' => 'post' ] ); echo '<table> <tr> <th>Post Title</th> <th>Author</th> <th>Moderated by</th> </tr>'; foreach ( $recent_posts as $recent ) { $post_author = get_user_by( 'id', $recent['post_author'] ); $last_user_id = get_post_meta( $recent['ID'], '_edit_last', true ); $last_user = get_userdata( $last_user_id ); // Bail out of the loop if we've shown enough items. if ( $counter >= $items_to_show ) { break; } // Skip display of items where the author is the same as the moderator: if ( $post_author->display_name === $last_user->display_name ) { continue; } echo '<tr><td><a href="' . get_permalink( $recent['ID'] ) . '" title="Read: ' . esc_attr( $recent['post_title'] ).'" >' . $recent['post_title'].'</a></td>'; echo '<td>'. esc_html( $post_author->display_name ) .'</td>'; echo '<td>'. esc_html( $last_user->display_name ) .'</td></tr>'; $counter++; } echo '</table>'; } ``` **Edit based on feedback from comment:** This code skips the display of items where `$post_author->display_name === $last_user->display_name`. It's not the most efficient code though, since we're querying more items than needed. This is done because we'll skip some items and we want to (try) to ensure that there are at least 10 items to display (`$items_to_show` = 10).
246,866
<p>I'm using <code>get_posts()</code> to fetch posts from a particular category to display at the top of my homepage, separate from the main homepage Loop. Everything seems to work fine, but for the title (returned through <code>the_title()</code>) which is always the same; the title of the first post fetched by <code>get_posts()</code>. <code>the_permalink()</code> does the same as well, but <code>the_excerpt()</code> returns the correct result for each post.</p> <p>Here's my code (I have removed only a few lines for fear I might inadvertently remove what is causing this problem):</p> <pre><code>$query = get_posts(array( 'numberposts'=&gt;-1, 'category'=&gt;3 )); $events = array(); if ($query) { foreach ($query as $tpost) { $fields = get_post_custom($tpost-&gt;ID); if (isset($fields['event_start'])) { $usetime = $fields['event_start'][0]; if (isset($fields['event_end'])) { $usetime = $fields['event_end'][0]; } if ($usetime&gt;time()) { $events[] = array("post"=&gt;$tpost,"fields"=&gt;$fields); } } } usort($events,function($a,$b){ $a = $a['fields']['event_start'][0]; $b = $b['fields']['event_start'][0]; if ($a==$b) { return 0; } return ($a &lt; $b) ? -1 : 1; }); } if (count($events)&gt;0) { ?&gt; &lt;div class="pad10 tac"&gt; &lt;h2 class="mar10"&gt;Upcoming Events&lt;/h2&gt; &lt;div class="tiles"&gt; &lt;?php foreach ($events as $event ) { ?&gt; &lt;?php setup_postdata( $event['post'] );?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" class='noshow'&gt; &lt;div class="tile smalltile"&gt;&lt;div id='post-&lt;?php the_ID(); ?&gt;'&gt; &lt;h2&gt;&lt;?php the_title();?&gt;&lt;/h2&gt; &lt;b&gt;&lt;?php echo(date_i18n("D, F j @ g:ia",$event['fields']['event_start'][0])); ?&gt;&lt;/b&gt; &lt;p&gt;&lt;?php the_excerpt();?&gt;&lt;/p&gt; &lt;/div&gt;&lt;/div&gt; &lt;/a&gt; &lt;?php }?&gt; &lt;/div&gt;&lt;/div&gt; &lt;?php }?&gt; </code></pre> <p>I'm really scratching my head on this, especially as this code is, for the most part, based off of the <code>get_posts()</code> example from <a href="https://premium.wpmudev.org/blog/creating-custom-queries-wordpress/" rel="nofollow noreferrer">this article</a>, where it is reportedly working fine.</p> <p>I'm thinking that this likely has something to do with my use of setup_postdata, but I suppose this is really just wild speculation.</p>
[ { "answer_id": 246874, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>Making Milos's comment into an answer....</p>\n\n<p>The problem you are facing is the result of many wordpress template oriented functions expect some global variables. In <code>WP_Query</code> based loops setting those variable is done by calling the <code>the_post()</code> method of the <code>WP_Query</code> object, but with <code>get_posts</code> you need to call <code>setup_postdata()</code> for that.</p>\n\n<p>My personal preference is to just try to avoid functions like <code>the_title</code> in favor of functions like <code>get_the_title</code>, that accept an explicit post id, whenever possible.</p>\n" }, { "answer_id": 398765, "author": "Santo Boldizar", "author_id": 203612, "author_profile": "https://wordpress.stackexchange.com/users/203612", "pm_score": 0, "selected": false, "text": "<p>Use <code>setup_postdata()</code> for that.</p>\n<p><strong>Important</strong> <code>setup_postdata()</code> does not assign the global <code>$post</code> variable so it’s important that you do this yourself.</p>\n<p><strong>Important</strong> use <code>wp_reset_postdata()</code> after your foreach loop.</p>\n<p>For more information visit:\n<a href=\"https://developer.wordpress.org/reference/functions/setup_postdata/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/setup_postdata/</a></p>\n<pre><code>&lt;?php\n // Get posts\n global $post;\n $posts = get_posts([\n 'post_type' =&gt; 'post',\n 'numberposts' =&gt; 6\n ]);\n?&gt;\n\n&lt;?php foreach ($posts as $key =&gt; $post): ?&gt;\n &lt;?php setup_postdata($post); ?&gt;\n &lt;h3&gt;\n &lt;a href=&quot;&lt;?php the_permalink(); ?&gt;&quot; title=&quot;&lt;?php the_title(); ?&gt;&quot;&gt;\n &lt;?php the_title(); ?&gt;\n &lt;/a&gt;\n &lt;/h3&gt;\n&lt;?php endforeach; ?&gt;\n&lt;?php wp_reset_postdata(); ?&gt;\n</code></pre>\n" } ]
2016/11/21
[ "https://wordpress.stackexchange.com/questions/246866", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107412/" ]
I'm using `get_posts()` to fetch posts from a particular category to display at the top of my homepage, separate from the main homepage Loop. Everything seems to work fine, but for the title (returned through `the_title()`) which is always the same; the title of the first post fetched by `get_posts()`. `the_permalink()` does the same as well, but `the_excerpt()` returns the correct result for each post. Here's my code (I have removed only a few lines for fear I might inadvertently remove what is causing this problem): ``` $query = get_posts(array( 'numberposts'=>-1, 'category'=>3 )); $events = array(); if ($query) { foreach ($query as $tpost) { $fields = get_post_custom($tpost->ID); if (isset($fields['event_start'])) { $usetime = $fields['event_start'][0]; if (isset($fields['event_end'])) { $usetime = $fields['event_end'][0]; } if ($usetime>time()) { $events[] = array("post"=>$tpost,"fields"=>$fields); } } } usort($events,function($a,$b){ $a = $a['fields']['event_start'][0]; $b = $b['fields']['event_start'][0]; if ($a==$b) { return 0; } return ($a < $b) ? -1 : 1; }); } if (count($events)>0) { ?> <div class="pad10 tac"> <h2 class="mar10">Upcoming Events</h2> <div class="tiles"> <?php foreach ($events as $event ) { ?> <?php setup_postdata( $event['post'] );?> <a href="<?php the_permalink(); ?>" class='noshow'> <div class="tile smalltile"><div id='post-<?php the_ID(); ?>'> <h2><?php the_title();?></h2> <b><?php echo(date_i18n("D, F j @ g:ia",$event['fields']['event_start'][0])); ?></b> <p><?php the_excerpt();?></p> </div></div> </a> <?php }?> </div></div> <?php }?> ``` I'm really scratching my head on this, especially as this code is, for the most part, based off of the `get_posts()` example from [this article](https://premium.wpmudev.org/blog/creating-custom-queries-wordpress/), where it is reportedly working fine. I'm thinking that this likely has something to do with my use of setup\_postdata, but I suppose this is really just wild speculation.
Making Milos's comment into an answer.... The problem you are facing is the result of many wordpress template oriented functions expect some global variables. In `WP_Query` based loops setting those variable is done by calling the `the_post()` method of the `WP_Query` object, but with `get_posts` you need to call `setup_postdata()` for that. My personal preference is to just try to avoid functions like `the_title` in favor of functions like `get_the_title`, that accept an explicit post id, whenever possible.
246,872
<p>I am setting up a transient with one hour expiry time. Now i want to know how much time left for the transient to expire.</p> <p>I am getting the transient timeout value with get_option function.</p> <p>Can anyone help me out.</p> <p>Thank You.</p>
[ { "answer_id": 246873, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>Transients by definition can expire at any moment, no matter what interval you have requested, therefor the \"time till expiry\" can not be reliably determined. you can hack something by inspecting the \"raw\" option, but it is a bad idea to relay on it.</p>\n" }, { "answer_id": 248254, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 2, "selected": false, "text": "<p>There is no built-in WordPress function to get the transient timeout. But you can use the following function to get the transient timeout.</p>\n\n<pre><code>function get_transient_timeout( $transient ) {\n global $wpdb;\n $transient_timeout = $wpdb-&gt;get_col( \"\n SELECT option_value\n FROM $wpdb-&gt;options\n WHERE option_name\n LIKE '%_transient_timeout_$transient%'\n \" );\n return $transient_timeout[0];\n}\n</code></pre>\n" }, { "answer_id": 367956, "author": "sMyles", "author_id": 51201, "author_profile": "https://wordpress.stackexchange.com/users/51201", "pm_score": 3, "selected": false, "text": "<p>The problem here is that if the site is actually using something like Redis, or any other supported \"external cache\" then nothing is going to actually be set in the options table (which can be checked with <code>wp_using_ext_object_cache</code>)</p>\n\n<p>Storage in the options table is just how WordPress handles transients outside of any external caching (or local object caching).</p>\n\n<p>With that said, to calculate the time remaining, you would do something like this:</p>\n\n<pre><code>$expires = (int) get_option( '_transient_timeout_MY_TRANSIENT_NAME', 0 );\n$time_left = $expires - time();\n</code></pre>\n\n<p>The value for expiration is calculated by adding <code>time()</code> to the value passed when setting the transient, so to get time left, just subtract <code>time()</code> from the value set for expiration</p>\n" } ]
2016/11/21
[ "https://wordpress.stackexchange.com/questions/246872", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107417/" ]
I am setting up a transient with one hour expiry time. Now i want to know how much time left for the transient to expire. I am getting the transient timeout value with get\_option function. Can anyone help me out. Thank You.
The problem here is that if the site is actually using something like Redis, or any other supported "external cache" then nothing is going to actually be set in the options table (which can be checked with `wp_using_ext_object_cache`) Storage in the options table is just how WordPress handles transients outside of any external caching (or local object caching). With that said, to calculate the time remaining, you would do something like this: ``` $expires = (int) get_option( '_transient_timeout_MY_TRANSIENT_NAME', 0 ); $time_left = $expires - time(); ``` The value for expiration is calculated by adding `time()` to the value passed when setting the transient, so to get time left, just subtract `time()` from the value set for expiration
246,885
<p>I've got three page templates called "Simple", "Front", and "Form" and I would like to add a shortcut in the admin side bar to directly create a page that would be associated with any of these templates. So below "Add new" there would be:</p> <p><a href="https://i.stack.imgur.com/6Hm8C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6Hm8C.png" alt="enter image description here"></a></p> <ul> <li>Add new Simple Page</li> <li>Add new Front Page</li> <li>Add new Form Page</li> </ul> <p>I've searched for it on Google but can't find any information. Is it possible to do this in WordPress?</p>
[ { "answer_id": 246890, "author": "GKS", "author_id": 90674, "author_profile": "https://wordpress.stackexchange.com/users/90674", "pm_score": 2, "selected": false, "text": "<p>I found this question very interesting ,So here is what i have done to make this possible. </p>\n\n<p>Fetch page template and add them as sub menu of Post type page.</p>\n\n<pre><code>function addTemplateAddNewSubMenu() {\n\n global $submenu;\n\n // here we are fetching all page template from current activated theme.\n $templates = wp_get_theme()-&gt;get_page_templates( 'page' );\n\n foreach ( $templates as $filename =&gt; $title ) {\n\n if ( $filename != 'default' &amp;&amp; $filename != '' ) {\n\n // add page-template filename as query string to add new page link.\n $url = 'post-new.php?post_type=page&amp;template=' . $filename;\n\n $submenu['edit.php?post_type=page'][] = array( 'Add new ' . $title , 'manage_options', $url );\n }\n }\n}\n\nadd_action( 'admin_menu', 'addTemplateAddNewSubMenu' );\n</code></pre>\n\n<p>I have added page template as query string to </p>\n\n<pre><code>/wp-admin/post-new.php?post_type=page&amp;template=template-contact.php\n</code></pre>\n\n<p>Making page template dropdown selected by jQuery and template Query string.</p>\n\n<pre><code>add_action( 'admin_head','selectPageTemplate' );\n\nfunction selectPageTemplate() {\n\n global $pagenow;\n\n if ( $pagenow == 'post-new.php' ) {\n\n if ( get_post_type() == 'page' &amp;&amp; isset($_GET['template']) ) {\n\n $template = $_GET['template']; ?&gt;\n\n &lt;script&gt;\n jQuery(function($){\n $('#page_template').val('&lt;?php echo $template;?&gt;');\n });\n &lt;/script&gt;\n\n &lt;?php\n }\n }\n\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/0OQEr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0OQEr.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 246892, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 0, "selected": false, "text": "<p>Here's an example how to set the page template, for new pages, through the custom <code>wpse_page_template</code> GET parameter:</p>\n\n<pre><code>https://examle.tld/wp-admin/post-new.php?post_type=page&amp;wpse_page_template=tpl-test.php\n</code></pre>\n\n<p>We can hook into the <code>save_post_page</code> hook and target the <em>auto-draft</em> status:</p>\n\n<pre><code>add_action( 'save_post_page', function ( $post_ID, $post, $update )\n{\n // Target 'auto-draft' status only\n if ( 'auto-draft' !== get_post_status( $post ) )\n return $post_ID;\n\n // User input\n $input_tpl = filter_input( INPUT_GET, 'wpse_page_template', FILTER_SANITIZE_STRING );\n $input_tpl = sanitize_file_name( $input_tpl );\n\n // Get current page templates\n $page_templates = wp_get_theme()-&gt;get_page_templates( $post );\n\n // Nothing to do if user tries a non a valid page template\n if ( ! isset( $page_templates[$input_tpl] ) )\n return $post_ID;\n\n // Update the user defined page template\n update_post_meta( $post_ID, '_wp_page_template', $input_tpl );\n\n return $post_ID;\n\n}, 10, 3 );\n</code></pre>\n\n<p>This approach could be extended for custom post types in WordPress 4.7+.</p>\n" } ]
2016/11/02
[ "https://wordpress.stackexchange.com/questions/246885", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8029/" ]
I've got three page templates called "Simple", "Front", and "Form" and I would like to add a shortcut in the admin side bar to directly create a page that would be associated with any of these templates. So below "Add new" there would be: [![enter image description here](https://i.stack.imgur.com/6Hm8C.png)](https://i.stack.imgur.com/6Hm8C.png) * Add new Simple Page * Add new Front Page * Add new Form Page I've searched for it on Google but can't find any information. Is it possible to do this in WordPress?
I found this question very interesting ,So here is what i have done to make this possible. Fetch page template and add them as sub menu of Post type page. ``` function addTemplateAddNewSubMenu() { global $submenu; // here we are fetching all page template from current activated theme. $templates = wp_get_theme()->get_page_templates( 'page' ); foreach ( $templates as $filename => $title ) { if ( $filename != 'default' && $filename != '' ) { // add page-template filename as query string to add new page link. $url = 'post-new.php?post_type=page&template=' . $filename; $submenu['edit.php?post_type=page'][] = array( 'Add new ' . $title , 'manage_options', $url ); } } } add_action( 'admin_menu', 'addTemplateAddNewSubMenu' ); ``` I have added page template as query string to ``` /wp-admin/post-new.php?post_type=page&template=template-contact.php ``` Making page template dropdown selected by jQuery and template Query string. ``` add_action( 'admin_head','selectPageTemplate' ); function selectPageTemplate() { global $pagenow; if ( $pagenow == 'post-new.php' ) { if ( get_post_type() == 'page' && isset($_GET['template']) ) { $template = $_GET['template']; ?> <script> jQuery(function($){ $('#page_template').val('<?php echo $template;?>'); }); </script> <?php } } } ``` [![enter image description here](https://i.stack.imgur.com/0OQEr.png)](https://i.stack.imgur.com/0OQEr.png)
246,899
<p>Here is a section of code that I have in a template file — to display sub-navigation if the page has child-pages:</p> <pre><code>&lt;?php // display sub-nav if page has children ?&gt; &lt;?php $children = get_pages(array('child_of' =&gt; $post-&gt;ID)); ?&gt; &lt;?php if (count($children)) : ?&gt; &lt;ul class="nav nav-tabs"&gt; &lt;?php foreach ($children as $val) : ?&gt; &lt;li role="presentation"&gt; &lt;a href="&lt;?php echo get_permalink($val-&gt;ID); ?&gt;"&gt;&lt;?php echo $val-&gt;post_title; ?&gt;&lt;/a&gt; &lt;/li&gt; &lt;?php endforeach; ?&gt; &lt;/ul&gt; </code></pre> <p>The code works fine when in the template file <code>page.php</code>, but if I put it all into a new file — <code>nav.php</code> and then include it with <code>&lt;?php get_template_part( 'include', 'nav' ); ?&gt;</code> then it stops working.</p> <p>How can I set it so that the <code>$post</code> variable still works? Do I need to do something with global variables?</p>
[ { "answer_id": 246905, "author": "GKS", "author_id": 90674, "author_profile": "https://wordpress.stackexchange.com/users/90674", "pm_score": 1, "selected": true, "text": "<p>is your file name is 'include-nav.php' or it is placed inside 'include' folder ? </p>\n\n<p>if not then simply call it by passing name of <strong>nav.php</strong> </p>\n\n<pre><code>&lt;?php get_template_part( 'nav' ); ?&gt;\n</code></pre>\n\n<p>you don't have to pass include keyword to call template. </p>\n\n<p>Hope this help :) </p>\n" }, { "answer_id": 246949, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 0, "selected": false, "text": "<p>Existing variables will be accessible from within the included template if you wrap <code>locate_template()</code> inside an <code>include</code> statement:</p>\n\n<pre><code>include( locate_template( 'nav.php' ) );\n</code></pre>\n" }, { "answer_id": 246954, "author": "JHoffmann", "author_id": 63847, "author_profile": "https://wordpress.stackexchange.com/users/63847", "pm_score": 1, "selected": false, "text": "<p><code>get_template_part()</code> calls your template file via <code>require()</code> but it does this inside of a function call. This means, it happens in a new variable scope. To make <code>$post</code> accessible again just use the <code>global</code> keyword.</p>\n\n<pre><code>&lt;?php \nglobal $post;\n$children = get_pages(array('child_of' =&gt; $post-&gt;ID)); \n?&gt;\n</code></pre>\n" } ]
2016/11/21
[ "https://wordpress.stackexchange.com/questions/246899", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
Here is a section of code that I have in a template file — to display sub-navigation if the page has child-pages: ``` <?php // display sub-nav if page has children ?> <?php $children = get_pages(array('child_of' => $post->ID)); ?> <?php if (count($children)) : ?> <ul class="nav nav-tabs"> <?php foreach ($children as $val) : ?> <li role="presentation"> <a href="<?php echo get_permalink($val->ID); ?>"><?php echo $val->post_title; ?></a> </li> <?php endforeach; ?> </ul> ``` The code works fine when in the template file `page.php`, but if I put it all into a new file — `nav.php` and then include it with `<?php get_template_part( 'include', 'nav' ); ?>` then it stops working. How can I set it so that the `$post` variable still works? Do I need to do something with global variables?
is your file name is 'include-nav.php' or it is placed inside 'include' folder ? if not then simply call it by passing name of **nav.php** ``` <?php get_template_part( 'nav' ); ?> ``` you don't have to pass include keyword to call template. Hope this help :)
246,914
<p>Am I using <code>add_action('init'</code> correctly?<br> I want to display some data if a user visits <code>example.com/?my_plugin</code></p> <p>At the moment I'm using...</p> <pre><code>&lt;?php add_action( 'init', 'my_plugin' ); function my_plugin() { if( isset( $_GET['my_plugin'] ) ) { ... echo $data; } } </code></pre> <p>This will run every time any page on the blog is loaded, as I understand it. Does that present a performance issue?</p> <p>Is there a better way I could accomplish this?</p>
[ { "answer_id": 246918, "author": "MD Sultan Nasir Uddin", "author_id": 86834, "author_profile": "https://wordpress.stackexchange.com/users/86834", "pm_score": 0, "selected": false, "text": "<p>init hook runs after WordPress has finished loading but before any headers are sent. </p>\n\n<p>if your action is not involving any complex query or not trying to call too many extra files then you don't need to be worried.</p>\n" }, { "answer_id": 246929, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 3, "selected": true, "text": "<p>Performance impact of hooked functionality is determined by how often hook fires and how intensive the operation is.</p>\n\n<p><code>init</code> only ever fires one per load, so multiple runs are not a factor for it.</p>\n\n<p>Mostly the thing you need to pay attention to is context. If your logic fires on every load and result is conditional the first thing it should do is determine if the context is the one you want. In all other cases that it the <em>only</em> thing it should do.</p>\n\n<p>As long as your context check is lightweight the performance impact should be perfectly insignificant.</p>\n\n<p>If your context check <em>is</em> heavy for some reason you might want to find a more specific hook (such as those in template loader logic) that would fire less and in more narrow circumstances. But for something as simple as example you made that won't be necessary.</p>\n" } ]
2016/11/21
[ "https://wordpress.stackexchange.com/questions/246914", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81576/" ]
Am I using `add_action('init'` correctly? I want to display some data if a user visits `example.com/?my_plugin` At the moment I'm using... ``` <?php add_action( 'init', 'my_plugin' ); function my_plugin() { if( isset( $_GET['my_plugin'] ) ) { ... echo $data; } } ``` This will run every time any page on the blog is loaded, as I understand it. Does that present a performance issue? Is there a better way I could accomplish this?
Performance impact of hooked functionality is determined by how often hook fires and how intensive the operation is. `init` only ever fires one per load, so multiple runs are not a factor for it. Mostly the thing you need to pay attention to is context. If your logic fires on every load and result is conditional the first thing it should do is determine if the context is the one you want. In all other cases that it the *only* thing it should do. As long as your context check is lightweight the performance impact should be perfectly insignificant. If your context check *is* heavy for some reason you might want to find a more specific hook (such as those in template loader logic) that would fire less and in more narrow circumstances. But for something as simple as example you made that won't be necessary.
246,946
<p>I have created a custom login page that uses wp_login_form() to create the login form:</p> <pre><code>&lt;div class="login-form"&gt; &lt;?php wp_login_form( array( 'remember' =&gt; false, 'label_username' =&gt; '', 'label_password' =&gt; '' ) ); ?&gt; &lt;/div&gt; </code></pre> <p>I tried to add a simple message to the login form using the default example from the WordPress Codex page about the <a href="https://codex.wordpress.org/Plugin_API/Action_Reference/login_form" rel="nofollow noreferrer">login form action hook</a>, like this:</p> <pre><code>add_action( 'login_form', function(){ //Adding the text ?&gt; &lt;p&gt;You can type a little note to those logging in here.&lt;/p&gt; &lt;?php }); </code></pre> <p>I literally copy-pasted the last code snippet from the Codex into my custom themes <em>functions.php</em>, to test if it's working.</p> <p>Now, when I open my custom login page, the text does not appear, but when I open the default login page, the text does appear.</p> <p>So, does wp_login_form() simply not use the login_form action hook or am I missing something?</p>
[ { "answer_id": 246918, "author": "MD Sultan Nasir Uddin", "author_id": 86834, "author_profile": "https://wordpress.stackexchange.com/users/86834", "pm_score": 0, "selected": false, "text": "<p>init hook runs after WordPress has finished loading but before any headers are sent. </p>\n\n<p>if your action is not involving any complex query or not trying to call too many extra files then you don't need to be worried.</p>\n" }, { "answer_id": 246929, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 3, "selected": true, "text": "<p>Performance impact of hooked functionality is determined by how often hook fires and how intensive the operation is.</p>\n\n<p><code>init</code> only ever fires one per load, so multiple runs are not a factor for it.</p>\n\n<p>Mostly the thing you need to pay attention to is context. If your logic fires on every load and result is conditional the first thing it should do is determine if the context is the one you want. In all other cases that it the <em>only</em> thing it should do.</p>\n\n<p>As long as your context check is lightweight the performance impact should be perfectly insignificant.</p>\n\n<p>If your context check <em>is</em> heavy for some reason you might want to find a more specific hook (such as those in template loader logic) that would fire less and in more narrow circumstances. But for something as simple as example you made that won't be necessary.</p>\n" } ]
2016/11/21
[ "https://wordpress.stackexchange.com/questions/246946", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107448/" ]
I have created a custom login page that uses wp\_login\_form() to create the login form: ``` <div class="login-form"> <?php wp_login_form( array( 'remember' => false, 'label_username' => '', 'label_password' => '' ) ); ?> </div> ``` I tried to add a simple message to the login form using the default example from the WordPress Codex page about the [login form action hook](https://codex.wordpress.org/Plugin_API/Action_Reference/login_form), like this: ``` add_action( 'login_form', function(){ //Adding the text ?> <p>You can type a little note to those logging in here.</p> <?php }); ``` I literally copy-pasted the last code snippet from the Codex into my custom themes *functions.php*, to test if it's working. Now, when I open my custom login page, the text does not appear, but when I open the default login page, the text does appear. So, does wp\_login\_form() simply not use the login\_form action hook or am I missing something?
Performance impact of hooked functionality is determined by how often hook fires and how intensive the operation is. `init` only ever fires one per load, so multiple runs are not a factor for it. Mostly the thing you need to pay attention to is context. If your logic fires on every load and result is conditional the first thing it should do is determine if the context is the one you want. In all other cases that it the *only* thing it should do. As long as your context check is lightweight the performance impact should be perfectly insignificant. If your context check *is* heavy for some reason you might want to find a more specific hook (such as those in template loader logic) that would fire less and in more narrow circumstances. But for something as simple as example you made that won't be necessary.
246,957
<p>I am trying to work out how to change details of a post after its status has changed.</p> <p>I would like to change the title of the post by appending the post id number to it. Here is the code that I'm working with now, but it doesn't change the post's title:</p> <pre><code>function update_post_info( $post_id, $post, $update ) { // Stop anything from happening if revision if ( wp_is_post_revision( $post_id ) ) return; //get post type $post_type = get_post_type($post_id); // If this isn't a custom post, don't update it. // if ( "cbre_access_form" != $post_type ) return; //run codes based on post status $post_status = get_post_status(); if ( $post_status != 'draft' ) { if ( isset( $_POST['post_title'] ) ) { //stuck on this part not changing post title $ppt = 'test title - '.$post_id; update_post_meta( $post_id, 'post_title', $ppt ); } } } add_action( 'save_post', 'update_post_info', 10, 3 ); </code></pre>
[ { "answer_id": 246965, "author": "Syed Fakhar Abbas", "author_id": 90591, "author_profile": "https://wordpress.stackexchange.com/users/90591", "pm_score": 0, "selected": false, "text": "<p><code>post_title</code> saved in the <code>posts</code> the table as <code>post_title</code> not in the post_meta; Also you have to remove the <code>save_post</code> hook and then add because <code>wp_update_post</code> results in save_post being fired and it will create the <a href=\"https://codex.wordpress.org/Function_Reference/wp_update_post#Caution_-_Infinite_loop\" rel=\"nofollow noreferrer\">infinite loop</a>.</p>\n\n<pre><code>\nfunction update_post_info( $post_id, $post, $update ) {\n\n// Stop anything from happening if revision\nif ( wp_is_post_revision( $post_id ) ) return;\n\n//get post type\n $post_type = get_post_type($post_id);\n\n// If this isn't a custom post, don't update it.\n// if ( \"cbre_access_form\" != $post_type ) return;\n\n //run codes based on post status\n $post_status = $post->post_status;\n if ( $post_status != 'draft' ) \n {\n if ( isset( $_POST['post_title'] ) ) {\n $my_post = array(\n 'ID' => $post_id,\n 'post_title' => $_POST['post_title'].' - '.$post_id,\n );\n if ( ! wp_is_post_revision( $post_id ) ) {\n\n // unhook this function so it doesn't loop infinitely\n remove_action('save_post', 'update_post_info');\n\n // update the post, which calls save_post again\n wp_update_post( $my_post );\n\n // re-hook this function\n add_action('save_post', 'update_post_info');\n }\n }\n }\n}\nadd_action( 'save_post', 'update_post_info', 10, 3 );\n\n\n</code></pre>\n" }, { "answer_id": 246966, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": true, "text": "<p>A post's title (<code>post_title</code>) is not saved in meta data; it's a field within the post table. </p>\n\n<p>Here's an updated version of your original code.</p>\n\n<ul>\n<li><p><a href=\"https://codex.wordpress.org/Function_Reference/wp_update_post\" rel=\"nofollow noreferrer\">Infinite loop is\nprevented</a>\nby removing and then readding the <code>wpse246957_update_post_info</code>\ncallback.</p></li>\n<li><p>Post title is successfully saved with the suffix <code>- $post_id</code> <a href=\"https://stackoverflow.com/a/1018803/3059883\">A\ncheck is in place</a> to\nprevent the suffix from being re-added if it has already been added.</p></li>\n</ul>\n\n<p><strong></strong></p>\n\n<pre><code>add_action( 'save_post', 'wpse246957_update_post_info', 10, 3 );\nfunction wpse246957_update_post_info( $post_id, $post, $update ) {\n\n // Stop anything from happening if revision\n if ( wp_is_post_revision( $post_id ) ) {\n return;\n }\n\n // unhook this function so it doesn't loop infinitely\n remove_action( 'save_post', 'wpse246957_update_post_info' );\n\n // get post type\n $post_type = get_post_type( $post_id );\n\n // If this isn't a custom post, don't update it.\n // if ( \"cbre_access_form\" != $post_type ) return;\n\n // run codes based on post status\n $post_status = get_post_status();\n if ( $post_status != 'draft' ) {\n if ( isset( $_POST['post_title'] ) ) {\n\n $suffix = ' - ' . $post_id;\n if ( ! preg_match( '/' . preg_quote( $suffix, '/' ) . '$/', $_POST['post_title'] ) ) {\n wp_update_post( [\n \"ID\" =&gt; $post_id,\n \"post_title\" =&gt; $_POST['post_title'] . $suffix,\n ] ); \n }\n }\n }\n\n // re-hook this function\n add_action( 'save_post', 'wpse246957_update_post_info', 10, 3 );\n}\n</code></pre>\n\n<p>Personally, I'd probably append the suffix before outputting the title in your template file or wherever you are outputting the title because there could be some edge case with the approach above when it comes to re-saving the post title.</p>\n" } ]
2016/11/21
[ "https://wordpress.stackexchange.com/questions/246957", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84968/" ]
I am trying to work out how to change details of a post after its status has changed. I would like to change the title of the post by appending the post id number to it. Here is the code that I'm working with now, but it doesn't change the post's title: ``` function update_post_info( $post_id, $post, $update ) { // Stop anything from happening if revision if ( wp_is_post_revision( $post_id ) ) return; //get post type $post_type = get_post_type($post_id); // If this isn't a custom post, don't update it. // if ( "cbre_access_form" != $post_type ) return; //run codes based on post status $post_status = get_post_status(); if ( $post_status != 'draft' ) { if ( isset( $_POST['post_title'] ) ) { //stuck on this part not changing post title $ppt = 'test title - '.$post_id; update_post_meta( $post_id, 'post_title', $ppt ); } } } add_action( 'save_post', 'update_post_info', 10, 3 ); ```
A post's title (`post_title`) is not saved in meta data; it's a field within the post table. Here's an updated version of your original code. * [Infinite loop is prevented](https://codex.wordpress.org/Function_Reference/wp_update_post) by removing and then readding the `wpse246957_update_post_info` callback. * Post title is successfully saved with the suffix `- $post_id` [A check is in place](https://stackoverflow.com/a/1018803/3059883) to prevent the suffix from being re-added if it has already been added. ``` add_action( 'save_post', 'wpse246957_update_post_info', 10, 3 ); function wpse246957_update_post_info( $post_id, $post, $update ) { // Stop anything from happening if revision if ( wp_is_post_revision( $post_id ) ) { return; } // unhook this function so it doesn't loop infinitely remove_action( 'save_post', 'wpse246957_update_post_info' ); // get post type $post_type = get_post_type( $post_id ); // If this isn't a custom post, don't update it. // if ( "cbre_access_form" != $post_type ) return; // run codes based on post status $post_status = get_post_status(); if ( $post_status != 'draft' ) { if ( isset( $_POST['post_title'] ) ) { $suffix = ' - ' . $post_id; if ( ! preg_match( '/' . preg_quote( $suffix, '/' ) . '$/', $_POST['post_title'] ) ) { wp_update_post( [ "ID" => $post_id, "post_title" => $_POST['post_title'] . $suffix, ] ); } } } // re-hook this function add_action( 'save_post', 'wpse246957_update_post_info', 10, 3 ); } ``` Personally, I'd probably append the suffix before outputting the title in your template file or wherever you are outputting the title because there could be some edge case with the approach above when it comes to re-saving the post title.
246,963
<p>I'm looking around and see some hints at what I'm wanting to do may be possible, but it's just not clicking for me.</p> <p>I have a custom post type rt_doctors. I'm trying to make it so there will be a dynamic list of the doctors in my main menu. </p> <p>I'd like to have in the Nav Menu a menu item doctors that links to the index/archive page of my doctors Custom Post Type, and hanging from this Menu Item, a list of Submenu Items each linking to a single post of the doctors themselves.</p> <p>It looks like i may need to use a custom walker, but i don't seem to understand it.</p> <p>here is the code i added just as a test: (I created a page called Products2 because my cpt is making products as the archive page. I've tried with just Products as well (I have that page created from before the cpt was made also)</p> <pre><code>class Walker_rt_Submenu extends Walker_Nav_Menu { function end_el(&amp;$output, $item, $depth=0, $args=array()) { if( 'Products2' == $item-&gt;title ){ $output .= '&lt;ul&gt;&lt;li&gt;Dynamic Subnav&lt;/li&gt;&lt;/ul&gt;'; } $output .= "&lt;/li&gt;\n"; } } wp_nav_menu( array( 'theme_location' =&gt; 'primary', 'walker' =&gt; new Walker_rt_Submenu ) ); </code></pre> <p>but i get this error:</p> <pre><code>Call to a member function get_page_permastruct() on null in /home/randomnoises/public_html/wp-includes/link-template.php on line 355 </code></pre> <p>I'm just using twenty sixteen as the theme for testing.</p>
[ { "answer_id": 247650, "author": "Dan.", "author_id": 97196, "author_profile": "https://wordpress.stackexchange.com/users/97196", "pm_score": 3, "selected": true, "text": "<p><code>Walker_Nav_Menu</code> isn't what you would use for this.</p>\n\n<p>Instead, use the <code>wp_get_nav_menu_items</code> filter. Before we start, you need some way of allowing the code to identify which is the menu item/page that you wish to be the parent of the list of posts. You can do this with a CSS class - give the parent menu item a CSS class in admin panel, let's call it 'doctors-parent-item'.</p>\n\n<pre><code>add_filter( 'wp_get_nav_menu_items', 'my_theme_doctors_menu_filter', 10, 3 );\n\nfunction my_theme_doctors_menu_filter( $items, $menu, $args ) {\n $child_items = array(); // here, we will add all items for the single posts\n $menu_order = count($items); // this is required, to make sure it doesn't push out other menu items\n $parent_item_id = 0; // we will use this variable to identify the parent menu item\n\n //First, we loop through all menu items to find the one we want to be the parent of the sub-menu with all the posts.\n foreach ( $items as $item ) {\n if ( in_array('doctors-parent-item', $item-&gt;classes) ){\n $parent_item_id = $item-&gt;ID;\n }\n }\n\n if($parent_item_id &gt; 0){\n\n foreach ( get_posts( 'post_type=rt_doctors&amp;numberposts=-1' ) as $post ) {\n $post-&gt;menu_item_parent = $parent_item_id;\n $post-&gt;post_type = 'nav_menu_item';\n $post-&gt;object = 'custom';\n $post-&gt;type = 'custom';\n $post-&gt;menu_order = ++$menu_order;\n $post-&gt;title = $post-&gt;post_title;\n $post-&gt;url = get_permalink( $post-&gt;ID );\n array_push($child_items, $post);\n }\n\n }\n\n return array_merge( $items, $child_items );\n}\n</code></pre>\n\n<p>Your menu will now dispaly all <code>rt_doctors</code>'s in a sub menu underneath the menu item that you gave the CSS class 'doctors-parent-item`</p>\n" }, { "answer_id": 413195, "author": "J May", "author_id": 78557, "author_profile": "https://wordpress.stackexchange.com/users/78557", "pm_score": 0, "selected": false, "text": "<p>To add a few things to Dan's excellent answer that may not be obvious to some:</p>\n<ol>\n<li>You need to turn on the ability to add CSS classes to Wordpress menu item in the &quot;Screen Options&quot; menu in the top right after navigating to Appearance-&gt;Menus. Then you will be able to add your chosen class name to the menu item(s) in question.</li>\n<li>You can add separate post types to respective menu items by simply creating unique ID vars for each and using conditionals:</li>\n</ol>\n<pre><code>add_filter( 'wp_get_nav_menu_items', 'wpse246963_add_cpt_to_menu', 10, 3 );\n\nfunction wpse246963_add_cpt_to_menu( $items, $menu, $args ) {\n $child_items = array(); // here, we will add all items for the single posts\n $menu_order = count($items); // this is required, to make sure it doesn't push out other menu items\n $doctors_parent_item_id = 0; // we will use this variable to identify the parent menu item\n $locations_parent_item_id = 0; // we will use this variable to identify the parent menu item\n\n //First, we loop through all menu items to find the one we want to be the parent of the sub-menu with all the posts.\n foreach ( $items as $item ) {\n if ( in_array('doctors-parent-item', $item-&gt;classes) ){\n $doctors_parent_item_id = $item-&gt;ID;\n } \n\n if ( in_array('locations-parent-item', $item-&gt;classes) ){\n $locations_parent_item_id = $item-&gt;ID;\n }\n }\n\n if ($doctors_parent_item_id &gt; 0) {\n\n foreach ( get_posts( 'post_type=rt-doctors&amp;numberposts=-1' ) as $post ) {\n $post-&gt;menu_item_parent = $doctors_parent_item_id;\n $post-&gt;post_type = 'nav_menu_item';\n $post-&gt;object = 'custom';\n $post-&gt;type = 'custom';\n $post-&gt;menu_order = ++$menu_order;\n $post-&gt;title = $post-&gt;post_title;\n $post-&gt;url = get_permalink( $post-&gt;ID );\n array_push($child_items, $post);\n }\n\n } \n\n if ($locations_parent_item_id &gt; 0) {\n\n foreach ( get_posts( 'post_type=rt-locations&amp;numberposts=-1' ) as $post ) {\n $post-&gt;menu_item_parent = $locations_parent_item_id;\n $post-&gt;post_type = 'nav_menu_item';\n $post-&gt;object = 'custom';\n $post-&gt;type = 'custom';\n $post-&gt;menu_order = ++$menu_order;\n $post-&gt;title = $post-&gt;post_title;\n $post-&gt;url = get_permalink( $post-&gt;ID );\n array_push($child_items, $post);\n }\n\n }\n\n return array_merge( $items, $child_items );\n}\n</code></pre>\n" } ]
2016/11/21
[ "https://wordpress.stackexchange.com/questions/246963", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77767/" ]
I'm looking around and see some hints at what I'm wanting to do may be possible, but it's just not clicking for me. I have a custom post type rt\_doctors. I'm trying to make it so there will be a dynamic list of the doctors in my main menu. I'd like to have in the Nav Menu a menu item doctors that links to the index/archive page of my doctors Custom Post Type, and hanging from this Menu Item, a list of Submenu Items each linking to a single post of the doctors themselves. It looks like i may need to use a custom walker, but i don't seem to understand it. here is the code i added just as a test: (I created a page called Products2 because my cpt is making products as the archive page. I've tried with just Products as well (I have that page created from before the cpt was made also) ``` class Walker_rt_Submenu extends Walker_Nav_Menu { function end_el(&$output, $item, $depth=0, $args=array()) { if( 'Products2' == $item->title ){ $output .= '<ul><li>Dynamic Subnav</li></ul>'; } $output .= "</li>\n"; } } wp_nav_menu( array( 'theme_location' => 'primary', 'walker' => new Walker_rt_Submenu ) ); ``` but i get this error: ``` Call to a member function get_page_permastruct() on null in /home/randomnoises/public_html/wp-includes/link-template.php on line 355 ``` I'm just using twenty sixteen as the theme for testing.
`Walker_Nav_Menu` isn't what you would use for this. Instead, use the `wp_get_nav_menu_items` filter. Before we start, you need some way of allowing the code to identify which is the menu item/page that you wish to be the parent of the list of posts. You can do this with a CSS class - give the parent menu item a CSS class in admin panel, let's call it 'doctors-parent-item'. ``` add_filter( 'wp_get_nav_menu_items', 'my_theme_doctors_menu_filter', 10, 3 ); function my_theme_doctors_menu_filter( $items, $menu, $args ) { $child_items = array(); // here, we will add all items for the single posts $menu_order = count($items); // this is required, to make sure it doesn't push out other menu items $parent_item_id = 0; // we will use this variable to identify the parent menu item //First, we loop through all menu items to find the one we want to be the parent of the sub-menu with all the posts. foreach ( $items as $item ) { if ( in_array('doctors-parent-item', $item->classes) ){ $parent_item_id = $item->ID; } } if($parent_item_id > 0){ foreach ( get_posts( 'post_type=rt_doctors&numberposts=-1' ) as $post ) { $post->menu_item_parent = $parent_item_id; $post->post_type = 'nav_menu_item'; $post->object = 'custom'; $post->type = 'custom'; $post->menu_order = ++$menu_order; $post->title = $post->post_title; $post->url = get_permalink( $post->ID ); array_push($child_items, $post); } } return array_merge( $items, $child_items ); } ``` Your menu will now dispaly all `rt_doctors`'s in a sub menu underneath the menu item that you gave the CSS class 'doctors-parent-item`
246,967
<p>I have 3 separate sites/installs on the same server and they all use the same database:</p> <ul> <li>xxxx.com/en</li> <li>xxxx.com/de</li> <li>xxxx.com/es</li> </ul> <p>I want a <code>&lt;div&gt;</code> from a specific site in <code>xxxx.com/en</code> to appear on the other sites. Let's say I have <code>&lt;div id="table1"&gt;xxxx&lt;div&gt;</code> on <code>xxxx.com/en/page1</code>; I want this to show on <code>xxxx.com/de/page1</code>.</p> <p>I did not think this would be so complicated in WordPress. With plain PHP, it would be just an include, but WordPress is a closed system. So, how can I do this? </p>
[ { "answer_id": 247650, "author": "Dan.", "author_id": 97196, "author_profile": "https://wordpress.stackexchange.com/users/97196", "pm_score": 3, "selected": true, "text": "<p><code>Walker_Nav_Menu</code> isn't what you would use for this.</p>\n\n<p>Instead, use the <code>wp_get_nav_menu_items</code> filter. Before we start, you need some way of allowing the code to identify which is the menu item/page that you wish to be the parent of the list of posts. You can do this with a CSS class - give the parent menu item a CSS class in admin panel, let's call it 'doctors-parent-item'.</p>\n\n<pre><code>add_filter( 'wp_get_nav_menu_items', 'my_theme_doctors_menu_filter', 10, 3 );\n\nfunction my_theme_doctors_menu_filter( $items, $menu, $args ) {\n $child_items = array(); // here, we will add all items for the single posts\n $menu_order = count($items); // this is required, to make sure it doesn't push out other menu items\n $parent_item_id = 0; // we will use this variable to identify the parent menu item\n\n //First, we loop through all menu items to find the one we want to be the parent of the sub-menu with all the posts.\n foreach ( $items as $item ) {\n if ( in_array('doctors-parent-item', $item-&gt;classes) ){\n $parent_item_id = $item-&gt;ID;\n }\n }\n\n if($parent_item_id &gt; 0){\n\n foreach ( get_posts( 'post_type=rt_doctors&amp;numberposts=-1' ) as $post ) {\n $post-&gt;menu_item_parent = $parent_item_id;\n $post-&gt;post_type = 'nav_menu_item';\n $post-&gt;object = 'custom';\n $post-&gt;type = 'custom';\n $post-&gt;menu_order = ++$menu_order;\n $post-&gt;title = $post-&gt;post_title;\n $post-&gt;url = get_permalink( $post-&gt;ID );\n array_push($child_items, $post);\n }\n\n }\n\n return array_merge( $items, $child_items );\n}\n</code></pre>\n\n<p>Your menu will now dispaly all <code>rt_doctors</code>'s in a sub menu underneath the menu item that you gave the CSS class 'doctors-parent-item`</p>\n" }, { "answer_id": 413195, "author": "J May", "author_id": 78557, "author_profile": "https://wordpress.stackexchange.com/users/78557", "pm_score": 0, "selected": false, "text": "<p>To add a few things to Dan's excellent answer that may not be obvious to some:</p>\n<ol>\n<li>You need to turn on the ability to add CSS classes to Wordpress menu item in the &quot;Screen Options&quot; menu in the top right after navigating to Appearance-&gt;Menus. Then you will be able to add your chosen class name to the menu item(s) in question.</li>\n<li>You can add separate post types to respective menu items by simply creating unique ID vars for each and using conditionals:</li>\n</ol>\n<pre><code>add_filter( 'wp_get_nav_menu_items', 'wpse246963_add_cpt_to_menu', 10, 3 );\n\nfunction wpse246963_add_cpt_to_menu( $items, $menu, $args ) {\n $child_items = array(); // here, we will add all items for the single posts\n $menu_order = count($items); // this is required, to make sure it doesn't push out other menu items\n $doctors_parent_item_id = 0; // we will use this variable to identify the parent menu item\n $locations_parent_item_id = 0; // we will use this variable to identify the parent menu item\n\n //First, we loop through all menu items to find the one we want to be the parent of the sub-menu with all the posts.\n foreach ( $items as $item ) {\n if ( in_array('doctors-parent-item', $item-&gt;classes) ){\n $doctors_parent_item_id = $item-&gt;ID;\n } \n\n if ( in_array('locations-parent-item', $item-&gt;classes) ){\n $locations_parent_item_id = $item-&gt;ID;\n }\n }\n\n if ($doctors_parent_item_id &gt; 0) {\n\n foreach ( get_posts( 'post_type=rt-doctors&amp;numberposts=-1' ) as $post ) {\n $post-&gt;menu_item_parent = $doctors_parent_item_id;\n $post-&gt;post_type = 'nav_menu_item';\n $post-&gt;object = 'custom';\n $post-&gt;type = 'custom';\n $post-&gt;menu_order = ++$menu_order;\n $post-&gt;title = $post-&gt;post_title;\n $post-&gt;url = get_permalink( $post-&gt;ID );\n array_push($child_items, $post);\n }\n\n } \n\n if ($locations_parent_item_id &gt; 0) {\n\n foreach ( get_posts( 'post_type=rt-locations&amp;numberposts=-1' ) as $post ) {\n $post-&gt;menu_item_parent = $locations_parent_item_id;\n $post-&gt;post_type = 'nav_menu_item';\n $post-&gt;object = 'custom';\n $post-&gt;type = 'custom';\n $post-&gt;menu_order = ++$menu_order;\n $post-&gt;title = $post-&gt;post_title;\n $post-&gt;url = get_permalink( $post-&gt;ID );\n array_push($child_items, $post);\n }\n\n }\n\n return array_merge( $items, $child_items );\n}\n</code></pre>\n" } ]
2016/11/21
[ "https://wordpress.stackexchange.com/questions/246967", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107478/" ]
I have 3 separate sites/installs on the same server and they all use the same database: * xxxx.com/en * xxxx.com/de * xxxx.com/es I want a `<div>` from a specific site in `xxxx.com/en` to appear on the other sites. Let's say I have `<div id="table1">xxxx<div>` on `xxxx.com/en/page1`; I want this to show on `xxxx.com/de/page1`. I did not think this would be so complicated in WordPress. With plain PHP, it would be just an include, but WordPress is a closed system. So, how can I do this?
`Walker_Nav_Menu` isn't what you would use for this. Instead, use the `wp_get_nav_menu_items` filter. Before we start, you need some way of allowing the code to identify which is the menu item/page that you wish to be the parent of the list of posts. You can do this with a CSS class - give the parent menu item a CSS class in admin panel, let's call it 'doctors-parent-item'. ``` add_filter( 'wp_get_nav_menu_items', 'my_theme_doctors_menu_filter', 10, 3 ); function my_theme_doctors_menu_filter( $items, $menu, $args ) { $child_items = array(); // here, we will add all items for the single posts $menu_order = count($items); // this is required, to make sure it doesn't push out other menu items $parent_item_id = 0; // we will use this variable to identify the parent menu item //First, we loop through all menu items to find the one we want to be the parent of the sub-menu with all the posts. foreach ( $items as $item ) { if ( in_array('doctors-parent-item', $item->classes) ){ $parent_item_id = $item->ID; } } if($parent_item_id > 0){ foreach ( get_posts( 'post_type=rt_doctors&numberposts=-1' ) as $post ) { $post->menu_item_parent = $parent_item_id; $post->post_type = 'nav_menu_item'; $post->object = 'custom'; $post->type = 'custom'; $post->menu_order = ++$menu_order; $post->title = $post->post_title; $post->url = get_permalink( $post->ID ); array_push($child_items, $post); } } return array_merge( $items, $child_items ); } ``` Your menu will now dispaly all `rt_doctors`'s in a sub menu underneath the menu item that you gave the CSS class 'doctors-parent-item`
246,975
<p>I have a custom taxonomy called prod-cat</p> <p>I want to order the output in the template by number, so I added a term_meta to the taxonomy like this:</p> <pre><code>add_action( 'prod-cat_add_form_fields', 'add_feature_group_field', 10, 2 ); function add_feature_group_field($taxonomy) { ?&gt; &lt;div class="form-field term-order-wrap"&gt; &lt;label for="term-order"&gt;Order&lt;/label&gt; &lt;input type="text" name="wm-cat-prod-order" /&gt; &lt;/div&gt; &lt;?php } </code></pre> <p>And then:</p> <pre><code>add_action( 'created_prod-cat', 'save_feature_meta', 10, 2 ); function save_feature_meta( $term_id, $tt_id ){ if( isset( $_POST['wm-cat-prod-order'] ) &amp;&amp; '' !== $_POST['wm-cat-prod-order'] ){ add_term_meta( $term_id, 'wm-cat-prod-order', $_POST['wm-cat-prod-order'], true ); } } </code></pre> <p>I have the term_meta working, It's getting saved. Then in the template I do this: </p> <pre><code>$args = array( 'taxonomy' =&gt; 'categoria-de-productos', 'orderby' =&gt; 'wm-cat-prod-order', 'order' =&gt; 'ASC', 'hide_empty' =&gt; false, 'hierarchical' =&gt; false, 'parent' =&gt; 0, ); $terms = get_terms( $args ); </code></pre> <p>But I can't get it to orderby the "wm-cat-prod-order" meta. Anyone on this? Thanks</p>
[ { "answer_id": 246994, "author": "Fabian Marz", "author_id": 77421, "author_profile": "https://wordpress.stackexchange.com/users/77421", "pm_score": 5, "selected": true, "text": "<p><code>get_terms</code> supports a <code>meta_query</code> which calls a new <a href=\"https://codex.wordpress.org/Class_Reference/WP_Meta_Query\" rel=\"noreferrer\">WP_Meta_Query</a> parameter as you can see <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"noreferrer\">here</a>. To query your terms with your desired meta, you could change your function call to something like this:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$args = array(\n 'taxonomy' =&gt; 'categoria-de-productos',\n 'orderby' =&gt; 'meta_value_num',\n 'order' =&gt; 'ASC',\n 'hide_empty' =&gt; false,\n 'hierarchical' =&gt; false,\n 'parent' =&gt; 0,\n 'meta_query' =&gt; [[\n 'key' =&gt; 'wm-cat-prod-order',\n 'type' =&gt; 'NUMERIC',\n ]],\n);\n\n$terms = get_terms( $args );\n</code></pre>\n\n<p>This code is untested and may needs to be changed in your example. But the links should guide you to the solution.</p>\n" }, { "answer_id": 285541, "author": "Lucas Gabriel", "author_id": 27812, "author_profile": "https://wordpress.stackexchange.com/users/27812", "pm_score": 0, "selected": false, "text": "<p>for me, I made a custom taxonomy and in that custom taxonomy I had a custom meta. I wanted to have in the admin backend a column and made it sortable. to make sortable work for a custom taxonomy in a custom meta I did this.</p>\n\n<p><a href=\"https://pastebin.com/vr2sCKzX\" rel=\"nofollow noreferrer\">https://pastebin.com/vr2sCKzX</a></p>\n\n<pre><code>public function pre_get_terms( $query ) {\n$meta_query_args = array(\n 'relation' =&gt; 'AND', // Optional, defaults to \"AND\"\n array(\n 'key' =&gt; 'order_index',\n 'value' =&gt; 0,\n 'compare' =&gt; '&gt;='\n )\n);\n$meta_query = new WP_Meta_Query( $meta_query_args );\n$query-&gt;meta_query = $meta_query;\n$query-&gt;orderby = 'position_clause';\n</code></pre>\n\n<p>}\nI found the answer in this link <a href=\"https://core.trac.wordpress.org/ticket/34996\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/34996</a></p>\n\n<p>I just had to adapt the answer provided in the comments by @eherman24</p>\n" }, { "answer_id": 312815, "author": "Danilo Bruno", "author_id": 149619, "author_profile": "https://wordpress.stackexchange.com/users/149619", "pm_score": 2, "selected": false, "text": "<pre><code>$args = array(\n\n 'taxonomy' =&gt; 'MY_TAX',\n 'meta_key' =&gt; 'ordem',\n 'meta_compare' =&gt; 'NUMERIC',\n 'orderby' =&gt; 'meta_value_num',\n 'order' =&gt; 'ASC',\n 'hide_empty' =&gt; false,\n);\n\n$the_query = new WP_Term_Query($args);\n\nforeach ( $the_query-&gt;get_terms() as $term )\n{\n ...\n}\n</code></pre>\n" }, { "answer_id": 372979, "author": "AuRise", "author_id": 110134, "author_profile": "https://wordpress.stackexchange.com/users/110134", "pm_score": 2, "selected": false, "text": "<p>I was having a rough time with this as well, and I created my meta field with ACF. This is what I did to get it to work (removed some properties for brevity):</p>\n<pre><code>$args = array(\n 'taxonomy' =&gt; 'categoria-de-productos',\n 'order' =&gt; 'ASC',\n 'orderby' =&gt; 'meta_value_num',//Treat the meta value as numeric\n 'meta_key' =&gt; 'wm-cat-prod-order'//Meta key\n);\n$terms_query = new WP_Term_Query( $args );\nif( ! empty( $terms_query-&gt;terms ) ) {\n foreach( $terms_query-&gt;terms as $term ) {\n //Do stuff, $term is a WP_Term object\n }\n}\n</code></pre>\n<p>One of the things I usually do is define a fallback, like <code>'meta_value_num term_id'</code> to use <code>term_id</code> if the values for <code>wm-cat-prod-order</code> are all the same, but this broke it entirely and produced unexpected results. It <em>only</em> worked if <code>'meta_value_num'</code> was the only value for <code>orderby</code>.</p>\n" } ]
2016/11/22
[ "https://wordpress.stackexchange.com/questions/246975", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63523/" ]
I have a custom taxonomy called prod-cat I want to order the output in the template by number, so I added a term\_meta to the taxonomy like this: ``` add_action( 'prod-cat_add_form_fields', 'add_feature_group_field', 10, 2 ); function add_feature_group_field($taxonomy) { ?> <div class="form-field term-order-wrap"> <label for="term-order">Order</label> <input type="text" name="wm-cat-prod-order" /> </div> <?php } ``` And then: ``` add_action( 'created_prod-cat', 'save_feature_meta', 10, 2 ); function save_feature_meta( $term_id, $tt_id ){ if( isset( $_POST['wm-cat-prod-order'] ) && '' !== $_POST['wm-cat-prod-order'] ){ add_term_meta( $term_id, 'wm-cat-prod-order', $_POST['wm-cat-prod-order'], true ); } } ``` I have the term\_meta working, It's getting saved. Then in the template I do this: ``` $args = array( 'taxonomy' => 'categoria-de-productos', 'orderby' => 'wm-cat-prod-order', 'order' => 'ASC', 'hide_empty' => false, 'hierarchical' => false, 'parent' => 0, ); $terms = get_terms( $args ); ``` But I can't get it to orderby the "wm-cat-prod-order" meta. Anyone on this? Thanks
`get_terms` supports a `meta_query` which calls a new [WP\_Meta\_Query](https://codex.wordpress.org/Class_Reference/WP_Meta_Query) parameter as you can see [here](https://developer.wordpress.org/reference/functions/get_terms/). To query your terms with your desired meta, you could change your function call to something like this: ```php $args = array( 'taxonomy' => 'categoria-de-productos', 'orderby' => 'meta_value_num', 'order' => 'ASC', 'hide_empty' => false, 'hierarchical' => false, 'parent' => 0, 'meta_query' => [[ 'key' => 'wm-cat-prod-order', 'type' => 'NUMERIC', ]], ); $terms = get_terms( $args ); ``` This code is untested and may needs to be changed in your example. But the links should guide you to the solution.
246,987
<p>Been looking around on this website and the internet but can't seem to find a solution. My client wants every order which has the order status cancelled to be completely removed out of WooCommerce after an amount of time.</p> <pre><code>&lt;?php function update_order_status( $order_id ) { $order = new WC_Order( $order_id ); $order_status = $order-&gt;get_status(); if ('cancelled' == $order_status || 'failed' == $order_status || 'pending' == $order_status ) { wp_delete_post($order_id,true); } } </code></pre> <p>I currently have the above code snippet but I want this action to be delayed 5 minutes because pending orders could be still in payment.</p> <p>So TL;DR Orders with status 'cancelled', 'failed' &amp; 'pending' should be completely deleted after 5 minutes.</p> <p>Anyone who could help me out on this one?</p> <p>Best regards, Dylan</p>
[ { "answer_id": 246990, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Hmm... If we use your script, I think if you save the time like: </p>\n\n<pre><code>&lt;?php\nfunction update_order_status( $order_id ) {\n$order = new WC_Order( $order_id );\n$order_status = $order-&gt;get_status();\n\nif ('cancelled' == $order_status || 'failed' == $order_status || 'pending' == $order_status ) { \n $current_time = date('h:i:s'); /* this is not necessary - not being used. */\n\n sleep(300); // 300 seconds in 5 minutes\n\n wp_delete_post($order_id,true); \n } \n\n\n}\n</code></pre>\n\n<p>Look, I don't know if this will work, but it's worth a try. </p>\n" }, { "answer_id": 246991, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 0, "selected": false, "text": "<p>I think the user can can change the order status within five minutes. So I wrote the below code with hook-</p>\n\n<pre><code>add_action( 'woocommerce_order_status_failed', 'the_dramatist_woocommerce_auto_delete_order' );\nadd_action( 'woocommerce_order_status_pending', 'the_dramatist_woocommerce_auto_delete_order' );\nadd_action( 'woocommerce_order_status_cancelled', 'the_dramatist_woocommerce_auto_delete_order' );\n\nfunction the_dramatist_woocommerce_auto_delete_order( $order_id ) {\n // 5*60 = 300 seconds. Here 1minute = 60 seconds.\n wp_schedule_single_event(tim() + 300, 'the_dramatist_main_delete_event', $order_id);\n}\n\nfunction the_dramatist_main_delete_event( $order_id ) {\n global $woocommerce;\n $order = new WC_Order( $order_id );\n $order_status = $order-&gt;get_status();\n if ( !$order_id )\n return false;\n if ('cancelled' == $order_status || 'failed' == $order_status || 'pending' == $order_status ) {\n wp_delete_post($order_id,true);\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>Here we are detecting order status change by hook and checking the order status again after wake from sleep. So if the user change the order status with in five minutes then the delete will not occur. Please test it. I've not tested it. Hope that help you.</p>\n\n<blockquote>\n <p>P.S. I think <code>sleep()</code> function will cause some delay in the WordPress life cycle. So better we use <code>wp_schedule_single_event</code> function. So I updated my code.</p>\n</blockquote>\n" }, { "answer_id": 286615, "author": "Niket Joshi", "author_id": 122094, "author_profile": "https://wordpress.stackexchange.com/users/122094", "pm_score": 1, "selected": false, "text": "<p>do the following code in your child theme function.php file as given below.</p>\n\n<pre><code>function wc_remove_cancelled_status( $statuses ){\n if( isset( $statuses['wc-cancelled'] ) ){\n unset( $statuses['wc-cancelled'] );\n }\n return $statuses;\n} \nadd_filter( 'wc_order_statuses', 'wc_remove_cancelled_status' );\n</code></pre>\n" } ]
2016/11/22
[ "https://wordpress.stackexchange.com/questions/246987", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102035/" ]
Been looking around on this website and the internet but can't seem to find a solution. My client wants every order which has the order status cancelled to be completely removed out of WooCommerce after an amount of time. ``` <?php function update_order_status( $order_id ) { $order = new WC_Order( $order_id ); $order_status = $order->get_status(); if ('cancelled' == $order_status || 'failed' == $order_status || 'pending' == $order_status ) { wp_delete_post($order_id,true); } } ``` I currently have the above code snippet but I want this action to be delayed 5 minutes because pending orders could be still in payment. So TL;DR Orders with status 'cancelled', 'failed' & 'pending' should be completely deleted after 5 minutes. Anyone who could help me out on this one? Best regards, Dylan
do the following code in your child theme function.php file as given below. ``` function wc_remove_cancelled_status( $statuses ){ if( isset( $statuses['wc-cancelled'] ) ){ unset( $statuses['wc-cancelled'] ); } return $statuses; } add_filter( 'wc_order_statuses', 'wc_remove_cancelled_status' ); ```
247,002
<p>I want to edit the content before save to database for the first time only when add a new post, so i check the path if it's at the post-new.php i want to apply the filter, but it's not working. anyone know how to solve this ? </p> <pre><code>$pagePath = parse_url( $_SERVER['REQUEST_URI'] ); $pagePath = $pagePath['path']; $pagePath = substr($pagePath, 1); if($pagePath === 'wp-admin/post-new.php'){ function my_filter_function_name( $content ) { return $content . 'text before save to db'; } add_filter( 'content_save_pre', 'my_filter_function_name', 10, 1 ); } </code></pre>
[ { "answer_id": 246990, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Hmm... If we use your script, I think if you save the time like: </p>\n\n<pre><code>&lt;?php\nfunction update_order_status( $order_id ) {\n$order = new WC_Order( $order_id );\n$order_status = $order-&gt;get_status();\n\nif ('cancelled' == $order_status || 'failed' == $order_status || 'pending' == $order_status ) { \n $current_time = date('h:i:s'); /* this is not necessary - not being used. */\n\n sleep(300); // 300 seconds in 5 minutes\n\n wp_delete_post($order_id,true); \n } \n\n\n}\n</code></pre>\n\n<p>Look, I don't know if this will work, but it's worth a try. </p>\n" }, { "answer_id": 246991, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 0, "selected": false, "text": "<p>I think the user can can change the order status within five minutes. So I wrote the below code with hook-</p>\n\n<pre><code>add_action( 'woocommerce_order_status_failed', 'the_dramatist_woocommerce_auto_delete_order' );\nadd_action( 'woocommerce_order_status_pending', 'the_dramatist_woocommerce_auto_delete_order' );\nadd_action( 'woocommerce_order_status_cancelled', 'the_dramatist_woocommerce_auto_delete_order' );\n\nfunction the_dramatist_woocommerce_auto_delete_order( $order_id ) {\n // 5*60 = 300 seconds. Here 1minute = 60 seconds.\n wp_schedule_single_event(tim() + 300, 'the_dramatist_main_delete_event', $order_id);\n}\n\nfunction the_dramatist_main_delete_event( $order_id ) {\n global $woocommerce;\n $order = new WC_Order( $order_id );\n $order_status = $order-&gt;get_status();\n if ( !$order_id )\n return false;\n if ('cancelled' == $order_status || 'failed' == $order_status || 'pending' == $order_status ) {\n wp_delete_post($order_id,true);\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>Here we are detecting order status change by hook and checking the order status again after wake from sleep. So if the user change the order status with in five minutes then the delete will not occur. Please test it. I've not tested it. Hope that help you.</p>\n\n<blockquote>\n <p>P.S. I think <code>sleep()</code> function will cause some delay in the WordPress life cycle. So better we use <code>wp_schedule_single_event</code> function. So I updated my code.</p>\n</blockquote>\n" }, { "answer_id": 286615, "author": "Niket Joshi", "author_id": 122094, "author_profile": "https://wordpress.stackexchange.com/users/122094", "pm_score": 1, "selected": false, "text": "<p>do the following code in your child theme function.php file as given below.</p>\n\n<pre><code>function wc_remove_cancelled_status( $statuses ){\n if( isset( $statuses['wc-cancelled'] ) ){\n unset( $statuses['wc-cancelled'] );\n }\n return $statuses;\n} \nadd_filter( 'wc_order_statuses', 'wc_remove_cancelled_status' );\n</code></pre>\n" } ]
2016/11/22
[ "https://wordpress.stackexchange.com/questions/247002", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107171/" ]
I want to edit the content before save to database for the first time only when add a new post, so i check the path if it's at the post-new.php i want to apply the filter, but it's not working. anyone know how to solve this ? ``` $pagePath = parse_url( $_SERVER['REQUEST_URI'] ); $pagePath = $pagePath['path']; $pagePath = substr($pagePath, 1); if($pagePath === 'wp-admin/post-new.php'){ function my_filter_function_name( $content ) { return $content . 'text before save to db'; } add_filter( 'content_save_pre', 'my_filter_function_name', 10, 1 ); } ```
do the following code in your child theme function.php file as given below. ``` function wc_remove_cancelled_status( $statuses ){ if( isset( $statuses['wc-cancelled'] ) ){ unset( $statuses['wc-cancelled'] ); } return $statuses; } add_filter( 'wc_order_statuses', 'wc_remove_cancelled_status' ); ```
247,011
<p>I need to show in the each post his parent category and sub category, at the moment I use this code:</p> <pre><code>&lt;?php $categories = get_the_category(); echo 'Parent Category: &lt;a href="' . esc_url( get_category_link( $categories[0]-&gt;term_id ) ) . '"&gt;' . esc_html( $categories[0]-&gt;name ) . '&lt;/a&gt; \n'; echo 'Sub Category: &lt;a href="' . esc_url( get_category_link( $categories[1]-&gt;term_id ) ) . '"&gt;' . esc_html( $categories[1]-&gt;name ) . '&lt;/a&gt;'; ?&gt; </code></pre> <p>The problem is that this code gives categories[0] and categories[1] values based on their order. In some post the order is Parent -> Sub, in others is Sub -> Parent (don't know why). So when I access $categories[1] in some posts I get the parent instead of the sub.</p>
[ { "answer_id": 246990, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Hmm... If we use your script, I think if you save the time like: </p>\n\n<pre><code>&lt;?php\nfunction update_order_status( $order_id ) {\n$order = new WC_Order( $order_id );\n$order_status = $order-&gt;get_status();\n\nif ('cancelled' == $order_status || 'failed' == $order_status || 'pending' == $order_status ) { \n $current_time = date('h:i:s'); /* this is not necessary - not being used. */\n\n sleep(300); // 300 seconds in 5 minutes\n\n wp_delete_post($order_id,true); \n } \n\n\n}\n</code></pre>\n\n<p>Look, I don't know if this will work, but it's worth a try. </p>\n" }, { "answer_id": 246991, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 0, "selected": false, "text": "<p>I think the user can can change the order status within five minutes. So I wrote the below code with hook-</p>\n\n<pre><code>add_action( 'woocommerce_order_status_failed', 'the_dramatist_woocommerce_auto_delete_order' );\nadd_action( 'woocommerce_order_status_pending', 'the_dramatist_woocommerce_auto_delete_order' );\nadd_action( 'woocommerce_order_status_cancelled', 'the_dramatist_woocommerce_auto_delete_order' );\n\nfunction the_dramatist_woocommerce_auto_delete_order( $order_id ) {\n // 5*60 = 300 seconds. Here 1minute = 60 seconds.\n wp_schedule_single_event(tim() + 300, 'the_dramatist_main_delete_event', $order_id);\n}\n\nfunction the_dramatist_main_delete_event( $order_id ) {\n global $woocommerce;\n $order = new WC_Order( $order_id );\n $order_status = $order-&gt;get_status();\n if ( !$order_id )\n return false;\n if ('cancelled' == $order_status || 'failed' == $order_status || 'pending' == $order_status ) {\n wp_delete_post($order_id,true);\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>Here we are detecting order status change by hook and checking the order status again after wake from sleep. So if the user change the order status with in five minutes then the delete will not occur. Please test it. I've not tested it. Hope that help you.</p>\n\n<blockquote>\n <p>P.S. I think <code>sleep()</code> function will cause some delay in the WordPress life cycle. So better we use <code>wp_schedule_single_event</code> function. So I updated my code.</p>\n</blockquote>\n" }, { "answer_id": 286615, "author": "Niket Joshi", "author_id": 122094, "author_profile": "https://wordpress.stackexchange.com/users/122094", "pm_score": 1, "selected": false, "text": "<p>do the following code in your child theme function.php file as given below.</p>\n\n<pre><code>function wc_remove_cancelled_status( $statuses ){\n if( isset( $statuses['wc-cancelled'] ) ){\n unset( $statuses['wc-cancelled'] );\n }\n return $statuses;\n} \nadd_filter( 'wc_order_statuses', 'wc_remove_cancelled_status' );\n</code></pre>\n" } ]
2016/11/22
[ "https://wordpress.stackexchange.com/questions/247011", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107505/" ]
I need to show in the each post his parent category and sub category, at the moment I use this code: ``` <?php $categories = get_the_category(); echo 'Parent Category: <a href="' . esc_url( get_category_link( $categories[0]->term_id ) ) . '">' . esc_html( $categories[0]->name ) . '</a> \n'; echo 'Sub Category: <a href="' . esc_url( get_category_link( $categories[1]->term_id ) ) . '">' . esc_html( $categories[1]->name ) . '</a>'; ?> ``` The problem is that this code gives categories[0] and categories[1] values based on their order. In some post the order is Parent -> Sub, in others is Sub -> Parent (don't know why). So when I access $categories[1] in some posts I get the parent instead of the sub.
do the following code in your child theme function.php file as given below. ``` function wc_remove_cancelled_status( $statuses ){ if( isset( $statuses['wc-cancelled'] ) ){ unset( $statuses['wc-cancelled'] ); } return $statuses; } add_filter( 'wc_order_statuses', 'wc_remove_cancelled_status' ); ```
247,013
<p>I've generated three different custom post types (e.g. books, movies, games). I've also created a custom taxonomy for all of them (e.g. genre).</p> <p>What I need are archives for the taxonomy based on the post types. For example: "books-genre", "movies-genre"...</p> <p>Is there any solution to do that? Now I've only the taxonomy archive for "genre".</p>
[ { "answer_id": 247020, "author": "GKS", "author_id": 90674, "author_profile": "https://wordpress.stackexchange.com/users/90674", "pm_score": 0, "selected": false, "text": "<p>You can register taxonomy dynamically like this, </p>\n\n<pre><code>add_action('init',function(){\n\n $postType = array( 'books','movies','games' );\n\n foreach ( $postType as $k =&gt; $cpt ) {\n\n $tax_slug = strtolower( $cpt ) . '-genre';\n\n register_taxonomy(\n $tax_slug,\n strtolower( $cpt ),\n array(\n 'label' =&gt; 'Genre',\n 'rewrite' =&gt; array( 'slug' =&gt; $tax_slug ),\n 'hierarchical' =&gt; true,\n )\n );\n }\n});\n</code></pre>\n" }, { "answer_id": 247381, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 4, "selected": true, "text": "<p>Here is a complete example made possible using <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\" rel=\"noreferrer\"><code>add_rewrite_rule()</code></a>. The basic setup for this example is documented first, then we'll get to the real part of the solution using <code>add_rewrite_rule()</code>.</p>\n\n<h2>Taxonomy and Post Type registration</h2>\n\n<p>Register the <code>genre</code> taxonomy and the <code>book</code>, <code>movie</code>, and <code>game</code> post types <em>(note that the singular version of each of these names is being used in this example because it's considered a <a href=\"https://softwareengineering.stackexchange.com/questions/103720/classes-naming-singular-or-plural\">best practice</a>)</em>.</p>\n\n<pre><code>// Create taxonomy: genre for post types: book, movie, and game\n// https://codex.wordpress.org/Function_Reference/register_taxonomy\nadd_action( 'init', 'wpse247013_register_taxonomies', 0 );\nfunction wpse247013_register_taxonomies() {\n $args = [\n 'public' =&gt; true,\n 'hierarchical' =&gt; false,\n 'label' =&gt; __( 'Genres', 'textdomain' ),\n 'show_ui' =&gt; true,\n 'show_admin_column' =&gt; true,\n 'query_var' =&gt; 'genre',\n 'rewrite' =&gt; [ 'slug' =&gt; 'genres' ],\n ];\n\n register_taxonomy( 'genre', [ 'book', 'movie', 'game' ], $args );\n}\n\n// Create post types: movie, book, and game\n// https://developer.wordpress.org/reference/functions/register_post_type/\nadd_action( 'init', 'wpse247013_register_post_types' );\nfunction wpse247013_register_post_types() {\n $book_args = [\n 'label' =&gt; __( 'Books', 'textdomain' ),\n 'public' =&gt; true,\n 'publicly_queryable' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'query_var' =&gt; true,\n 'rewrite' =&gt; [ 'slug' =&gt; 'books' ],\n 'capability_type' =&gt; 'post',\n 'has_archive' =&gt; true,\n 'hierarchical' =&gt; false,\n 'menu_position' =&gt; null,\n 'supports' =&gt; [ 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ],\n 'taxonomies' =&gt; [ 'genre' ],\n ];\n register_post_type( 'book', $book_args );\n\n $movie_args = [\n 'label' =&gt; __( 'Movies', 'textdomain' ),\n 'public' =&gt; true,\n 'publicly_queryable' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'query_var' =&gt; true,\n 'rewrite' =&gt; [ 'slug' =&gt; 'movies' ],\n 'capability_type' =&gt; 'post',\n 'has_archive' =&gt; true,\n 'hierarchical' =&gt; false,\n 'menu_position' =&gt; null,\n 'supports' =&gt; [ 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ],\n 'taxonomies' =&gt; [ 'genre' ],\n ];\n register_post_type( 'movie', $movie_args );\n\n $game_args = [\n 'label' =&gt; __( 'Games', 'textdomain' ),\n 'public' =&gt; true,\n 'publicly_queryable' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'query_var' =&gt; true,\n 'rewrite' =&gt; [ 'slug' =&gt; 'games' ],\n 'capability_type' =&gt; 'post',\n 'has_archive' =&gt; true,\n 'hierarchical' =&gt; false,\n 'menu_position' =&gt; null,\n 'supports' =&gt; [ 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ],\n 'taxonomies' =&gt; [ 'genre' ],\n ];\n register_post_type( 'game', $game_args );\n}\n</code></pre>\n\n<h2>Basic URL Examples</h2>\n\n<blockquote>\n <p>Based on the setup above, we'll get these URLs out of the box:</p>\n \n <p><strong>Post type archive URLs</strong></p>\n \n <ul>\n <li><a href=\"http://example.com/books/\" rel=\"noreferrer\">http://example.com/books/</a></li>\n <li><a href=\"http://example.com/movies/\" rel=\"noreferrer\">http://example.com/movies/</a></li>\n <li><a href=\"http://example.com/games/\" rel=\"noreferrer\">http://example.com/games/</a></li>\n </ul>\n \n <p><strong>Single post type URLs</strong></p>\n \n <ul>\n <li><a href=\"http://example.com/books/\" rel=\"noreferrer\">http://example.com/books/</a>{book-post-slug}</li>\n <li><a href=\"http://example.com/movies/\" rel=\"noreferrer\">http://example.com/movies/</a>{movie-post-slug}</li>\n <li><a href=\"http://example.com/games/\" rel=\"noreferrer\">http://example.com/games/</a>{game-post-slug}</li>\n </ul>\n \n <p><strong>Taxonomy Term archive URLs</strong></p>\n \n <ul>\n <li><a href=\"http://example.com/genres/\" rel=\"noreferrer\">http://example.com/genres/</a>{genre-term-slug}\n <br><em>(this archive will include <strong>all</strong> post types, which is not what we're after)</em></li>\n </ul>\n</blockquote>\n\n<h2>Handle rewrite rules</h2>\n\n<p>Rewrite rules must be added in order to limit a particular genre term to a single post type. An additional rule is needed for pagination for each post type.</p>\n\n<pre><code>/**\n * Add rewrite rules for genre terms limited to book, movie, and game post types.\n * Pagination issue fix via http://wordpress.stackexchange.com/a/23155/2807\n * @link https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\n */\nfunction wpse247013_rewrite_rules() {\n // Book Genres\n add_rewrite_rule( '^books/book-genres/([^/]+)/?$',\n 'index.php?taxonomy=genre&amp;post_type=book&amp;term=$matches[1]', 'top' );\n\n // Book Genres pagination\n add_rewrite_rule( '^books/book-genres/([^/]+)/page/([0-9]+)?$',\n 'index.php?post_type=book&amp;genre=$matches[1]&amp;paged=$matches[2]', 'top' );\n\n // Movie Genres\n add_rewrite_rule( '^movies/movie-genres/([^/]+)/?$',\n 'index.php?taxonomy=genre&amp;post_type=movie&amp;term=$matches[1]', 'top' );\n\n // Movie Genres pagination\n add_rewrite_rule( '^movies/movie-genres/([^/]+)/page/([0-9]+)?$',\n 'index.php?post_type=movie&amp;genre=$matches[1]&amp;paged=$matches[2]', 'top' );\n\n // Game Genres\n add_rewrite_rule( '^games/game-genres/([^/]+)/?$',\n 'index.php?taxonomy=genre&amp;post_type=game&amp;term=$matches[1]', 'top' );\n\n // Game Genres pagination\n add_rewrite_rule( '^games/game-genres/([^/]+)/page/([0-9]+)?$',\n 'index.php?post_type=game&amp;genre=$matches[1]&amp;paged=$matches[2]', 'top' );\n}\nadd_action( 'init', 'wpse247013_rewrite_rules', 10, 0 );\n</code></pre>\n\n<p>Make sure to flush the rewrite rules by visiting <strong>Settings > Permalinks</strong> after adding this code to your plugin or theme. If you're using a plugin, you can flush the rules programmatically using <a href=\"https://codex.wordpress.org/Function_Reference/flush_rewrite_rules\" rel=\"noreferrer\">register_activation_hook</a>.</p>\n\n<h2>Custom URLs</h2>\n\n<blockquote>\n <p>The rewrite rules added above will enable the following new URLs:</p>\n \n <ul>\n <li><p><a href=\"http://example.com/books/book-genres/\" rel=\"noreferrer\">http://example.com/books/book-genres/</a>{genre-term-slug}\n <br>(<em>lists only books associated with the specified genre-term-slug )</em></p></li>\n <li><p><a href=\"http://example.com/movies/movie-genres/\" rel=\"noreferrer\">http://example.com/movies/movie-genres/</a>{genre-term-slug}\n <br><em>(lists only movies associated with the specified genre-term-slug )</em></p></li>\n <li><p><a href=\"http://example.com/games/game-genres/\" rel=\"noreferrer\">http://example.com/games/game-genres/</a>{genre-term-slug}\n <br><em>(lists only games associated with the specified genre-term-slug )</em></p></li>\n </ul>\n</blockquote>\n" } ]
2016/11/22
[ "https://wordpress.stackexchange.com/questions/247013", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/96806/" ]
I've generated three different custom post types (e.g. books, movies, games). I've also created a custom taxonomy for all of them (e.g. genre). What I need are archives for the taxonomy based on the post types. For example: "books-genre", "movies-genre"... Is there any solution to do that? Now I've only the taxonomy archive for "genre".
Here is a complete example made possible using [`add_rewrite_rule()`](https://codex.wordpress.org/Rewrite_API/add_rewrite_rule). The basic setup for this example is documented first, then we'll get to the real part of the solution using `add_rewrite_rule()`. Taxonomy and Post Type registration ----------------------------------- Register the `genre` taxonomy and the `book`, `movie`, and `game` post types *(note that the singular version of each of these names is being used in this example because it's considered a [best practice](https://softwareengineering.stackexchange.com/questions/103720/classes-naming-singular-or-plural))*. ``` // Create taxonomy: genre for post types: book, movie, and game // https://codex.wordpress.org/Function_Reference/register_taxonomy add_action( 'init', 'wpse247013_register_taxonomies', 0 ); function wpse247013_register_taxonomies() { $args = [ 'public' => true, 'hierarchical' => false, 'label' => __( 'Genres', 'textdomain' ), 'show_ui' => true, 'show_admin_column' => true, 'query_var' => 'genre', 'rewrite' => [ 'slug' => 'genres' ], ]; register_taxonomy( 'genre', [ 'book', 'movie', 'game' ], $args ); } // Create post types: movie, book, and game // https://developer.wordpress.org/reference/functions/register_post_type/ add_action( 'init', 'wpse247013_register_post_types' ); function wpse247013_register_post_types() { $book_args = [ 'label' => __( 'Books', 'textdomain' ), 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => [ 'slug' => 'books' ], 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => null, 'supports' => [ 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ], 'taxonomies' => [ 'genre' ], ]; register_post_type( 'book', $book_args ); $movie_args = [ 'label' => __( 'Movies', 'textdomain' ), 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => [ 'slug' => 'movies' ], 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => null, 'supports' => [ 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ], 'taxonomies' => [ 'genre' ], ]; register_post_type( 'movie', $movie_args ); $game_args = [ 'label' => __( 'Games', 'textdomain' ), 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => [ 'slug' => 'games' ], 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => null, 'supports' => [ 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ], 'taxonomies' => [ 'genre' ], ]; register_post_type( 'game', $game_args ); } ``` Basic URL Examples ------------------ > > Based on the setup above, we'll get these URLs out of the box: > > > **Post type archive URLs** > > > * <http://example.com/books/> > * <http://example.com/movies/> > * <http://example.com/games/> > > > **Single post type URLs** > > > * <http://example.com/books/>{book-post-slug} > * <http://example.com/movies/>{movie-post-slug} > * <http://example.com/games/>{game-post-slug} > > > **Taxonomy Term archive URLs** > > > * <http://example.com/genres/>{genre-term-slug} > > *(this archive will include **all** post types, which is not what we're after)* > > > Handle rewrite rules -------------------- Rewrite rules must be added in order to limit a particular genre term to a single post type. An additional rule is needed for pagination for each post type. ``` /** * Add rewrite rules for genre terms limited to book, movie, and game post types. * Pagination issue fix via http://wordpress.stackexchange.com/a/23155/2807 * @link https://codex.wordpress.org/Rewrite_API/add_rewrite_rule */ function wpse247013_rewrite_rules() { // Book Genres add_rewrite_rule( '^books/book-genres/([^/]+)/?$', 'index.php?taxonomy=genre&post_type=book&term=$matches[1]', 'top' ); // Book Genres pagination add_rewrite_rule( '^books/book-genres/([^/]+)/page/([0-9]+)?$', 'index.php?post_type=book&genre=$matches[1]&paged=$matches[2]', 'top' ); // Movie Genres add_rewrite_rule( '^movies/movie-genres/([^/]+)/?$', 'index.php?taxonomy=genre&post_type=movie&term=$matches[1]', 'top' ); // Movie Genres pagination add_rewrite_rule( '^movies/movie-genres/([^/]+)/page/([0-9]+)?$', 'index.php?post_type=movie&genre=$matches[1]&paged=$matches[2]', 'top' ); // Game Genres add_rewrite_rule( '^games/game-genres/([^/]+)/?$', 'index.php?taxonomy=genre&post_type=game&term=$matches[1]', 'top' ); // Game Genres pagination add_rewrite_rule( '^games/game-genres/([^/]+)/page/([0-9]+)?$', 'index.php?post_type=game&genre=$matches[1]&paged=$matches[2]', 'top' ); } add_action( 'init', 'wpse247013_rewrite_rules', 10, 0 ); ``` Make sure to flush the rewrite rules by visiting **Settings > Permalinks** after adding this code to your plugin or theme. If you're using a plugin, you can flush the rules programmatically using [register\_activation\_hook](https://codex.wordpress.org/Function_Reference/flush_rewrite_rules). Custom URLs ----------- > > The rewrite rules added above will enable the following new URLs: > > > * <http://example.com/books/book-genres/>{genre-term-slug} > > (*lists only books associated with the specified genre-term-slug )* > * <http://example.com/movies/movie-genres/>{genre-term-slug} > > *(lists only movies associated with the specified genre-term-slug )* > * <http://example.com/games/game-genres/>{genre-term-slug} > > *(lists only games associated with the specified genre-term-slug )* > > >
247,016
<p>I am trying to run string locator plugin to find some strings in my theme directory. but whenever i try to run this plugin, following error ocures "Warning The maximum time your server allows a script to run is too low for the plugin to run as intended, at startup 2 seconds have passed"</p> <p>I have tried to increase max exeecution time for script in php.ini by going to Xampp control panel click config> php.ini .... but nothing changed. is there any other way to make this plugin work? thanks!</p>
[ { "answer_id": 247020, "author": "GKS", "author_id": 90674, "author_profile": "https://wordpress.stackexchange.com/users/90674", "pm_score": 0, "selected": false, "text": "<p>You can register taxonomy dynamically like this, </p>\n\n<pre><code>add_action('init',function(){\n\n $postType = array( 'books','movies','games' );\n\n foreach ( $postType as $k =&gt; $cpt ) {\n\n $tax_slug = strtolower( $cpt ) . '-genre';\n\n register_taxonomy(\n $tax_slug,\n strtolower( $cpt ),\n array(\n 'label' =&gt; 'Genre',\n 'rewrite' =&gt; array( 'slug' =&gt; $tax_slug ),\n 'hierarchical' =&gt; true,\n )\n );\n }\n});\n</code></pre>\n" }, { "answer_id": 247381, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 4, "selected": true, "text": "<p>Here is a complete example made possible using <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\" rel=\"noreferrer\"><code>add_rewrite_rule()</code></a>. The basic setup for this example is documented first, then we'll get to the real part of the solution using <code>add_rewrite_rule()</code>.</p>\n\n<h2>Taxonomy and Post Type registration</h2>\n\n<p>Register the <code>genre</code> taxonomy and the <code>book</code>, <code>movie</code>, and <code>game</code> post types <em>(note that the singular version of each of these names is being used in this example because it's considered a <a href=\"https://softwareengineering.stackexchange.com/questions/103720/classes-naming-singular-or-plural\">best practice</a>)</em>.</p>\n\n<pre><code>// Create taxonomy: genre for post types: book, movie, and game\n// https://codex.wordpress.org/Function_Reference/register_taxonomy\nadd_action( 'init', 'wpse247013_register_taxonomies', 0 );\nfunction wpse247013_register_taxonomies() {\n $args = [\n 'public' =&gt; true,\n 'hierarchical' =&gt; false,\n 'label' =&gt; __( 'Genres', 'textdomain' ),\n 'show_ui' =&gt; true,\n 'show_admin_column' =&gt; true,\n 'query_var' =&gt; 'genre',\n 'rewrite' =&gt; [ 'slug' =&gt; 'genres' ],\n ];\n\n register_taxonomy( 'genre', [ 'book', 'movie', 'game' ], $args );\n}\n\n// Create post types: movie, book, and game\n// https://developer.wordpress.org/reference/functions/register_post_type/\nadd_action( 'init', 'wpse247013_register_post_types' );\nfunction wpse247013_register_post_types() {\n $book_args = [\n 'label' =&gt; __( 'Books', 'textdomain' ),\n 'public' =&gt; true,\n 'publicly_queryable' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'query_var' =&gt; true,\n 'rewrite' =&gt; [ 'slug' =&gt; 'books' ],\n 'capability_type' =&gt; 'post',\n 'has_archive' =&gt; true,\n 'hierarchical' =&gt; false,\n 'menu_position' =&gt; null,\n 'supports' =&gt; [ 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ],\n 'taxonomies' =&gt; [ 'genre' ],\n ];\n register_post_type( 'book', $book_args );\n\n $movie_args = [\n 'label' =&gt; __( 'Movies', 'textdomain' ),\n 'public' =&gt; true,\n 'publicly_queryable' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'query_var' =&gt; true,\n 'rewrite' =&gt; [ 'slug' =&gt; 'movies' ],\n 'capability_type' =&gt; 'post',\n 'has_archive' =&gt; true,\n 'hierarchical' =&gt; false,\n 'menu_position' =&gt; null,\n 'supports' =&gt; [ 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ],\n 'taxonomies' =&gt; [ 'genre' ],\n ];\n register_post_type( 'movie', $movie_args );\n\n $game_args = [\n 'label' =&gt; __( 'Games', 'textdomain' ),\n 'public' =&gt; true,\n 'publicly_queryable' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'query_var' =&gt; true,\n 'rewrite' =&gt; [ 'slug' =&gt; 'games' ],\n 'capability_type' =&gt; 'post',\n 'has_archive' =&gt; true,\n 'hierarchical' =&gt; false,\n 'menu_position' =&gt; null,\n 'supports' =&gt; [ 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ],\n 'taxonomies' =&gt; [ 'genre' ],\n ];\n register_post_type( 'game', $game_args );\n}\n</code></pre>\n\n<h2>Basic URL Examples</h2>\n\n<blockquote>\n <p>Based on the setup above, we'll get these URLs out of the box:</p>\n \n <p><strong>Post type archive URLs</strong></p>\n \n <ul>\n <li><a href=\"http://example.com/books/\" rel=\"noreferrer\">http://example.com/books/</a></li>\n <li><a href=\"http://example.com/movies/\" rel=\"noreferrer\">http://example.com/movies/</a></li>\n <li><a href=\"http://example.com/games/\" rel=\"noreferrer\">http://example.com/games/</a></li>\n </ul>\n \n <p><strong>Single post type URLs</strong></p>\n \n <ul>\n <li><a href=\"http://example.com/books/\" rel=\"noreferrer\">http://example.com/books/</a>{book-post-slug}</li>\n <li><a href=\"http://example.com/movies/\" rel=\"noreferrer\">http://example.com/movies/</a>{movie-post-slug}</li>\n <li><a href=\"http://example.com/games/\" rel=\"noreferrer\">http://example.com/games/</a>{game-post-slug}</li>\n </ul>\n \n <p><strong>Taxonomy Term archive URLs</strong></p>\n \n <ul>\n <li><a href=\"http://example.com/genres/\" rel=\"noreferrer\">http://example.com/genres/</a>{genre-term-slug}\n <br><em>(this archive will include <strong>all</strong> post types, which is not what we're after)</em></li>\n </ul>\n</blockquote>\n\n<h2>Handle rewrite rules</h2>\n\n<p>Rewrite rules must be added in order to limit a particular genre term to a single post type. An additional rule is needed for pagination for each post type.</p>\n\n<pre><code>/**\n * Add rewrite rules for genre terms limited to book, movie, and game post types.\n * Pagination issue fix via http://wordpress.stackexchange.com/a/23155/2807\n * @link https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\n */\nfunction wpse247013_rewrite_rules() {\n // Book Genres\n add_rewrite_rule( '^books/book-genres/([^/]+)/?$',\n 'index.php?taxonomy=genre&amp;post_type=book&amp;term=$matches[1]', 'top' );\n\n // Book Genres pagination\n add_rewrite_rule( '^books/book-genres/([^/]+)/page/([0-9]+)?$',\n 'index.php?post_type=book&amp;genre=$matches[1]&amp;paged=$matches[2]', 'top' );\n\n // Movie Genres\n add_rewrite_rule( '^movies/movie-genres/([^/]+)/?$',\n 'index.php?taxonomy=genre&amp;post_type=movie&amp;term=$matches[1]', 'top' );\n\n // Movie Genres pagination\n add_rewrite_rule( '^movies/movie-genres/([^/]+)/page/([0-9]+)?$',\n 'index.php?post_type=movie&amp;genre=$matches[1]&amp;paged=$matches[2]', 'top' );\n\n // Game Genres\n add_rewrite_rule( '^games/game-genres/([^/]+)/?$',\n 'index.php?taxonomy=genre&amp;post_type=game&amp;term=$matches[1]', 'top' );\n\n // Game Genres pagination\n add_rewrite_rule( '^games/game-genres/([^/]+)/page/([0-9]+)?$',\n 'index.php?post_type=game&amp;genre=$matches[1]&amp;paged=$matches[2]', 'top' );\n}\nadd_action( 'init', 'wpse247013_rewrite_rules', 10, 0 );\n</code></pre>\n\n<p>Make sure to flush the rewrite rules by visiting <strong>Settings > Permalinks</strong> after adding this code to your plugin or theme. If you're using a plugin, you can flush the rules programmatically using <a href=\"https://codex.wordpress.org/Function_Reference/flush_rewrite_rules\" rel=\"noreferrer\">register_activation_hook</a>.</p>\n\n<h2>Custom URLs</h2>\n\n<blockquote>\n <p>The rewrite rules added above will enable the following new URLs:</p>\n \n <ul>\n <li><p><a href=\"http://example.com/books/book-genres/\" rel=\"noreferrer\">http://example.com/books/book-genres/</a>{genre-term-slug}\n <br>(<em>lists only books associated with the specified genre-term-slug )</em></p></li>\n <li><p><a href=\"http://example.com/movies/movie-genres/\" rel=\"noreferrer\">http://example.com/movies/movie-genres/</a>{genre-term-slug}\n <br><em>(lists only movies associated with the specified genre-term-slug )</em></p></li>\n <li><p><a href=\"http://example.com/games/game-genres/\" rel=\"noreferrer\">http://example.com/games/game-genres/</a>{genre-term-slug}\n <br><em>(lists only games associated with the specified genre-term-slug )</em></p></li>\n </ul>\n</blockquote>\n" } ]
2016/11/22
[ "https://wordpress.stackexchange.com/questions/247016", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107270/" ]
I am trying to run string locator plugin to find some strings in my theme directory. but whenever i try to run this plugin, following error ocures "Warning The maximum time your server allows a script to run is too low for the plugin to run as intended, at startup 2 seconds have passed" I have tried to increase max exeecution time for script in php.ini by going to Xampp control panel click config> php.ini .... but nothing changed. is there any other way to make this plugin work? thanks!
Here is a complete example made possible using [`add_rewrite_rule()`](https://codex.wordpress.org/Rewrite_API/add_rewrite_rule). The basic setup for this example is documented first, then we'll get to the real part of the solution using `add_rewrite_rule()`. Taxonomy and Post Type registration ----------------------------------- Register the `genre` taxonomy and the `book`, `movie`, and `game` post types *(note that the singular version of each of these names is being used in this example because it's considered a [best practice](https://softwareengineering.stackexchange.com/questions/103720/classes-naming-singular-or-plural))*. ``` // Create taxonomy: genre for post types: book, movie, and game // https://codex.wordpress.org/Function_Reference/register_taxonomy add_action( 'init', 'wpse247013_register_taxonomies', 0 ); function wpse247013_register_taxonomies() { $args = [ 'public' => true, 'hierarchical' => false, 'label' => __( 'Genres', 'textdomain' ), 'show_ui' => true, 'show_admin_column' => true, 'query_var' => 'genre', 'rewrite' => [ 'slug' => 'genres' ], ]; register_taxonomy( 'genre', [ 'book', 'movie', 'game' ], $args ); } // Create post types: movie, book, and game // https://developer.wordpress.org/reference/functions/register_post_type/ add_action( 'init', 'wpse247013_register_post_types' ); function wpse247013_register_post_types() { $book_args = [ 'label' => __( 'Books', 'textdomain' ), 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => [ 'slug' => 'books' ], 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => null, 'supports' => [ 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ], 'taxonomies' => [ 'genre' ], ]; register_post_type( 'book', $book_args ); $movie_args = [ 'label' => __( 'Movies', 'textdomain' ), 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => [ 'slug' => 'movies' ], 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => null, 'supports' => [ 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ], 'taxonomies' => [ 'genre' ], ]; register_post_type( 'movie', $movie_args ); $game_args = [ 'label' => __( 'Games', 'textdomain' ), 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => [ 'slug' => 'games' ], 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => null, 'supports' => [ 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ], 'taxonomies' => [ 'genre' ], ]; register_post_type( 'game', $game_args ); } ``` Basic URL Examples ------------------ > > Based on the setup above, we'll get these URLs out of the box: > > > **Post type archive URLs** > > > * <http://example.com/books/> > * <http://example.com/movies/> > * <http://example.com/games/> > > > **Single post type URLs** > > > * <http://example.com/books/>{book-post-slug} > * <http://example.com/movies/>{movie-post-slug} > * <http://example.com/games/>{game-post-slug} > > > **Taxonomy Term archive URLs** > > > * <http://example.com/genres/>{genre-term-slug} > > *(this archive will include **all** post types, which is not what we're after)* > > > Handle rewrite rules -------------------- Rewrite rules must be added in order to limit a particular genre term to a single post type. An additional rule is needed for pagination for each post type. ``` /** * Add rewrite rules for genre terms limited to book, movie, and game post types. * Pagination issue fix via http://wordpress.stackexchange.com/a/23155/2807 * @link https://codex.wordpress.org/Rewrite_API/add_rewrite_rule */ function wpse247013_rewrite_rules() { // Book Genres add_rewrite_rule( '^books/book-genres/([^/]+)/?$', 'index.php?taxonomy=genre&post_type=book&term=$matches[1]', 'top' ); // Book Genres pagination add_rewrite_rule( '^books/book-genres/([^/]+)/page/([0-9]+)?$', 'index.php?post_type=book&genre=$matches[1]&paged=$matches[2]', 'top' ); // Movie Genres add_rewrite_rule( '^movies/movie-genres/([^/]+)/?$', 'index.php?taxonomy=genre&post_type=movie&term=$matches[1]', 'top' ); // Movie Genres pagination add_rewrite_rule( '^movies/movie-genres/([^/]+)/page/([0-9]+)?$', 'index.php?post_type=movie&genre=$matches[1]&paged=$matches[2]', 'top' ); // Game Genres add_rewrite_rule( '^games/game-genres/([^/]+)/?$', 'index.php?taxonomy=genre&post_type=game&term=$matches[1]', 'top' ); // Game Genres pagination add_rewrite_rule( '^games/game-genres/([^/]+)/page/([0-9]+)?$', 'index.php?post_type=game&genre=$matches[1]&paged=$matches[2]', 'top' ); } add_action( 'init', 'wpse247013_rewrite_rules', 10, 0 ); ``` Make sure to flush the rewrite rules by visiting **Settings > Permalinks** after adding this code to your plugin or theme. If you're using a plugin, you can flush the rules programmatically using [register\_activation\_hook](https://codex.wordpress.org/Function_Reference/flush_rewrite_rules). Custom URLs ----------- > > The rewrite rules added above will enable the following new URLs: > > > * <http://example.com/books/book-genres/>{genre-term-slug} > > (*lists only books associated with the specified genre-term-slug )* > * <http://example.com/movies/movie-genres/>{genre-term-slug} > > *(lists only movies associated with the specified genre-term-slug )* > * <http://example.com/games/game-genres/>{genre-term-slug} > > *(lists only games associated with the specified genre-term-slug )* > > >