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
209,363
<p>I don't understand why wordpress stores that kind of data: posts' content and pages' content, directly within the database instead of storing it in the filesystem and referencing them in the database with an URL/path. Could someone please explain it to me? </p> <p>--EDIT</p> <p>As far as I know storing raw images in within the database is a bad practice since it increments considerably the size of the DB unneededly, and that's fine because images aren't stored within the database (i think), so my question is about "Why text isn't treated the same way?" and "If you have a large amount of huge posts wouldn't it somehow encounter the limits of the database sooner or later?"</p>
[ { "answer_id": 209349, "author": "jas", "author_id": 80247, "author_profile": "https://wordpress.stackexchange.com/users/80247", "pm_score": 2, "selected": true, "text": "<pre><code>$tags = get_the_tags( $post-&gt;ID );\n$separator = ' ';\n$output = '';\nif($tags){\necho '&lt;div class=\"entry-tags\"&gt;';\n echo \"&lt;p&gt;&lt;span&gt;\" . __('Tags', 'tracks') . \"&lt;/span&gt;\";\n foreach($tags as $tag) {\n // dpm($tag) here by uncomment you can check tag slug which you want to exclude\n if($tag-&gt;slug != \"yourtag\"){ // replace yourtag with you required tag name\n $output .= '&lt;a href=\"'.get_tag_link( $tag-&gt;term_id ).'\" title=\"' . esc_attr( sprintf( __( \"View all posts tagged %s\", 'tracks' ), $tag-&gt;name ) ) . '\"&gt;'.$tag-&gt;name.'&lt;/a&gt;'.$separator;\n }\n }\n echo trim($output, $separator);\n echo \"&lt;/p&gt;\";\n echo \"&lt;/div&gt;\";\n}\n</code></pre>\n\n<p>You can apply condition that if tagname is not equal to your tag then only it will be added to out put.</p>\n\n<p>Thanks!</p>\n" }, { "answer_id": 209372, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-includes/category-template.php#L1265\" rel=\"nofollow noreferrer\"><code>get_the_tags()</code> uses <code>get_the_terms()</code></a>:</p>\n\n<pre><code>1265 return apply_filters( 'get_the_tags', get_the_terms( $id, 'post_tag' ) );\n</code></pre>\n\n<p>Which in turn <a href=\"https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-includes/category-template.php#L1372\" rel=\"nofollow noreferrer\">applies a filter</a>:</p>\n\n<pre><code>1372 $terms = apply_filters( 'get_the_terms', $terms, $post-&gt;ID, $taxonomy );\n</code></pre>\n\n<p>You can use that filter to exclude the term(s) you wish. The answer is effectively the same as for <a href=\"https://wordpress.stackexchange.com/q/208807/21376\">this question</a>, though the sequence of function calls in Core is slightly different:</p>\n\n<pre><code>function exclude_my_term($terms, $post, $taxonomy) {\n remove_filter('get_the_terms','exclude_my_term',10,3);\n unset($terms[123]); // where 123 is the ID of the term to exclude\n return $terms;\n}\nadd_filter('get_the_terms','exclude_my_term',10,3);\n</code></pre>\n" }, { "answer_id": 220922, "author": "Bernard Meisler", "author_id": 90742, "author_profile": "https://wordpress.stackexchange.com/users/90742", "pm_score": 0, "selected": false, "text": "<p>I found a similar answer on Stack Overflow, which I think is clearer. To exclude a tag from <code>get_the_tag_list</code>, apply a filter to <code>get_terms</code>:</p>\n\n<pre><code>add_filter('get_the_terms', 'exclude_terms');\necho get_the_tag_list('&lt;p class=\"text-muted\"&gt;&lt;i class=\"fa fa-tags\"&gt;',', ','&lt;/i&gt;&lt;/p&gt;');\nremove_filter('get_the_terms', 'exclude_terms');\n</code></pre>\n\n<p>Add a filter on <code>get_the_terms</code> and then immediately remove it after echoing.</p>\n\n<p>The callback function removes terms by IDs or slugs:</p>\n\n<pre><code>function exclude_terms($terms) {\n $exclude_terms = array(9,11); //put term ids here to remove!\n if (!empty($terms) &amp;&amp; is_array($terms)) {\n foreach ($terms as $key =&gt; $term) {\n if (in_array($term-&gt;term_id, $exclude_terms)) {\n unset($terms[$key]);\n }\n }\n }\n\n return $terms;\n}\n</code></pre>\n\n<p>You can do the exact same thing for <code>get_the_category_list</code> - just create a duplicate callback function with a different name - e.g., exclude-cats - and then add the ids you want to exclude and apply the filter:</p>\n\n<pre><code>add_filter('get_the_terms', 'exclude_cats');\necho get_the_category_list('&lt;p class=\"text-muted\"&gt;&lt;i class=\"fa fa-tags\"&gt;',', ','&lt;/i&gt;&lt;/p&gt;');\nremove_filter('get_the_terms', 'exclude_cats');\n</code></pre>\n\n<p>I suppose you could make this one function and pass in the IDs...</p>\n" } ]
2015/11/20
[ "https://wordpress.stackexchange.com/questions/209363", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81710/" ]
I don't understand why wordpress stores that kind of data: posts' content and pages' content, directly within the database instead of storing it in the filesystem and referencing them in the database with an URL/path. Could someone please explain it to me? --EDIT As far as I know storing raw images in within the database is a bad practice since it increments considerably the size of the DB unneededly, and that's fine because images aren't stored within the database (i think), so my question is about "Why text isn't treated the same way?" and "If you have a large amount of huge posts wouldn't it somehow encounter the limits of the database sooner or later?"
``` $tags = get_the_tags( $post->ID ); $separator = ' '; $output = ''; if($tags){ echo '<div class="entry-tags">'; echo "<p><span>" . __('Tags', 'tracks') . "</span>"; foreach($tags as $tag) { // dpm($tag) here by uncomment you can check tag slug which you want to exclude if($tag->slug != "yourtag"){ // replace yourtag with you required tag name $output .= '<a href="'.get_tag_link( $tag->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts tagged %s", 'tracks' ), $tag->name ) ) . '">'.$tag->name.'</a>'.$separator; } } echo trim($output, $separator); echo "</p>"; echo "</div>"; } ``` You can apply condition that if tagname is not equal to your tag then only it will be added to out put. Thanks!
209,392
<p>I just installed <strong>[first time]</strong> WordPress 4.3.1, but I was facing the problem with it so I downgraded and installed 4.2.5 and facing same problem.</p> <p><strong>Problem</strong>: <strong>index.php is not loading, I clicked on link and also write in url but still not working</strong></p> <p>I uninstalled and then later I reinstalled and tried again but facing same problem.</p> <p>After some google, I also tried other options as suggested on other websites.</p> <pre><code>Remember, index.php on other directories are working fine. </code></pre> <ol> <li>Edit .htaccess</li> <li>Change Theme</li> <li>Restarted Apache and Mysql</li> </ol> <blockquote> <p>but didn't work. Themes are also not showing Live Preview</p> </blockquote> <p><em>But Dashboard is running</em></p> <p>Please Help</p> <blockquote> <p>My pc, I am not working on Xampp or Wampp. I have running <code>Mysql</code> and workbench <code>Apache</code> as binary and then manually installed php</p> </blockquote> <p>Thanks</p> <p>I also checked error.log it showing that error</p> <pre><code>[Fri Nov 20 18:08:16.599079 2015] [authz_core:error] [pid 6188:tid 868] [client ::1:58552] AH01630: client denied by server configuration: B:/server/Apache/Apache24/htdocs/KayD/.htaccess, referer: http://localhost/kayd/ </code></pre> <p><strong>HTTPD.conf</strong></p> <pre><code># # This is the main Apache HTTP server configuration file. It contains the # configuration directives that give the server its instructions. # See &lt;URL:http://httpd.apache.org/docs/2.4/&gt; for detailed information. # In particular, see # &lt;URL:http://httpd.apache.org/docs/2.4/mod/directives.html&gt; # for a discussion of each configuration directive. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), the # server will use that explicit path. If the filenames do *not* begin # with "/", the value of ServerRoot is prepended -- so "logs/access_log" # with ServerRoot set to "/usr/local/apache2" will be interpreted by the # server as "/usr/local/apache2/logs/access_log", whereas "/logs/access_log" # will be interpreted as '/logs/access_log'. # # NOTE: Where filenames are specified, you must use forward slashes # instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). # If a drive letter is omitted, the drive on which httpd.exe is located # will be used by default. It is recommended that you always supply # an explicit drive letter in absolute paths to avoid confusion. # # ServerRoot: The top of the directory tree under which the server's # configuration, error, and log files are kept. # # Do not add a slash at the end of the directory path. If you point # ServerRoot at a non-local disk, be sure to specify a local disk on the # Mutex directive, if file-based mutexes are used. If you wish to share the # same ServerRoot for multiple httpd daemons, you will need to change at # least PidFile. # ServerRoot "B:/server/Apache/Apache24" # # Mutex: Allows you to set the mutex mechanism and mutex file directory # for individual mutexes, or change the global defaults # # Uncomment and change the directory if mutexes are file-based and the default # mutex file directory is not on a local disk or is not appropriate for some # other reason. # # Mutex default:logs # # Listen: Allows you to bind Apache to specific IP addresses and/or # ports, instead of the default. See also the &lt;VirtualHost&gt; # directive. # # Change this to Listen on specific IP addresses as shown below to # prevent Apache from glomming onto all bound IP addresses. # #Listen 12.34.56.78:80 Listen 80 # # Dynamic Shared Object (DSO) Support # # To be able to use the functionality of a module which was built as a DSO you # have to place corresponding `LoadModule' lines at this location so the # directives contained in it are actually available _before_ they are used. # Statically compiled modules (those listed by `httpd -l') do not need # to be loaded here. # # Example: # LoadModule foo_module modules/mod_foo.so # LoadModule access_compat_module modules/mod_access_compat.so LoadModule actions_module modules/mod_actions.so LoadModule alias_module modules/mod_alias.so LoadModule allowmethods_module modules/mod_allowmethods.so LoadModule asis_module modules/mod_asis.so LoadModule auth_basic_module modules/mod_auth_basic.so #LoadModule auth_digest_module modules/mod_auth_digest.so #LoadModule auth_form_module modules/mod_auth_form.so #LoadModule authn_anon_module modules/mod_authn_anon.so LoadModule authn_core_module modules/mod_authn_core.so #LoadModule authn_dbd_module modules/mod_authn_dbd.so #LoadModule authn_dbm_module modules/mod_authn_dbm.so LoadModule authn_file_module modules/mod_authn_file.so #LoadModule authn_socache_module modules/mod_authn_socache.so #LoadModule authnz_fcgi_module modules/mod_authnz_fcgi.so #LoadModule authnz_ldap_module modules/mod_authnz_ldap.so LoadModule authz_core_module modules/mod_authz_core.so #LoadModule authz_dbd_module modules/mod_authz_dbd.so #LoadModule authz_dbm_module modules/mod_authz_dbm.so LoadModule authz_groupfile_module modules/mod_authz_groupfile.so LoadModule authz_host_module modules/mod_authz_host.so #LoadModule authz_owner_module modules/mod_authz_owner.so LoadModule authz_user_module modules/mod_authz_user.so LoadModule autoindex_module modules/mod_autoindex.so #LoadModule buffer_module modules/mod_buffer.so #LoadModule cache_module modules/mod_cache.so #LoadModule cache_disk_module modules/mod_cache_disk.so #LoadModule cache_socache_module modules/mod_cache_socache.so #LoadModule cern_meta_module modules/mod_cern_meta.so LoadModule cgi_module modules/mod_cgi.so #LoadModule charset_lite_module modules/mod_charset_lite.so #LoadModule data_module modules/mod_data.so #LoadModule dav_module modules/mod_dav.so #LoadModule dav_fs_module modules/mod_dav_fs.so #LoadModule dav_lock_module modules/mod_dav_lock.so #LoadModule dbd_module modules/mod_dbd.so #LoadModule deflate_module modules/mod_deflate.so LoadModule dir_module modules/mod_dir.so #LoadModule dumpio_module modules/mod_dumpio.so LoadModule env_module modules/mod_env.so #LoadModule expires_module modules/mod_expires.so #LoadModule ext_filter_module modules/mod_ext_filter.so #LoadModule file_cache_module modules/mod_file_cache.so #LoadModule filter_module modules/mod_filter.so #LoadModule headers_module modules/mod_headers.so #LoadModule heartbeat_module modules/mod_heartbeat.so #LoadModule heartmonitor_module modules/mod_heartmonitor.so #LoadModule ident_module modules/mod_ident.so #LoadModule imagemap_module modules/mod_imagemap.so LoadModule include_module modules/mod_include.so #LoadModule info_module modules/mod_info.so LoadModule isapi_module modules/mod_isapi.so #LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so #LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so #LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so #LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so #LoadModule ldap_module modules/mod_ldap.so #LoadModule logio_module modules/mod_logio.so LoadModule log_config_module modules/mod_log_config.so #LoadModule log_debug_module modules/mod_log_debug.so #LoadModule log_forensic_module modules/mod_log_forensic.so #LoadModule lua_module modules/mod_lua.so #LoadModule macro_module modules/mod_macro.so LoadModule mime_module modules/mod_mime.so #LoadModule mime_magic_module modules/mod_mime_magic.so LoadModule negotiation_module modules/mod_negotiation.so #LoadModule proxy_module modules/mod_proxy.so #LoadModule proxy_ajp_module modules/mod_proxy_ajp.so #LoadModule proxy_balancer_module modules/mod_proxy_balancer.so #LoadModule proxy_connect_module modules/mod_proxy_connect.so #LoadModule proxy_express_module modules/mod_proxy_express.so #LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so #LoadModule proxy_ftp_module modules/mod_proxy_ftp.so #LoadModule proxy_html_module modules/mod_proxy_html.so #LoadModule proxy_http_module modules/mod_proxy_http.so #LoadModule proxy_scgi_module modules/mod_proxy_scgi.so #LoadModule proxy_wstunnel_module modules/mod_proxy_wstunnel.so #LoadModule ratelimit_module modules/mod_ratelimit.so #LoadModule reflector_module modules/mod_reflector.so #LoadModule remoteip_module modules/mod_remoteip.so #LoadModule request_module modules/mod_request.so #LoadModule reqtimeout_module modules/mod_reqtimeout.so #LoadModule rewrite_module modules/mod_rewrite.so #LoadModule sed_module modules/mod_sed.so #LoadModule session_module modules/mod_session.so #LoadModule session_cookie_module modules/mod_session_cookie.so #LoadModule session_crypto_module modules/mod_session_crypto.so #LoadModule session_dbd_module modules/mod_session_dbd.so LoadModule setenvif_module modules/mod_setenvif.so #LoadModule slotmem_plain_module modules/mod_slotmem_plain.so #LoadModule slotmem_shm_module modules/mod_slotmem_shm.so #LoadModule socache_dbm_module modules/mod_socache_dbm.so #LoadModule socache_memcache_module modules/mod_socache_memcache.so #LoadModule socache_shmcb_module modules/mod_socache_shmcb.so #LoadModule speling_module modules/mod_speling.so #LoadModule ssl_module modules/mod_ssl.so #LoadModule status_module modules/mod_status.so #LoadModule substitute_module modules/mod_substitute.so #LoadModule unique_id_module modules/mod_unique_id.so #LoadModule userdir_module modules/mod_userdir.so #LoadModule usertrack_module modules/mod_usertrack.so #LoadModule version_module modules/mod_version.so #LoadModule vhost_alias_module modules/mod_vhost_alias.so #LoadModule watchdog_module modules/mod_watchdog.so #LoadModule xml2enc_module modules/mod_xml2enc.so &lt;IfModule unixd_module&gt; # # If you wish httpd to run as a different user or group, you must run # httpd as root initially and it will switch. # # User/Group: The name (or #number) of the user/group to run httpd as. # It is usually good practice to create a dedicated user and group for # running httpd, as with most system services. # User daemon Group daemon &lt;/IfModule&gt; # 'Main' server configuration # # The directives in this section set up the values used by the 'main' # server, which responds to any requests that aren't handled by a # &lt;VirtualHost&gt; definition. These values also provide defaults for # any &lt;VirtualHost&gt; containers you may define later in the file. # # All of these directives may appear inside &lt;VirtualHost&gt; containers, # in which case these default settings will be overridden for the # virtual host being defined. # # # ServerAdmin: Your address, where problems with the server should be # e-mailed. This address appears on some server-generated pages, such # as error documents. e.g. [email protected] # ServerAdmin [email protected] # # ServerName gives the name and port that the server uses to identify itself. # This can often be determined automatically, but we recommend you specify # it explicitly to prevent problems during startup. # # If your host doesn't have a registered DNS name, enter its IP address here. # ServerName www.example.com:80 # # Deny access to the entirety of your server's filesystem. You must # explicitly permit access to web content directories in other # &lt;Directory&gt; blocks below. # &lt;Directory /&gt; AllowOverride none Require all denied &lt;/Directory&gt; &lt;Directory "B:/server/Apache/Apache24/htdocs/KayD"&gt; Require local &lt;/Directory&gt; # # Note that from this point forward you must specifically allow # particular features to be enabled - so if something's not working as # you might expect, make sure that you have specifically enabled it # below. # # # DocumentRoot: The directory out of which you will serve your # documents. By default, all requests are taken from this directory, but # symbolic links and aliases may be used to point to other locations. # DocumentRoot "B:/server/Apache/Apache24/htdocs" &lt;Directory "B:/server/Apache/Apache24/htdocs"&gt; # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.4/mod/core.html#options # for more information. # Options Indexes FollowSymLinks # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # AllowOverride FileInfo AuthConfig Limit # AllowOverride None # # Controls who can get stuff from this server. # Require all granted &lt;/Directory&gt; # # DirectoryIndex: sets the file that Apache will serve if a directory # is requested. # &lt;IfModule dir_module&gt; DirectoryIndex index.html &lt;/IfModule&gt; # # The following lines prevent .htaccess and .htpasswd files from being # viewed by Web clients. # &lt;Files ".ht*"&gt; Require all denied &lt;/Files&gt; # # ErrorLog: The location of the error log file. # If you do not specify an ErrorLog directive within a &lt;VirtualHost&gt; # container, error messages relating to that virtual host will be # logged here. If you *do* define an error logfile for a &lt;VirtualHost&gt; # container, that host's errors will be logged there and not here. # ErrorLog "logs/error.log" # # LogLevel: Control the number of messages logged to the error_log. # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. # LogLevel warn &lt;IfModule log_config_module&gt; # # The following directives define some format nicknames for use with # a CustomLog directive (see below). # LogFormat "%h %l %u %t \"%r\" %&gt;s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %&gt;s %b" common &lt;IfModule logio_module&gt; # You need to enable mod_logio.c to use %I and %O LogFormat "%h %l %u %t \"%r\" %&gt;s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio &lt;/IfModule&gt; # # The location and format of the access logfile (Common Logfile Format). # If you do not define any access logfiles within a &lt;VirtualHost&gt; # container, they will be logged here. Contrariwise, if you *do* # define per-&lt;VirtualHost&gt; access logfiles, transactions will be # logged therein and *not* in this file. # CustomLog "logs/access.log" common # # If you prefer a logfile with access, agent, and referer information # (Combined Logfile Format) you can use the following directive. # #CustomLog "logs/access.log" combined &lt;/IfModule&gt; &lt;IfModule alias_module&gt; # # Redirect: Allows you to tell clients about documents that used to # exist in your server's namespace, but do not anymore. The client # will make a new request for the document at its new location. # Example: # Redirect permanent /foo http://www.example.com/bar # # Alias: Maps web paths into filesystem paths and is used to # access content that does not live under the DocumentRoot. # Example: # Alias /webpath /full/filesystem/path # # If you include a trailing / on /webpath then the server will # require it to be present in the URL. You will also likely # need to provide a &lt;Directory&gt; section to allow access to # the filesystem path. # # ScriptAlias: This controls which directories contain server scripts. # ScriptAliases are essentially the same as Aliases, except that # documents in the target directory are treated as applications and # run by the server when requested rather than as documents sent to the # client. The same rules about trailing "/" apply to ScriptAlias # directives as to Alias. # ScriptAlias /cgi-bin/ "B:/server/Apache/Apache24/cgi-bin/" &lt;/IfModule&gt; &lt;IfModule cgid_module&gt; # # ScriptSock: On threaded servers, designate the path to the UNIX # socket used to communicate with the CGI daemon of mod_cgid. # #Scriptsock cgisock &lt;/IfModule&gt; # # "B:/server/Apache/Apache24/cgi-bin" should be changed to whatever your ScriptAliased # CGI directory exists, if you have that configured. # &lt;Directory "B:/server/Apache/Apache24/cgi-bin"&gt; AllowOverride None Options None Require all granted &lt;/Directory&gt; &lt;IfModule mime_module&gt; # # TypesConfig points to the file containing the list of mappings from # filename extension to MIME-type. # TypesConfig conf/mime.types # # AddType allows you to add to or override the MIME configuration # file specified in TypesConfig for specific file types. # #AddType application/x-gzip .tgz # # AddEncoding allows you to have certain browsers uncompress # information on the fly. Note: Not all browsers support this. # #AddEncoding x-compress .Z #AddEncoding x-gzip .gz .tgz # # If the AddEncoding directives above are commented-out, then you # probably should define those extensions to indicate media types: # AddType application/x-compress .Z AddType application/x-gzip .gz .tgz # # AddHandler allows you to map certain file extensions to "handlers": # actions unrelated to filetype. These can be either built into the server # or added with the Action directive (see below) # # To use CGI scripts outside of ScriptAliased directories: # (You will also need to add "ExecCGI" to the "Options" directive.) # #AddHandler cgi-script .cgi # For type maps (negotiated resources): #AddHandler type-map var # # Filters allow you to process content before it is sent to the client. # # To parse .shtml files for server-side includes (SSI): # (You will also need to add "Includes" to the "Options" directive.) # #AddType text/html .shtml #AddOutputFilter INCLUDES .shtml &lt;/IfModule&gt; # # The mod_mime_magic module allows the server to use various hints from the # contents of the file itself to determine its type. The MIMEMagicFile # directive tells the module where the hint definitions are located. # #MIMEMagicFile conf/magic # # Customizable error responses come in three flavors: # 1) plain text 2) local redirects 3) external redirects # # Some examples: #ErrorDocument 500 "The server made a boo boo." #ErrorDocument 404 /missing.html #ErrorDocument 404 "/cgi-bin/missing_handler.pl" #ErrorDocument 402 http://www.example.com/subscription_info.html # # # MaxRanges: Maximum number of Ranges in a request before # returning the entire resource, or one of the special # values 'default', 'none' or 'unlimited'. # Default setting is to accept 200 Ranges. #MaxRanges unlimited # # EnableMMAP and EnableSendfile: On systems that support it, # memory-mapping or the sendfile syscall may be used to deliver # files. This usually improves server performance, but must # be turned off when serving from networked-mounted # filesystems or if support for these functions is otherwise # broken on your system. # Defaults: EnableMMAP On, EnableSendfile Off # #EnableMMAP off #EnableSendfile on # Supplemental configuration # # The configuration files in the conf/extra/ directory can be # included to add extra features or to modify the default configuration of # the server, or you may simply copy their contents here and change as # necessary. # Server-pool management (MPM specific) #Include conf/extra/httpd-mpm.conf # Multi-language error messages #Include conf/extra/httpd-multilang-errordoc.conf # Fancy directory listings #Include conf/extra/httpd-autoindex.conf # Language settings #Include conf/extra/httpd-languages.conf # User home directories #Include conf/extra/httpd-userdir.conf # Real-time info on requests and configuration #Include conf/extra/httpd-info.conf # Virtual hosts #Include conf/extra/httpd-vhosts.conf # Local access to the Apache HTTP Server Manual #Include conf/extra/httpd-manual.conf # Distributed authoring and versioning (WebDAV) #Include conf/extra/httpd-dav.conf # Various default settings #Include conf/extra/httpd-default.conf # Configure mod_proxy_html to understand HTML4/XHTML1 &lt;IfModule proxy_html_module&gt; Include conf/extra/proxy-html.conf &lt;/IfModule&gt; # Secure (SSL/TLS) connections #Include conf/extra/httpd-ssl.conf # # Note: The following must must be present to support # starting without SSL on platforms with no /dev/random equivalent # but a statically compiled-in mod_ssl. # &lt;IfModule ssl_module&gt; SSLRandomSeed startup builtin SSLRandomSeed connect builtin &lt;/IfModule&gt; # # uncomment out the below to deal with user agents that deliberately # violate open standards by misusing DNT (DNT *must* be a specific # end-user choice) # #&lt;IfModule setenvif_module&gt; #BrowserMatch "MSIE 10.0;" bad_DNT #&lt;/IfModule&gt; #&lt;IfModule headers_module&gt; #RequestHeader unset DNT env=bad_DNT #&lt;/IfModule&gt; # LoadModule php5_module "B:/server/Apache/php-5.6.5-Win32-VC11-x64/php5apache2_4.dll" AddHandler application/x-httpd-php .php # configure the path to php.ini PHPIniDir "B:/server/Apache/php-5.6.5-Win32-VC11-x64" </code></pre> <p><strong>HTACCESS File</strong></p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase /KayD/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /KayD/index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p><strong>Document Root</strong> <em>B:\server\Apache\Apache24\htdocs\KayD</em></p> <blockquote> <p><strong>I checked again <em><code>http://localhost/KayD/index.php</code></em></strong> still has a problem but <em><code>http://localhost/KayD/index.php/2015/11/20/hello-world/ is working</code></em></p> <p>What going on here?</p> </blockquote>
[ { "answer_id": 209394, "author": "Craig Pearson", "author_id": 17295, "author_profile": "https://wordpress.stackexchange.com/users/17295", "pm_score": 1, "selected": false, "text": "<p>It appears that you don't have the mod_rewrite module enabled in apache. This explains why you can access the dashboard found at <code>wp-admin/index.php</code>, but not the main index.php. Your .htaccess is depending on the rewrite module to do its work, which isn't active.</p>\n\n<p>To enable it in your http.conf file you need to find the line:</p>\n\n<p><code>#LoadModule rewrite_module modules/mod_rewrite.so</code></p>\n\n<p>And remove the \"#\" this uncomments the inclusion and tells apache to load the module. You then need to restart apache for the changes to take effect.</p>\n\n<p>Personally I would recommend that the following modules are loaded:</p>\n\n<pre><code>LoadModule authz_host_module modules/mod_authz_host.so\nLoadModule log_config_module modules/mod_log_config.so\nLoadModule expires_module modules/mod_expires.so\nLoadModule deflate_module modules/mod_deflate.so\nLoadModule headers_module modules/mod_headers.so\nLoadModule setenvif_module modules/mod_setenvif.so\nLoadModule mime_module modules/mod_mime.so\nLoadModule autoindex_module modules/mod_autoindex.so\nLoadModule dir_module modules/mod_dir.so\nLoadModule alias_module modules/mod_alias.so\nLoadModule rewrite_module modules/mod_rewrite.so\n</code></pre>\n" }, { "answer_id": 284947, "author": "junho", "author_id": 130883, "author_profile": "https://wordpress.stackexchange.com/users/130883", "pm_score": 0, "selected": false, "text": "<p>In the file <code>apache/httpd.conf</code> you must add <code>index.php</code> in <code>&lt;ifMdule&gt;</code>:</p>\n\n<pre><code>&lt;IfModule dir_module&gt;\n DirectoryIndex index.php index.html\n&lt;/IfModule&gt;\n</code></pre>\n" }, { "answer_id": 310448, "author": "JTC", "author_id": 148053, "author_profile": "https://wordpress.stackexchange.com/users/148053", "pm_score": 0, "selected": false, "text": "<p>I'm not exactly sure why, but for me it worked to add this line into the <code>.htaccess</code> file after <code>RewriteEngine on</code>:</p>\n<p><code>DirectoryIndex index.html index.php</code></p>\n<p>But for sure it has something to do with missing apache modules.</p>\n" } ]
2015/11/21
[ "https://wordpress.stackexchange.com/questions/209392", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17941/" ]
I just installed **[first time]** WordPress 4.3.1, but I was facing the problem with it so I downgraded and installed 4.2.5 and facing same problem. **Problem**: **index.php is not loading, I clicked on link and also write in url but still not working** I uninstalled and then later I reinstalled and tried again but facing same problem. After some google, I also tried other options as suggested on other websites. ``` Remember, index.php on other directories are working fine. ``` 1. Edit .htaccess 2. Change Theme 3. Restarted Apache and Mysql > > but didn't work. Themes are also not showing Live Preview > > > *But Dashboard is running* Please Help > > My pc, I am not working on Xampp or Wampp. I have running `Mysql` and > workbench `Apache` as binary and then manually installed php > > > Thanks I also checked error.log it showing that error ``` [Fri Nov 20 18:08:16.599079 2015] [authz_core:error] [pid 6188:tid 868] [client ::1:58552] AH01630: client denied by server configuration: B:/server/Apache/Apache24/htdocs/KayD/.htaccess, referer: http://localhost/kayd/ ``` **HTTPD.conf** ``` # # This is the main Apache HTTP server configuration file. It contains the # configuration directives that give the server its instructions. # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information. # In particular, see # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html> # for a discussion of each configuration directive. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), the # server will use that explicit path. If the filenames do *not* begin # with "/", the value of ServerRoot is prepended -- so "logs/access_log" # with ServerRoot set to "/usr/local/apache2" will be interpreted by the # server as "/usr/local/apache2/logs/access_log", whereas "/logs/access_log" # will be interpreted as '/logs/access_log'. # # NOTE: Where filenames are specified, you must use forward slashes # instead of backslashes (e.g., "c:/apache" instead of "c:\apache"). # If a drive letter is omitted, the drive on which httpd.exe is located # will be used by default. It is recommended that you always supply # an explicit drive letter in absolute paths to avoid confusion. # # ServerRoot: The top of the directory tree under which the server's # configuration, error, and log files are kept. # # Do not add a slash at the end of the directory path. If you point # ServerRoot at a non-local disk, be sure to specify a local disk on the # Mutex directive, if file-based mutexes are used. If you wish to share the # same ServerRoot for multiple httpd daemons, you will need to change at # least PidFile. # ServerRoot "B:/server/Apache/Apache24" # # Mutex: Allows you to set the mutex mechanism and mutex file directory # for individual mutexes, or change the global defaults # # Uncomment and change the directory if mutexes are file-based and the default # mutex file directory is not on a local disk or is not appropriate for some # other reason. # # Mutex default:logs # # Listen: Allows you to bind Apache to specific IP addresses and/or # ports, instead of the default. See also the <VirtualHost> # directive. # # Change this to Listen on specific IP addresses as shown below to # prevent Apache from glomming onto all bound IP addresses. # #Listen 12.34.56.78:80 Listen 80 # # Dynamic Shared Object (DSO) Support # # To be able to use the functionality of a module which was built as a DSO you # have to place corresponding `LoadModule' lines at this location so the # directives contained in it are actually available _before_ they are used. # Statically compiled modules (those listed by `httpd -l') do not need # to be loaded here. # # Example: # LoadModule foo_module modules/mod_foo.so # LoadModule access_compat_module modules/mod_access_compat.so LoadModule actions_module modules/mod_actions.so LoadModule alias_module modules/mod_alias.so LoadModule allowmethods_module modules/mod_allowmethods.so LoadModule asis_module modules/mod_asis.so LoadModule auth_basic_module modules/mod_auth_basic.so #LoadModule auth_digest_module modules/mod_auth_digest.so #LoadModule auth_form_module modules/mod_auth_form.so #LoadModule authn_anon_module modules/mod_authn_anon.so LoadModule authn_core_module modules/mod_authn_core.so #LoadModule authn_dbd_module modules/mod_authn_dbd.so #LoadModule authn_dbm_module modules/mod_authn_dbm.so LoadModule authn_file_module modules/mod_authn_file.so #LoadModule authn_socache_module modules/mod_authn_socache.so #LoadModule authnz_fcgi_module modules/mod_authnz_fcgi.so #LoadModule authnz_ldap_module modules/mod_authnz_ldap.so LoadModule authz_core_module modules/mod_authz_core.so #LoadModule authz_dbd_module modules/mod_authz_dbd.so #LoadModule authz_dbm_module modules/mod_authz_dbm.so LoadModule authz_groupfile_module modules/mod_authz_groupfile.so LoadModule authz_host_module modules/mod_authz_host.so #LoadModule authz_owner_module modules/mod_authz_owner.so LoadModule authz_user_module modules/mod_authz_user.so LoadModule autoindex_module modules/mod_autoindex.so #LoadModule buffer_module modules/mod_buffer.so #LoadModule cache_module modules/mod_cache.so #LoadModule cache_disk_module modules/mod_cache_disk.so #LoadModule cache_socache_module modules/mod_cache_socache.so #LoadModule cern_meta_module modules/mod_cern_meta.so LoadModule cgi_module modules/mod_cgi.so #LoadModule charset_lite_module modules/mod_charset_lite.so #LoadModule data_module modules/mod_data.so #LoadModule dav_module modules/mod_dav.so #LoadModule dav_fs_module modules/mod_dav_fs.so #LoadModule dav_lock_module modules/mod_dav_lock.so #LoadModule dbd_module modules/mod_dbd.so #LoadModule deflate_module modules/mod_deflate.so LoadModule dir_module modules/mod_dir.so #LoadModule dumpio_module modules/mod_dumpio.so LoadModule env_module modules/mod_env.so #LoadModule expires_module modules/mod_expires.so #LoadModule ext_filter_module modules/mod_ext_filter.so #LoadModule file_cache_module modules/mod_file_cache.so #LoadModule filter_module modules/mod_filter.so #LoadModule headers_module modules/mod_headers.so #LoadModule heartbeat_module modules/mod_heartbeat.so #LoadModule heartmonitor_module modules/mod_heartmonitor.so #LoadModule ident_module modules/mod_ident.so #LoadModule imagemap_module modules/mod_imagemap.so LoadModule include_module modules/mod_include.so #LoadModule info_module modules/mod_info.so LoadModule isapi_module modules/mod_isapi.so #LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so #LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so #LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so #LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so #LoadModule ldap_module modules/mod_ldap.so #LoadModule logio_module modules/mod_logio.so LoadModule log_config_module modules/mod_log_config.so #LoadModule log_debug_module modules/mod_log_debug.so #LoadModule log_forensic_module modules/mod_log_forensic.so #LoadModule lua_module modules/mod_lua.so #LoadModule macro_module modules/mod_macro.so LoadModule mime_module modules/mod_mime.so #LoadModule mime_magic_module modules/mod_mime_magic.so LoadModule negotiation_module modules/mod_negotiation.so #LoadModule proxy_module modules/mod_proxy.so #LoadModule proxy_ajp_module modules/mod_proxy_ajp.so #LoadModule proxy_balancer_module modules/mod_proxy_balancer.so #LoadModule proxy_connect_module modules/mod_proxy_connect.so #LoadModule proxy_express_module modules/mod_proxy_express.so #LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so #LoadModule proxy_ftp_module modules/mod_proxy_ftp.so #LoadModule proxy_html_module modules/mod_proxy_html.so #LoadModule proxy_http_module modules/mod_proxy_http.so #LoadModule proxy_scgi_module modules/mod_proxy_scgi.so #LoadModule proxy_wstunnel_module modules/mod_proxy_wstunnel.so #LoadModule ratelimit_module modules/mod_ratelimit.so #LoadModule reflector_module modules/mod_reflector.so #LoadModule remoteip_module modules/mod_remoteip.so #LoadModule request_module modules/mod_request.so #LoadModule reqtimeout_module modules/mod_reqtimeout.so #LoadModule rewrite_module modules/mod_rewrite.so #LoadModule sed_module modules/mod_sed.so #LoadModule session_module modules/mod_session.so #LoadModule session_cookie_module modules/mod_session_cookie.so #LoadModule session_crypto_module modules/mod_session_crypto.so #LoadModule session_dbd_module modules/mod_session_dbd.so LoadModule setenvif_module modules/mod_setenvif.so #LoadModule slotmem_plain_module modules/mod_slotmem_plain.so #LoadModule slotmem_shm_module modules/mod_slotmem_shm.so #LoadModule socache_dbm_module modules/mod_socache_dbm.so #LoadModule socache_memcache_module modules/mod_socache_memcache.so #LoadModule socache_shmcb_module modules/mod_socache_shmcb.so #LoadModule speling_module modules/mod_speling.so #LoadModule ssl_module modules/mod_ssl.so #LoadModule status_module modules/mod_status.so #LoadModule substitute_module modules/mod_substitute.so #LoadModule unique_id_module modules/mod_unique_id.so #LoadModule userdir_module modules/mod_userdir.so #LoadModule usertrack_module modules/mod_usertrack.so #LoadModule version_module modules/mod_version.so #LoadModule vhost_alias_module modules/mod_vhost_alias.so #LoadModule watchdog_module modules/mod_watchdog.so #LoadModule xml2enc_module modules/mod_xml2enc.so <IfModule unixd_module> # # If you wish httpd to run as a different user or group, you must run # httpd as root initially and it will switch. # # User/Group: The name (or #number) of the user/group to run httpd as. # It is usually good practice to create a dedicated user and group for # running httpd, as with most system services. # User daemon Group daemon </IfModule> # 'Main' server configuration # # The directives in this section set up the values used by the 'main' # server, which responds to any requests that aren't handled by a # <VirtualHost> definition. These values also provide defaults for # any <VirtualHost> containers you may define later in the file. # # All of these directives may appear inside <VirtualHost> containers, # in which case these default settings will be overridden for the # virtual host being defined. # # # ServerAdmin: Your address, where problems with the server should be # e-mailed. This address appears on some server-generated pages, such # as error documents. e.g. [email protected] # ServerAdmin [email protected] # # ServerName gives the name and port that the server uses to identify itself. # This can often be determined automatically, but we recommend you specify # it explicitly to prevent problems during startup. # # If your host doesn't have a registered DNS name, enter its IP address here. # ServerName www.example.com:80 # # Deny access to the entirety of your server's filesystem. You must # explicitly permit access to web content directories in other # <Directory> blocks below. # <Directory /> AllowOverride none Require all denied </Directory> <Directory "B:/server/Apache/Apache24/htdocs/KayD"> Require local </Directory> # # Note that from this point forward you must specifically allow # particular features to be enabled - so if something's not working as # you might expect, make sure that you have specifically enabled it # below. # # # DocumentRoot: The directory out of which you will serve your # documents. By default, all requests are taken from this directory, but # symbolic links and aliases may be used to point to other locations. # DocumentRoot "B:/server/Apache/Apache24/htdocs" <Directory "B:/server/Apache/Apache24/htdocs"> # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.4/mod/core.html#options # for more information. # Options Indexes FollowSymLinks # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # AllowOverride FileInfo AuthConfig Limit # AllowOverride None # # Controls who can get stuff from this server. # Require all granted </Directory> # # DirectoryIndex: sets the file that Apache will serve if a directory # is requested. # <IfModule dir_module> DirectoryIndex index.html </IfModule> # # The following lines prevent .htaccess and .htpasswd files from being # viewed by Web clients. # <Files ".ht*"> Require all denied </Files> # # ErrorLog: The location of the error log file. # If you do not specify an ErrorLog directive within a <VirtualHost> # container, error messages relating to that virtual host will be # logged here. If you *do* define an error logfile for a <VirtualHost> # container, that host's errors will be logged there and not here. # ErrorLog "logs/error.log" # # LogLevel: Control the number of messages logged to the error_log. # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. # LogLevel warn <IfModule log_config_module> # # The following directives define some format nicknames for use with # a CustomLog directive (see below). # LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common <IfModule logio_module> # You need to enable mod_logio.c to use %I and %O LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio </IfModule> # # The location and format of the access logfile (Common Logfile Format). # If you do not define any access logfiles within a <VirtualHost> # container, they will be logged here. Contrariwise, if you *do* # define per-<VirtualHost> access logfiles, transactions will be # logged therein and *not* in this file. # CustomLog "logs/access.log" common # # If you prefer a logfile with access, agent, and referer information # (Combined Logfile Format) you can use the following directive. # #CustomLog "logs/access.log" combined </IfModule> <IfModule alias_module> # # Redirect: Allows you to tell clients about documents that used to # exist in your server's namespace, but do not anymore. The client # will make a new request for the document at its new location. # Example: # Redirect permanent /foo http://www.example.com/bar # # Alias: Maps web paths into filesystem paths and is used to # access content that does not live under the DocumentRoot. # Example: # Alias /webpath /full/filesystem/path # # If you include a trailing / on /webpath then the server will # require it to be present in the URL. You will also likely # need to provide a <Directory> section to allow access to # the filesystem path. # # ScriptAlias: This controls which directories contain server scripts. # ScriptAliases are essentially the same as Aliases, except that # documents in the target directory are treated as applications and # run by the server when requested rather than as documents sent to the # client. The same rules about trailing "/" apply to ScriptAlias # directives as to Alias. # ScriptAlias /cgi-bin/ "B:/server/Apache/Apache24/cgi-bin/" </IfModule> <IfModule cgid_module> # # ScriptSock: On threaded servers, designate the path to the UNIX # socket used to communicate with the CGI daemon of mod_cgid. # #Scriptsock cgisock </IfModule> # # "B:/server/Apache/Apache24/cgi-bin" should be changed to whatever your ScriptAliased # CGI directory exists, if you have that configured. # <Directory "B:/server/Apache/Apache24/cgi-bin"> AllowOverride None Options None Require all granted </Directory> <IfModule mime_module> # # TypesConfig points to the file containing the list of mappings from # filename extension to MIME-type. # TypesConfig conf/mime.types # # AddType allows you to add to or override the MIME configuration # file specified in TypesConfig for specific file types. # #AddType application/x-gzip .tgz # # AddEncoding allows you to have certain browsers uncompress # information on the fly. Note: Not all browsers support this. # #AddEncoding x-compress .Z #AddEncoding x-gzip .gz .tgz # # If the AddEncoding directives above are commented-out, then you # probably should define those extensions to indicate media types: # AddType application/x-compress .Z AddType application/x-gzip .gz .tgz # # AddHandler allows you to map certain file extensions to "handlers": # actions unrelated to filetype. These can be either built into the server # or added with the Action directive (see below) # # To use CGI scripts outside of ScriptAliased directories: # (You will also need to add "ExecCGI" to the "Options" directive.) # #AddHandler cgi-script .cgi # For type maps (negotiated resources): #AddHandler type-map var # # Filters allow you to process content before it is sent to the client. # # To parse .shtml files for server-side includes (SSI): # (You will also need to add "Includes" to the "Options" directive.) # #AddType text/html .shtml #AddOutputFilter INCLUDES .shtml </IfModule> # # The mod_mime_magic module allows the server to use various hints from the # contents of the file itself to determine its type. The MIMEMagicFile # directive tells the module where the hint definitions are located. # #MIMEMagicFile conf/magic # # Customizable error responses come in three flavors: # 1) plain text 2) local redirects 3) external redirects # # Some examples: #ErrorDocument 500 "The server made a boo boo." #ErrorDocument 404 /missing.html #ErrorDocument 404 "/cgi-bin/missing_handler.pl" #ErrorDocument 402 http://www.example.com/subscription_info.html # # # MaxRanges: Maximum number of Ranges in a request before # returning the entire resource, or one of the special # values 'default', 'none' or 'unlimited'. # Default setting is to accept 200 Ranges. #MaxRanges unlimited # # EnableMMAP and EnableSendfile: On systems that support it, # memory-mapping or the sendfile syscall may be used to deliver # files. This usually improves server performance, but must # be turned off when serving from networked-mounted # filesystems or if support for these functions is otherwise # broken on your system. # Defaults: EnableMMAP On, EnableSendfile Off # #EnableMMAP off #EnableSendfile on # Supplemental configuration # # The configuration files in the conf/extra/ directory can be # included to add extra features or to modify the default configuration of # the server, or you may simply copy their contents here and change as # necessary. # Server-pool management (MPM specific) #Include conf/extra/httpd-mpm.conf # Multi-language error messages #Include conf/extra/httpd-multilang-errordoc.conf # Fancy directory listings #Include conf/extra/httpd-autoindex.conf # Language settings #Include conf/extra/httpd-languages.conf # User home directories #Include conf/extra/httpd-userdir.conf # Real-time info on requests and configuration #Include conf/extra/httpd-info.conf # Virtual hosts #Include conf/extra/httpd-vhosts.conf # Local access to the Apache HTTP Server Manual #Include conf/extra/httpd-manual.conf # Distributed authoring and versioning (WebDAV) #Include conf/extra/httpd-dav.conf # Various default settings #Include conf/extra/httpd-default.conf # Configure mod_proxy_html to understand HTML4/XHTML1 <IfModule proxy_html_module> Include conf/extra/proxy-html.conf </IfModule> # Secure (SSL/TLS) connections #Include conf/extra/httpd-ssl.conf # # Note: The following must must be present to support # starting without SSL on platforms with no /dev/random equivalent # but a statically compiled-in mod_ssl. # <IfModule ssl_module> SSLRandomSeed startup builtin SSLRandomSeed connect builtin </IfModule> # # uncomment out the below to deal with user agents that deliberately # violate open standards by misusing DNT (DNT *must* be a specific # end-user choice) # #<IfModule setenvif_module> #BrowserMatch "MSIE 10.0;" bad_DNT #</IfModule> #<IfModule headers_module> #RequestHeader unset DNT env=bad_DNT #</IfModule> # LoadModule php5_module "B:/server/Apache/php-5.6.5-Win32-VC11-x64/php5apache2_4.dll" AddHandler application/x-httpd-php .php # configure the path to php.ini PHPIniDir "B:/server/Apache/php-5.6.5-Win32-VC11-x64" ``` **HTACCESS File** ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /KayD/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /KayD/index.php [L] </IfModule> # END WordPress ``` **Document Root** *B:\server\Apache\Apache24\htdocs\KayD* > > **I checked again *`http://localhost/KayD/index.php`*** > still has a problem but > *`http://localhost/KayD/index.php/2015/11/20/hello-world/ is working`* > > > What going on here? > > >
It appears that you don't have the mod\_rewrite module enabled in apache. This explains why you can access the dashboard found at `wp-admin/index.php`, but not the main index.php. Your .htaccess is depending on the rewrite module to do its work, which isn't active. To enable it in your http.conf file you need to find the line: `#LoadModule rewrite_module modules/mod_rewrite.so` And remove the "#" this uncomments the inclusion and tells apache to load the module. You then need to restart apache for the changes to take effect. Personally I would recommend that the following modules are loaded: ``` LoadModule authz_host_module modules/mod_authz_host.so LoadModule log_config_module modules/mod_log_config.so LoadModule expires_module modules/mod_expires.so LoadModule deflate_module modules/mod_deflate.so LoadModule headers_module modules/mod_headers.so LoadModule setenvif_module modules/mod_setenvif.so LoadModule mime_module modules/mod_mime.so LoadModule autoindex_module modules/mod_autoindex.so LoadModule dir_module modules/mod_dir.so LoadModule alias_module modules/mod_alias.so LoadModule rewrite_module modules/mod_rewrite.so ```
209,467
<p>I have a custom post type named 'advert' and a related custom taxonomy named 'advert_category', created by a 3rd party plugin. I run in a plugin an <code>if</code> statement that must to set (as I expect) a specific theme layout for single adverts (example.com/advert/a-single-advert.html) and for custom taxonomy archive pages (example.com/advert-category/services/), but the second condition <code>is_tax( 'advert_category' )</code> doesn't work. What is wrong here?</p> <p>My code:</p> <pre><code>function my_advert_single_template( ) { global $post; global $wpgo_global_column_layout; if ( $post-&gt;post_type == 'advert' || is_tax( 'advert_category' ) ) { $wpgo_global_column_layout = "2-col-l"; } } add_filter( 'single_template', 'my_advert_single_template' ); </code></pre> <p>This is how the custom post type and the custom taxonomy are registered:</p> <pre><code>// register post type and taxonomy in order to allow default data insertion. register_post_type( 'advert' ); register_taxonomy( 'advert_category', 'advert' ); $hid = wp_insert_post(array( 'post_type' =&gt; 'page', 'post_status' =&gt; 'publish', 'post_title' =&gt; 'Adverts', 'comment_status' =&gt; 'closed', 'ping_status' =&gt; 'closed', 'post_content' =&gt; "[adverts_list]" )); $aid = wp_insert_post(array( 'post_type' =&gt; 'page', 'post_status' =&gt; 'publish', 'post_title' =&gt; 'Add', 'post_parent' =&gt; $hid, 'comment_status' =&gt; 'closed', 'ping_status' =&gt; 'closed', 'post_content' =&gt; "[adverts_add]" )); $mid = wp_insert_post(array( 'post_type' =&gt; 'page', 'post_status' =&gt; 'publish', 'post_title' =&gt; 'Manage', 'post_parent' =&gt; $hid, 'comment_status' =&gt; 'closed', 'ping_status' =&gt; 'closed', 'post_content' =&gt; "[adverts_manage]" )); wp_insert_term( 'Default', 'advert_category' ); </code></pre>
[ { "answer_id": 209468, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>You hava a lot of issues here:</p>\n<ul>\n<li><p><code>pre_get_posts</code> is not the correct hook to set templates. <code>pre_get_posts</code> are used to alter the ain query query vars just before the SQL are build to run the main query's query</p>\n</li>\n<li><p>A filter should <strong>always</strong> return something. Not doing this will have unexpected behavior, and forgetting about this can have you on a wild goose chase for hours debugging the issue.</p>\n</li>\n<li><p>Using globals to control theme features or to store any kind of data is bad practice and not very safe coding. WordPress has already made such a huge mess of globals, particularly naming conventions. Just check how newbies (<em>that does not know Wordpress</em>) unknowingly use variable like <code>$post</code> and <code>$posts</code> as local variables. These are native globals uses by WordPress, and using them as local variables breaks the values of these globals.</p>\n<p>Because of this, something on the page goes wrong, there are no errors, so you are stuck on a wild goose chase trying to debug something that you have unknowingly broke. Globals are pure evil and you should avoid using them. Just think, if you use the variable <code>$wpgo_global_column_layout</code> for the query arguments of a custom query, you will break the value of the template that needs to be set, your template does not load because the value of <code>$wpgo_global_column_layout</code> are not recognized as a valid template name, you are stuffed and don't know why your template does not load as your code are 100% that should load a custom template</p>\n</li>\n<li><p><code>is_tax()</code> is the wrong check to use to check whether a post has a certain term or not, <code>is_tax()</code> simply checks if you are on a taxonomy archive or not. You should be using <a href=\"https://developer.wordpress.org/reference/functions/has_term/\" rel=\"nofollow noreferrer\"><code>has_term()</code></a> which do just that, checks if a certain post has a certain term</p>\n</li>\n<li><p>If you need to set a template for a taxonomy page, <code>single_template</code> is the wrong hook, you should be using the <a href=\"https://developer.wordpress.org/reference/hooks/type_template/\" rel=\"nofollow noreferrer\"><code>taxonomy_template</code></a> hook or the more generic <a href=\"https://developer.wordpress.org/reference/hooks/template_include/\" rel=\"nofollow noreferrer\"><code>template_include</code></a> filter</p>\n</li>\n<li><p>In the line <code>$post-&gt;post_type == 'advert' || is_tax( 'advert_category' )</code>, I suspect you are using the wrong operator. You should be using the <code>AND</code> operator. I'm not going to explain this here as I already done something similar <a href=\"https://wordpress.stackexchange.com/a/155506/31545\">here</a>. Note that, with the current setup, whenever you are viewing a post from the post type <code>advert</code>, your condition will return true and fire whether or not the second condition (<em><code>is_tax( 'advert_category' )</code></em>) fails.</p>\n</li>\n<li><p>If you need to target a term according to parent_child order, you simply need to check the term object's <code>$parent</code> property. A value of <code>0</code> means the term is a parent, any other value means that the term is a child/grandchild/grand-grandchild/etc term</p>\n</li>\n</ul>\n<p>Lets drop the crappy globals and set the templates properly. I do not know how your theme exactly sets templates through the <code>$wpgo_global_column_layout</code>, but the following should work with priority. I have commented the code to make it easy to follow</p>\n<h2>FOR SINGLE PAGES:</h2>\n<pre><code>add_filter( 'single_template', function ( $template )\n{\n // Remove all filters from the current filter\n remove_all_filters( current_filter(), PHP_INT_MAX );\n \n /**\n * Get the current single post object. We will use get_queried_object\n * as it is safer to use as $post\n *\n * @see https://wordpress.stackexchange.com/q/167706/31545\n */\n $current_post = get_queried_object();\n \n // Check if the current post belongs to the advert post type, if not, bail\n if ( $current_post-&gt;post_type !== 'advert' )\n return $template;\n \n // Get the post terms\n $terms = get_the_terms( \n $current_post, // Current post object\n 'advert_category' // Taxonomy name\n );\n \n // If $terms are empty or throws a WP_Error object, bail\n if ( !$terms || is_wp_error( $terms ) )\n return $template\n \n /**\n * Get the first term and check if it is a top level term or not.\n * Load template according to parent value\n *\n * NOTE, this only work correctly if the post has one term only\n */\n if ( $terms[0]-&gt;parent == 0 ) {\n $part = 'single-parent.php'; // Set the template to use for parent terms\n } else {\n $part = 'single-child.php'; // Set the child term template\n }\n \n // Check if the template exists, if not bail\n $locate_template = locate_template( $part );\n if ( !$locate_template ) \n return $template;\n \n // We have reached this point, set our custom template\n return $template = $locate_template;\n}, PHP_INT_MAX + 1 );\n</code></pre>\n<h2>FOR TAXONOMY PAGES:</h2>\n<pre><code>add_filter( 'taxonomy_template', function ( $template )\n{\n // Remove all filters from the current filter\n remove_all_filters( current_filter(), PHP_INT_MAX );\n\n // Get the current term object. We will use get_queried_object\n $current_term = get_queried_object();\n \n // If the current term does not belong to advert post type, bail\n if ( $current_term-&gt;taxonomy !== 'advert_category' )\n return $template;\n \n // Check if the term is top level or not and set template accordingly\n if ( $current_term-&gt;parent == 0 ) {\n $part = 'taxonomy-parent.php'; // Set the template to use for parent terms\n } else {\n $part = 'taxonomy-child.php'; // Set the child term template\n }\n \n // Check if the template exists, if not bail\n $locate_template = locate_template( $part );\n if ( !$locate_template ) \n return $template;\n \n // We have reached this point, set our custom template\n return $template = $locate_template;\n}, PHP_INT_MAX + 1 );\n</code></pre>\n<p>Just one note, all the code is untested, so make sure to test it locally first with debug set to true. Also modify and abuse the code to suit your needs</p>\n" }, { "answer_id": 209475, "author": "Luis Sanz", "author_id": 81084, "author_profile": "https://wordpress.stackexchange.com/users/81084", "pm_score": 1, "selected": false, "text": "<p>You have two problems in your function:</p>\n\n<ul>\n<li>You are missing an argument in the \"single_template\" filter and therefore the filter is not returning what it should.</li>\n<li>Also you are calling has_term() without specifying the taxonomy you are trying to search into.</li>\n</ul>\n\n<p>Check this out:</p>\n\n<pre><code>function my_advert_single_template( $single_template ) {\n global $post;\n global $wpgo_global_column_layout;\n\n if ( $post-&gt;post_type == 'advert' || has_term( 'util-categorie', 'advert_category' ) ) {\n $wpgo_global_column_layout = \"2-col-l\";\n }\n\n return $single_template;\n}\nadd_filter( 'single_template', 'my_advert_single_template' );\n</code></pre>\n" } ]
2015/11/22
[ "https://wordpress.stackexchange.com/questions/209467", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25187/" ]
I have a custom post type named 'advert' and a related custom taxonomy named 'advert\_category', created by a 3rd party plugin. I run in a plugin an `if` statement that must to set (as I expect) a specific theme layout for single adverts (example.com/advert/a-single-advert.html) and for custom taxonomy archive pages (example.com/advert-category/services/), but the second condition `is_tax( 'advert_category' )` doesn't work. What is wrong here? My code: ``` function my_advert_single_template( ) { global $post; global $wpgo_global_column_layout; if ( $post->post_type == 'advert' || is_tax( 'advert_category' ) ) { $wpgo_global_column_layout = "2-col-l"; } } add_filter( 'single_template', 'my_advert_single_template' ); ``` This is how the custom post type and the custom taxonomy are registered: ``` // register post type and taxonomy in order to allow default data insertion. register_post_type( 'advert' ); register_taxonomy( 'advert_category', 'advert' ); $hid = wp_insert_post(array( 'post_type' => 'page', 'post_status' => 'publish', 'post_title' => 'Adverts', 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_content' => "[adverts_list]" )); $aid = wp_insert_post(array( 'post_type' => 'page', 'post_status' => 'publish', 'post_title' => 'Add', 'post_parent' => $hid, 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_content' => "[adverts_add]" )); $mid = wp_insert_post(array( 'post_type' => 'page', 'post_status' => 'publish', 'post_title' => 'Manage', 'post_parent' => $hid, 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_content' => "[adverts_manage]" )); wp_insert_term( 'Default', 'advert_category' ); ```
You hava a lot of issues here: * `pre_get_posts` is not the correct hook to set templates. `pre_get_posts` are used to alter the ain query query vars just before the SQL are build to run the main query's query * A filter should **always** return something. Not doing this will have unexpected behavior, and forgetting about this can have you on a wild goose chase for hours debugging the issue. * Using globals to control theme features or to store any kind of data is bad practice and not very safe coding. WordPress has already made such a huge mess of globals, particularly naming conventions. Just check how newbies (*that does not know Wordpress*) unknowingly use variable like `$post` and `$posts` as local variables. These are native globals uses by WordPress, and using them as local variables breaks the values of these globals. Because of this, something on the page goes wrong, there are no errors, so you are stuck on a wild goose chase trying to debug something that you have unknowingly broke. Globals are pure evil and you should avoid using them. Just think, if you use the variable `$wpgo_global_column_layout` for the query arguments of a custom query, you will break the value of the template that needs to be set, your template does not load because the value of `$wpgo_global_column_layout` are not recognized as a valid template name, you are stuffed and don't know why your template does not load as your code are 100% that should load a custom template * `is_tax()` is the wrong check to use to check whether a post has a certain term or not, `is_tax()` simply checks if you are on a taxonomy archive or not. You should be using [`has_term()`](https://developer.wordpress.org/reference/functions/has_term/) which do just that, checks if a certain post has a certain term * If you need to set a template for a taxonomy page, `single_template` is the wrong hook, you should be using the [`taxonomy_template`](https://developer.wordpress.org/reference/hooks/type_template/) hook or the more generic [`template_include`](https://developer.wordpress.org/reference/hooks/template_include/) filter * In the line `$post->post_type == 'advert' || is_tax( 'advert_category' )`, I suspect you are using the wrong operator. You should be using the `AND` operator. I'm not going to explain this here as I already done something similar [here](https://wordpress.stackexchange.com/a/155506/31545). Note that, with the current setup, whenever you are viewing a post from the post type `advert`, your condition will return true and fire whether or not the second condition (*`is_tax( 'advert_category' )`*) fails. * If you need to target a term according to parent\_child order, you simply need to check the term object's `$parent` property. A value of `0` means the term is a parent, any other value means that the term is a child/grandchild/grand-grandchild/etc term Lets drop the crappy globals and set the templates properly. I do not know how your theme exactly sets templates through the `$wpgo_global_column_layout`, but the following should work with priority. I have commented the code to make it easy to follow FOR SINGLE PAGES: ----------------- ``` add_filter( 'single_template', function ( $template ) { // Remove all filters from the current filter remove_all_filters( current_filter(), PHP_INT_MAX ); /** * Get the current single post object. We will use get_queried_object * as it is safer to use as $post * * @see https://wordpress.stackexchange.com/q/167706/31545 */ $current_post = get_queried_object(); // Check if the current post belongs to the advert post type, if not, bail if ( $current_post->post_type !== 'advert' ) return $template; // Get the post terms $terms = get_the_terms( $current_post, // Current post object 'advert_category' // Taxonomy name ); // If $terms are empty or throws a WP_Error object, bail if ( !$terms || is_wp_error( $terms ) ) return $template /** * Get the first term and check if it is a top level term or not. * Load template according to parent value * * NOTE, this only work correctly if the post has one term only */ if ( $terms[0]->parent == 0 ) { $part = 'single-parent.php'; // Set the template to use for parent terms } else { $part = 'single-child.php'; // Set the child term template } // Check if the template exists, if not bail $locate_template = locate_template( $part ); if ( !$locate_template ) return $template; // We have reached this point, set our custom template return $template = $locate_template; }, PHP_INT_MAX + 1 ); ``` FOR TAXONOMY PAGES: ------------------- ``` add_filter( 'taxonomy_template', function ( $template ) { // Remove all filters from the current filter remove_all_filters( current_filter(), PHP_INT_MAX ); // Get the current term object. We will use get_queried_object $current_term = get_queried_object(); // If the current term does not belong to advert post type, bail if ( $current_term->taxonomy !== 'advert_category' ) return $template; // Check if the term is top level or not and set template accordingly if ( $current_term->parent == 0 ) { $part = 'taxonomy-parent.php'; // Set the template to use for parent terms } else { $part = 'taxonomy-child.php'; // Set the child term template } // Check if the template exists, if not bail $locate_template = locate_template( $part ); if ( !$locate_template ) return $template; // We have reached this point, set our custom template return $template = $locate_template; }, PHP_INT_MAX + 1 ); ``` Just one note, all the code is untested, so make sure to test it locally first with debug set to true. Also modify and abuse the code to suit your needs
209,503
<p>I have a custom comments loop on my <code>author.php</code> page. I am trying to get the post id so that I can echo the permalink for the post that the comment belongs to. Also so I can echo some post meta custom fields. </p> <p>This is what my loop looks like now -</p> <pre><code>&lt;?php $object = get_queried_object(); $authorID = get_queried_object()-&gt;ID; $author_email = get_the_author_meta( 'user_email', $authorID ); $postid = get_queried_object()-&gt;post-&gt;ID; $args = array( 'user_id' =&gt; $authorID, 'post_id' =&gt; $postid, ); // The Query $comments_query = new WP_Comment_Query; $comments = $comments_query-&gt;query( $args ); // Comment Loop if ( $comments ) { foreach ( $comments as $comment ) { ?&gt; </code></pre> <p>I tried place a normal post loop within this but things got weird. The part I need the post meta for is this --</p> <pre><code>&lt;div class="full-divs"&gt; &lt;strong&gt; &lt;a href="&lt;?php echo get_permalink(); ?&gt;"&gt; View &lt;?php $property_address = get_post_meta( get_the_ID(), 'imic_property_site_address', true ); echo $property_address; ?&gt; &lt;/a&gt; &lt;/strong&gt; &lt;/div&gt; </code></pre> <p>What am I doing wrong?</p>
[ { "answer_id": 209504, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>Note that it might be easier to use <code>get_comments()</code> here, since it's defined as:</p>\n\n<pre><code>function get_comments( $args = '' ) {\n $query = new WP_Comment_Query;\n return $query-&gt;query( $args );\n}\n</code></pre>\n\n<p>If you need the <em>comment url</em>, within your <code>foreach</code> comment loop, you can use:</p>\n\n<pre><code>$comment_url = esc_url( get_comment_link( $comment ) );\n</code></pre>\n\n<p>You can also get the <em>post id</em> from the <code>$comment</code> object with: </p>\n\n<pre><code>$post_id = $comment-&gt;comment_post_ID;\n</code></pre>\n\n<p>then you can use that to retrieve the <em>custom post meta</em>:</p>\n\n<pre><code>$property_address = get_post_meta( $post_id ,'imic_property_site_address',true);\n</code></pre>\n\n<p>To get the corresponding <code>post permalink</code></p>\n\n<pre><code>$post_url = esc_url( get_permalink( $post_id ) );\n</code></pre>\n" }, { "answer_id": 209505, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>There is no <code>$post</code> property in <code>get_queried_object()</code>. <code>get_queried_object()</code> returns info about the current author when viewing the author archive page. You can do a <code>var_dump()</code> to check what <code>get_queried_object()</code> return</p>\n\n<pre><code>var_dump( get_queried_object() );\n</code></pre>\n\n<p>This is why your code fails. I am really not sure what you need to achieve here, but any post info can be accessed by using the main query object</p>\n\n<ul>\n<li><p><code>$wp_query-&gt;posts</code> returns an array of post objects. This is the posts that will be displayed by the loop</p></li>\n<li><p><code>$wp_query-&gt;post</code> returns the first post object of the loop, the same post object as <code>$post</code> before the loop</p></li>\n</ul>\n\n<p>I probably think this is what you are after</p>\n" } ]
2015/11/22
[ "https://wordpress.stackexchange.com/questions/209503", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24067/" ]
I have a custom comments loop on my `author.php` page. I am trying to get the post id so that I can echo the permalink for the post that the comment belongs to. Also so I can echo some post meta custom fields. This is what my loop looks like now - ``` <?php $object = get_queried_object(); $authorID = get_queried_object()->ID; $author_email = get_the_author_meta( 'user_email', $authorID ); $postid = get_queried_object()->post->ID; $args = array( 'user_id' => $authorID, 'post_id' => $postid, ); // The Query $comments_query = new WP_Comment_Query; $comments = $comments_query->query( $args ); // Comment Loop if ( $comments ) { foreach ( $comments as $comment ) { ?> ``` I tried place a normal post loop within this but things got weird. The part I need the post meta for is this -- ``` <div class="full-divs"> <strong> <a href="<?php echo get_permalink(); ?>"> View <?php $property_address = get_post_meta( get_the_ID(), 'imic_property_site_address', true ); echo $property_address; ?> </a> </strong> </div> ``` What am I doing wrong?
Note that it might be easier to use `get_comments()` here, since it's defined as: ``` function get_comments( $args = '' ) { $query = new WP_Comment_Query; return $query->query( $args ); } ``` If you need the *comment url*, within your `foreach` comment loop, you can use: ``` $comment_url = esc_url( get_comment_link( $comment ) ); ``` You can also get the *post id* from the `$comment` object with: ``` $post_id = $comment->comment_post_ID; ``` then you can use that to retrieve the *custom post meta*: ``` $property_address = get_post_meta( $post_id ,'imic_property_site_address',true); ``` To get the corresponding `post permalink` ``` $post_url = esc_url( get_permalink( $post_id ) ); ```
209,506
<p>When I insert a large image into a post, I would like the image to open in a new browser tab rather than within the existing tab. </p> <p>I know that this can be accomplished by adding <code>target="_blank"</code> to the link, but how do I add this attribute to the image links?</p>
[ { "answer_id": 209504, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>Note that it might be easier to use <code>get_comments()</code> here, since it's defined as:</p>\n\n<pre><code>function get_comments( $args = '' ) {\n $query = new WP_Comment_Query;\n return $query-&gt;query( $args );\n}\n</code></pre>\n\n<p>If you need the <em>comment url</em>, within your <code>foreach</code> comment loop, you can use:</p>\n\n<pre><code>$comment_url = esc_url( get_comment_link( $comment ) );\n</code></pre>\n\n<p>You can also get the <em>post id</em> from the <code>$comment</code> object with: </p>\n\n<pre><code>$post_id = $comment-&gt;comment_post_ID;\n</code></pre>\n\n<p>then you can use that to retrieve the <em>custom post meta</em>:</p>\n\n<pre><code>$property_address = get_post_meta( $post_id ,'imic_property_site_address',true);\n</code></pre>\n\n<p>To get the corresponding <code>post permalink</code></p>\n\n<pre><code>$post_url = esc_url( get_permalink( $post_id ) );\n</code></pre>\n" }, { "answer_id": 209505, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>There is no <code>$post</code> property in <code>get_queried_object()</code>. <code>get_queried_object()</code> returns info about the current author when viewing the author archive page. You can do a <code>var_dump()</code> to check what <code>get_queried_object()</code> return</p>\n\n<pre><code>var_dump( get_queried_object() );\n</code></pre>\n\n<p>This is why your code fails. I am really not sure what you need to achieve here, but any post info can be accessed by using the main query object</p>\n\n<ul>\n<li><p><code>$wp_query-&gt;posts</code> returns an array of post objects. This is the posts that will be displayed by the loop</p></li>\n<li><p><code>$wp_query-&gt;post</code> returns the first post object of the loop, the same post object as <code>$post</code> before the loop</p></li>\n</ul>\n\n<p>I probably think this is what you are after</p>\n" } ]
2015/11/22
[ "https://wordpress.stackexchange.com/questions/209506", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70476/" ]
When I insert a large image into a post, I would like the image to open in a new browser tab rather than within the existing tab. I know that this can be accomplished by adding `target="_blank"` to the link, but how do I add this attribute to the image links?
Note that it might be easier to use `get_comments()` here, since it's defined as: ``` function get_comments( $args = '' ) { $query = new WP_Comment_Query; return $query->query( $args ); } ``` If you need the *comment url*, within your `foreach` comment loop, you can use: ``` $comment_url = esc_url( get_comment_link( $comment ) ); ``` You can also get the *post id* from the `$comment` object with: ``` $post_id = $comment->comment_post_ID; ``` then you can use that to retrieve the *custom post meta*: ``` $property_address = get_post_meta( $post_id ,'imic_property_site_address',true); ``` To get the corresponding `post permalink` ``` $post_url = esc_url( get_permalink( $post_id ) ); ```
209,529
<p>I want to order a custom post type by post meta field. This query works fine partially and load results. The problem is that the order of results vary at each time this query is executed. I have found some duplicates also in last few pages. Can you please help me figure out what sort of thing going there?</p> <pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND wp_posts.post_type = 'estate_agent' AND ((wp_posts.post_status = 'publish')) AND (wp_postmeta.meta_key = 'package_id') GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value+0 DESC LIMIT 0, 10 </code></pre> <p><a href="https://i.stack.imgur.com/zyc3v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zyc3v.png" alt="enter image description here"></a></p> <p><strong>Updated</strong> Actually I 'm using the Wordpress way for running above query. The above is the raw query output from Wordpress debug plugin. I'm really sorry for the confusion. This is what I have tried.</p> <pre><code>$args = array( 'post_type' =&gt; 'estate_agent', 'post_status' =&gt; 'publish', 'meta_key' =&gt; 'package_id', 'orderby' =&gt; 'meta_value_num', 'order' =&gt; 'DESC', 'paged' =&gt; $paged, 'posts_per_page' =&gt; 10, 'cache_results' =&gt; false, ); $agent_selection = new WP_Query($args); </code></pre>
[ { "answer_id": 209504, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>Note that it might be easier to use <code>get_comments()</code> here, since it's defined as:</p>\n\n<pre><code>function get_comments( $args = '' ) {\n $query = new WP_Comment_Query;\n return $query-&gt;query( $args );\n}\n</code></pre>\n\n<p>If you need the <em>comment url</em>, within your <code>foreach</code> comment loop, you can use:</p>\n\n<pre><code>$comment_url = esc_url( get_comment_link( $comment ) );\n</code></pre>\n\n<p>You can also get the <em>post id</em> from the <code>$comment</code> object with: </p>\n\n<pre><code>$post_id = $comment-&gt;comment_post_ID;\n</code></pre>\n\n<p>then you can use that to retrieve the <em>custom post meta</em>:</p>\n\n<pre><code>$property_address = get_post_meta( $post_id ,'imic_property_site_address',true);\n</code></pre>\n\n<p>To get the corresponding <code>post permalink</code></p>\n\n<pre><code>$post_url = esc_url( get_permalink( $post_id ) );\n</code></pre>\n" }, { "answer_id": 209505, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>There is no <code>$post</code> property in <code>get_queried_object()</code>. <code>get_queried_object()</code> returns info about the current author when viewing the author archive page. You can do a <code>var_dump()</code> to check what <code>get_queried_object()</code> return</p>\n\n<pre><code>var_dump( get_queried_object() );\n</code></pre>\n\n<p>This is why your code fails. I am really not sure what you need to achieve here, but any post info can be accessed by using the main query object</p>\n\n<ul>\n<li><p><code>$wp_query-&gt;posts</code> returns an array of post objects. This is the posts that will be displayed by the loop</p></li>\n<li><p><code>$wp_query-&gt;post</code> returns the first post object of the loop, the same post object as <code>$post</code> before the loop</p></li>\n</ul>\n\n<p>I probably think this is what you are after</p>\n" } ]
2015/11/23
[ "https://wordpress.stackexchange.com/questions/209529", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64277/" ]
I want to order a custom post type by post meta field. This query works fine partially and load results. The problem is that the order of results vary at each time this query is executed. I have found some duplicates also in last few pages. Can you please help me figure out what sort of thing going there? ``` SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND wp_posts.post_type = 'estate_agent' AND ((wp_posts.post_status = 'publish')) AND (wp_postmeta.meta_key = 'package_id') GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value+0 DESC LIMIT 0, 10 ``` [![enter image description here](https://i.stack.imgur.com/zyc3v.png)](https://i.stack.imgur.com/zyc3v.png) **Updated** Actually I 'm using the Wordpress way for running above query. The above is the raw query output from Wordpress debug plugin. I'm really sorry for the confusion. This is what I have tried. ``` $args = array( 'post_type' => 'estate_agent', 'post_status' => 'publish', 'meta_key' => 'package_id', 'orderby' => 'meta_value_num', 'order' => 'DESC', 'paged' => $paged, 'posts_per_page' => 10, 'cache_results' => false, ); $agent_selection = new WP_Query($args); ```
Note that it might be easier to use `get_comments()` here, since it's defined as: ``` function get_comments( $args = '' ) { $query = new WP_Comment_Query; return $query->query( $args ); } ``` If you need the *comment url*, within your `foreach` comment loop, you can use: ``` $comment_url = esc_url( get_comment_link( $comment ) ); ``` You can also get the *post id* from the `$comment` object with: ``` $post_id = $comment->comment_post_ID; ``` then you can use that to retrieve the *custom post meta*: ``` $property_address = get_post_meta( $post_id ,'imic_property_site_address',true); ``` To get the corresponding `post permalink` ``` $post_url = esc_url( get_permalink( $post_id ) ); ```
209,530
<p>Is there a way to use different templates for different <em>levels</em> within a hierarchical taxonomy, specified by filename. I know about <code>taxonomy-taxonomyname.php</code> and <code>taxonomy-taxonomyname-term.php</code> templates. Looking for a more generic "per taxonomy level" based method.</p> <p>So, a taxonomy named <strong>Earth</strong> might contain:</p> <ol> <li>Africa <ul> <li>Cameroon</li> <li>Congo</li> <li>Senegal</li> </ul></li> <li>Asia <ul> <li>Japan</li> <li>Korea</li> </ul></li> <li>Europe <ul> <li>Greece</li> <li>...</li> </ul></li> <li>South America</li> <li>...</li> </ol> <p>Is there a way to have one template for Africa, Asia, Europe and South America (<code>earth-numbers-level.php</code>)... and another template for Cameroon, Congo, Japan, Greece... (<code>earth-bullets-level.php</code>)?</p> <p>Looking over a few different template hierarchy docs, I'm guessing not. If that's true, <strong>what's the best/most efficient way to differentiate taxonomy levels within <code>taxonomy-earth.php</code></strong> so that I might use different template parts for each?</p>
[ { "answer_id": 209504, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>Note that it might be easier to use <code>get_comments()</code> here, since it's defined as:</p>\n\n<pre><code>function get_comments( $args = '' ) {\n $query = new WP_Comment_Query;\n return $query-&gt;query( $args );\n}\n</code></pre>\n\n<p>If you need the <em>comment url</em>, within your <code>foreach</code> comment loop, you can use:</p>\n\n<pre><code>$comment_url = esc_url( get_comment_link( $comment ) );\n</code></pre>\n\n<p>You can also get the <em>post id</em> from the <code>$comment</code> object with: </p>\n\n<pre><code>$post_id = $comment-&gt;comment_post_ID;\n</code></pre>\n\n<p>then you can use that to retrieve the <em>custom post meta</em>:</p>\n\n<pre><code>$property_address = get_post_meta( $post_id ,'imic_property_site_address',true);\n</code></pre>\n\n<p>To get the corresponding <code>post permalink</code></p>\n\n<pre><code>$post_url = esc_url( get_permalink( $post_id ) );\n</code></pre>\n" }, { "answer_id": 209505, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>There is no <code>$post</code> property in <code>get_queried_object()</code>. <code>get_queried_object()</code> returns info about the current author when viewing the author archive page. You can do a <code>var_dump()</code> to check what <code>get_queried_object()</code> return</p>\n\n<pre><code>var_dump( get_queried_object() );\n</code></pre>\n\n<p>This is why your code fails. I am really not sure what you need to achieve here, but any post info can be accessed by using the main query object</p>\n\n<ul>\n<li><p><code>$wp_query-&gt;posts</code> returns an array of post objects. This is the posts that will be displayed by the loop</p></li>\n<li><p><code>$wp_query-&gt;post</code> returns the first post object of the loop, the same post object as <code>$post</code> before the loop</p></li>\n</ul>\n\n<p>I probably think this is what you are after</p>\n" } ]
2015/11/23
[ "https://wordpress.stackexchange.com/questions/209530", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44795/" ]
Is there a way to use different templates for different *levels* within a hierarchical taxonomy, specified by filename. I know about `taxonomy-taxonomyname.php` and `taxonomy-taxonomyname-term.php` templates. Looking for a more generic "per taxonomy level" based method. So, a taxonomy named **Earth** might contain: 1. Africa * Cameroon * Congo * Senegal 2. Asia * Japan * Korea 3. Europe * Greece * ... 4. South America 5. ... Is there a way to have one template for Africa, Asia, Europe and South America (`earth-numbers-level.php`)... and another template for Cameroon, Congo, Japan, Greece... (`earth-bullets-level.php`)? Looking over a few different template hierarchy docs, I'm guessing not. If that's true, **what's the best/most efficient way to differentiate taxonomy levels within `taxonomy-earth.php`** so that I might use different template parts for each?
Note that it might be easier to use `get_comments()` here, since it's defined as: ``` function get_comments( $args = '' ) { $query = new WP_Comment_Query; return $query->query( $args ); } ``` If you need the *comment url*, within your `foreach` comment loop, you can use: ``` $comment_url = esc_url( get_comment_link( $comment ) ); ``` You can also get the *post id* from the `$comment` object with: ``` $post_id = $comment->comment_post_ID; ``` then you can use that to retrieve the *custom post meta*: ``` $property_address = get_post_meta( $post_id ,'imic_property_site_address',true); ``` To get the corresponding `post permalink` ``` $post_url = esc_url( get_permalink( $post_id ) ); ```
209,531
<p>The following coding is the out come of an other page php echo</p> <pre><code>user_list.php: $myarray=array(); ... ... $myjson = json_encode($myarray); echo $myuser-&gt;searchUser($myjson); </code></pre> <p>and the result of html is:</p> <pre><code>[{"userID":"1","username":"\u9ec3\u9ec3\u9ec3", "sex":"F","password":"1bbd886460827015e5d605ed44252251", "emails":"[email protected]","regdate":"2015-11-03 00:00:00", "dob":"1994-11-02","educationID":"6","positionID":"1", "home":"12341234","mobile":"21800000","address":"AC2 5\/F Rm5501","grade":"Y1","status":"0","office_tel":"41234123", "inviter":null,"inviter_relation":null,"believe":"0", "remark":null}] </code></pre> <p>As I know, here is a array not an object. So how i can get those data in other page like this?</p> <pre><code>$(".edituser").click(function () { var user = $(this).data("id"); $.ajax({ url:"user_list.php", data:"userID="+user, type : "POST", dataType: "json", success:function(data){ console.log(data); }, error:function(xhr){ alert('Ajax request fail'); } }); }); </code></pre> <p>How get i get the data in ajax? thx</p>
[ { "answer_id": 209535, "author": "Dijo David", "author_id": 4026, "author_profile": "https://wordpress.stackexchange.com/users/4026", "pm_score": 0, "selected": false, "text": "<p>Change the format in the following method.</p>\n\n<pre><code>$myuser-&gt;searchUser($myjson)\n</code></pre>\n\n<p>OR</p>\n\n<p>Use the 0 index to get the JSON object.</p>\n\n<pre><code>resultData[0] //will return JSON object\n</code></pre>\n\n<p>I will recommend changing the format in PHP method. All the best!</p>\n" }, { "answer_id": 209538, "author": "Nikhil", "author_id": 26760, "author_profile": "https://wordpress.stackexchange.com/users/26760", "pm_score": 2, "selected": true, "text": "<p>There are two methods to access the object.</p>\n\n<p><strong>1. Ajax response.</strong></p>\n\n<pre><code>$.ajax({\n url:\"your_file.php\",\n type : \"POST\",\n data : your_data,\n dataType: \"json\",\n success:function(data){ \n // Retrieve the object\n var result = data[0];\n // Grab username from the object\n console.log(result['username']);\n },\n error:function(xhr){\n alert('Ajax request fail');\n }\n});\n</code></pre>\n\n<p><strong>2. Server side script</strong></p>\n\n<pre><code>$yourArray = array();\n$yourJson = json_encode($yourArray);\n$userData = $yourJson-&gt;searchUser($yourJson);\n$jsonData = json_decode($userData);\n// Ouput the inner contents\necho json_encode($jsonData[0]);\n</code></pre>\n" } ]
2015/11/23
[ "https://wordpress.stackexchange.com/questions/209531", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84094/" ]
The following coding is the out come of an other page php echo ``` user_list.php: $myarray=array(); ... ... $myjson = json_encode($myarray); echo $myuser->searchUser($myjson); ``` and the result of html is: ``` [{"userID":"1","username":"\u9ec3\u9ec3\u9ec3", "sex":"F","password":"1bbd886460827015e5d605ed44252251", "emails":"[email protected]","regdate":"2015-11-03 00:00:00", "dob":"1994-11-02","educationID":"6","positionID":"1", "home":"12341234","mobile":"21800000","address":"AC2 5\/F Rm5501","grade":"Y1","status":"0","office_tel":"41234123", "inviter":null,"inviter_relation":null,"believe":"0", "remark":null}] ``` As I know, here is a array not an object. So how i can get those data in other page like this? ``` $(".edituser").click(function () { var user = $(this).data("id"); $.ajax({ url:"user_list.php", data:"userID="+user, type : "POST", dataType: "json", success:function(data){ console.log(data); }, error:function(xhr){ alert('Ajax request fail'); } }); }); ``` How get i get the data in ajax? thx
There are two methods to access the object. **1. Ajax response.** ``` $.ajax({ url:"your_file.php", type : "POST", data : your_data, dataType: "json", success:function(data){ // Retrieve the object var result = data[0]; // Grab username from the object console.log(result['username']); }, error:function(xhr){ alert('Ajax request fail'); } }); ``` **2. Server side script** ``` $yourArray = array(); $yourJson = json_encode($yourArray); $userData = $yourJson->searchUser($yourJson); $jsonData = json_decode($userData); // Ouput the inner contents echo json_encode($jsonData[0]); ```
209,532
<p>I've added functionality to upload profile picture by following <a href="http://www.flyinghippo.com/blog/adding-custom-fields-uploading-images-wordpress-users/" rel="noreferrer">THIS guide</a>.</p> <p>I can't find an online guide or any documentation about WP hooks.. <strong>How to replace Gravatar profile pictures (in comment section) with custom uploaded images?</strong></p> <p>I don't want to force my users to register Gravatar in order to change their profile picture on my site.</p>
[ { "answer_id": 209536, "author": "PHP Team", "author_id": 60469, "author_profile": "https://wordpress.stackexchange.com/users/60469", "pm_score": -1, "selected": true, "text": "<p>If you are set your custom or uploaded profile picture and need to see on front end, you can use below function .</p>\n\n<pre><code>&lt;?php echo get_avatar( $id_or_email, $size, $default, $alt, $args ); ?&gt; \n</code></pre>\n\n<p>If you have to change your gravatar to custom profile picture you can refer below link :\n<a href=\"http://www.wpbeginner.com/wp-tutorials/how-to-change-the-default-gravatar-on-wordpress/\" rel=\"nofollow\">http://www.wpbeginner.com/wp-tutorials/how-to-change-the-default-gravatar-on-wordpress/</a></p>\n" }, { "answer_id": 209547, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 3, "selected": false, "text": "<p>The hook you need is the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/get_avatar\" rel=\"noreferrer\"><code>get_avatar</code> filter</a>. It returs the image HTML element representing the user avatar.</p>\n\n<pre><code>add_filter( 'get_avatar', 'cyb_get_avatar', 10, 5 );\nfunction cyb_get_avatar( $avatar = '', $id_or_email, $size = 96, $default = '', $alt = '' ) {\n\n // Replace $avatar with your own image element, for example\n // $avatar = \"&lt;img alt='$alt' src='your_new_avatar_url' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' /&gt;\"\n\n return $avatar;\n\n}\n</code></pre>\n\n<p>Note that using this filter, you can still let users use gravatar. You could check if the user has uploaded an avatar to your site, then use it, it not you return normal <code>$avatar</code>, which will be from gravatar if user has one. (If you add to question the code you are using to store user avatars, I can give a exact working code):</p>\n\n<pre><code>add_filter( 'get_avatar', 'cyb_get_avatar', 10, 5 );\nfunction cyb_get_avatar( $avatar = '', $id_or_email, $size = 96, $default = '', $alt = '' ) {\n\n if( \"user_has_uploaded_a_local_avatar\" ) {\n // Replace $avatar with your own image element, for example\n // $avatar = \"&lt;img alt='$alt' src='your_new_avatar_url' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' /&gt;\"\n }\n\n // if user didn't upload a local avatar,\n // normal avatar will be used, which can be from gravatar\n return $avatar;\n\n}\n</code></pre>\n" }, { "answer_id": 286108, "author": "JPollock", "author_id": 25300, "author_profile": "https://wordpress.stackexchange.com/users/25300", "pm_score": 3, "selected": false, "text": "<p>Presuming that the user has their avatar saved, as the ID of an attachment, store in user meta, as the field <code>field_with_custom_avatar_id</code>, you could do this to show that attachment if the value is saved: </p>\n\n<pre><code>add_filter( 'get_avatar', 'slug_get_avatar', 10, 5 );\nfunction slug_get_avatar( $avatar, $id_or_email, $size, $default, $alt ) {\n\n //If is email, try and find user ID\n if( ! is_numeric( $id_or_email ) &amp;&amp; is_email( $id_or_email ) ){\n $user = get_user_by( 'email', $id_or_email );\n if( $user ){\n $id_or_email = $user-&gt;ID;\n }\n }\n\n //if not user ID, return\n if( ! is_numeric( $id_or_email ) ){\n return $avatar;\n }\n\n //Find ID of attachment saved user meta\n $saved = get_user_meta( $id_or_email, 'field_with_custom_avatar_id', true );\n if( 0 &lt; absint( $saved ) ) {\n //return saved image\n return wp_get_attachment_image( $saved, [ $size, $size ], false, ['alt' =&gt; $alt] );\n }\n\n //return normal\n return $avatar;\n\n}\n</code></pre>\n\n<p>Or, if it is saved as a URL of the image, in the user meta field <code>field_with_custom_avatar</code> -</p>\n\n<pre><code>add_filter( 'get_avatar', 'slug_get_avatar', 10, 5 );\nfunction slug_get_avatar( $avatar, $id_or_email, $size, $default, $alt ) {\n\n //If is email, try and find user ID\n if( ! is_numeric( $id_or_email ) &amp;&amp; is_email( $id_or_email ) ){\n $user = get_user_by( 'email', $id_or_email );\n if( $user ){\n $id_or_email = $user-&gt;ID;\n }\n }\n\n //if not user ID, return\n if( ! is_numeric( $id_or_email ) ){\n return $avatar;\n }\n\n //Find URL of saved avatar in user meta\n $saved = get_user_meta( $id_or_email, 'field_with_custom_avatar', true );\n //check if it is a URL\n if( filter_var( $saved, FILTER_VALIDATE_URL ) ) {\n //return saved image\n return sprintf( '&lt;img src=\"%\" alt=\"%\" /&gt;', esc_url( $saved ), esc_attr( $alt ) );\n }\n\n //return normal\n return $avatar;\n\n}\n</code></pre>\n" }, { "answer_id": 325038, "author": "atonus", "author_id": 158622, "author_profile": "https://wordpress.stackexchange.com/users/158622", "pm_score": 0, "selected": false, "text": "<p>This is a \"me too\" comment but with a solution :)</p>\n\n<p>So when I enabled comments section I got an error from <code>is_email($id_or_email)</code>.</p>\n\n<p>Here's the error</p>\n\n<p><strong>strlen() expects parameter 1 to be string, object given in /home/my_theme/public_html/wp-includes/formatting.php on line 2891</strong></p>\n\n<p>Error happens, cause <code>$id_or_email</code> contains actually an object and not a string.</p>\n\n<p>I found a workaround by fetching email string from the object <code>$id_or_email-&gt;comment_author_email</code></p>\n\n<p>So I changed <code>$id_or_email</code> to <code>$id_or_email-&gt;comment_author_email</code> and now I get the right avatar picture to the comments and no errors.</p>\n" } ]
2015/11/23
[ "https://wordpress.stackexchange.com/questions/209532", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80903/" ]
I've added functionality to upload profile picture by following [THIS guide](http://www.flyinghippo.com/blog/adding-custom-fields-uploading-images-wordpress-users/). I can't find an online guide or any documentation about WP hooks.. **How to replace Gravatar profile pictures (in comment section) with custom uploaded images?** I don't want to force my users to register Gravatar in order to change their profile picture on my site.
If you are set your custom or uploaded profile picture and need to see on front end, you can use below function . ``` <?php echo get_avatar( $id_or_email, $size, $default, $alt, $args ); ?> ``` If you have to change your gravatar to custom profile picture you can refer below link : <http://www.wpbeginner.com/wp-tutorials/how-to-change-the-default-gravatar-on-wordpress/>
209,537
<p>In my project I want to show product list in two ways on single page.</p> <ol> <li>First in gallery way in which 4 products in one row.(This I have already created).</li> <li>And second in list way(one product at a row) which I will create.</li> </ol> <p>But I actually what I want is that to provide an option to customers whether he/she want the products view in gallery form or in list. Two button(gallery and list) will be provide to them. BY clicking on gallery the view should be like gallery and vice versa.Any idea, how it can be done.</p> <p>NOTE: Ok, If anyone likes to give negative rating to any question then please also make some effort to explain the reason in the comment section, this won't take long. That will help us to find batter way of asking question.So don't reside your thoughts in your head, Share with everyone, that will be helpful. No Offence !</p>
[ { "answer_id": 209540, "author": "garth", "author_id": 80997, "author_profile": "https://wordpress.stackexchange.com/users/80997", "pm_score": 1, "selected": true, "text": "<p>Set a button, or dropdown menu, that calls a function to set a cookie and to switch between CSS files which contain the <code>_style</code> ID:</p>\n\n<pre><code>function switchStyle(style) {\n var file = $TMPL_URL + '/css/' + style;\n jQuery('head').append('&lt;link rel=\"stylesheet\" href=\"' + file + '\" type=\"text/css\" /&gt;');\n jQuery.cookie($TMPL_NAME + '_style', style, {\n expires: 365,\n path: '/'\n });\n}\n</code></pre>\n\n<p><code>jQuery.cookie</code> should be replaced with whatever your standard cookie function is. Change <code>expires: 365</code> to set whatever duration you wish, so the page remembers which setting was chosen for that user.</p>\n" }, { "answer_id": 209546, "author": "Dan ", "author_id": 5827, "author_profile": "https://wordpress.stackexchange.com/users/5827", "pm_score": 2, "selected": false, "text": "<p>I suggest either;</p>\n\n<p>1) A simple form with element which appends a parameter in the query string such as domain.com?view=list - you can use this value to alter the display of items in your PHP files.</p>\n\n<p>2) Use javaScript to toggle a class on the parent container for your items, then control the layout with CSS. This should be pretty easy and is the option I'd go for. </p>\n\n<p>Dan</p>\n" } ]
2015/11/23
[ "https://wordpress.stackexchange.com/questions/209537", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81621/" ]
In my project I want to show product list in two ways on single page. 1. First in gallery way in which 4 products in one row.(This I have already created). 2. And second in list way(one product at a row) which I will create. But I actually what I want is that to provide an option to customers whether he/she want the products view in gallery form or in list. Two button(gallery and list) will be provide to them. BY clicking on gallery the view should be like gallery and vice versa.Any idea, how it can be done. NOTE: Ok, If anyone likes to give negative rating to any question then please also make some effort to explain the reason in the comment section, this won't take long. That will help us to find batter way of asking question.So don't reside your thoughts in your head, Share with everyone, that will be helpful. No Offence !
Set a button, or dropdown menu, that calls a function to set a cookie and to switch between CSS files which contain the `_style` ID: ``` function switchStyle(style) { var file = $TMPL_URL + '/css/' + style; jQuery('head').append('<link rel="stylesheet" href="' + file + '" type="text/css" />'); jQuery.cookie($TMPL_NAME + '_style', style, { expires: 365, path: '/' }); } ``` `jQuery.cookie` should be replaced with whatever your standard cookie function is. Change `expires: 365` to set whatever duration you wish, so the page remembers which setting was chosen for that user.
209,549
<p>i'm using this function in my Wordpress index:</p> <pre><code>&lt;?php echo get_the_excerpt(); ?&gt; </code></pre> <p>But if the article contains an image in the first 50 words, I get the link of the image in this form:</p> <blockquote> <p>Immagine: <a href="https://i.imgur.com/UUsXR3w.jpg" rel="nofollow noreferrer">http://i.imgur.com/UUsXR3w.jpg</a></p> </blockquote> <p>How can I exclude images from the excerpt?</p>
[ { "answer_id": 209540, "author": "garth", "author_id": 80997, "author_profile": "https://wordpress.stackexchange.com/users/80997", "pm_score": 1, "selected": true, "text": "<p>Set a button, or dropdown menu, that calls a function to set a cookie and to switch between CSS files which contain the <code>_style</code> ID:</p>\n\n<pre><code>function switchStyle(style) {\n var file = $TMPL_URL + '/css/' + style;\n jQuery('head').append('&lt;link rel=\"stylesheet\" href=\"' + file + '\" type=\"text/css\" /&gt;');\n jQuery.cookie($TMPL_NAME + '_style', style, {\n expires: 365,\n path: '/'\n });\n}\n</code></pre>\n\n<p><code>jQuery.cookie</code> should be replaced with whatever your standard cookie function is. Change <code>expires: 365</code> to set whatever duration you wish, so the page remembers which setting was chosen for that user.</p>\n" }, { "answer_id": 209546, "author": "Dan ", "author_id": 5827, "author_profile": "https://wordpress.stackexchange.com/users/5827", "pm_score": 2, "selected": false, "text": "<p>I suggest either;</p>\n\n<p>1) A simple form with element which appends a parameter in the query string such as domain.com?view=list - you can use this value to alter the display of items in your PHP files.</p>\n\n<p>2) Use javaScript to toggle a class on the parent container for your items, then control the layout with CSS. This should be pretty easy and is the option I'd go for. </p>\n\n<p>Dan</p>\n" } ]
2015/11/23
[ "https://wordpress.stackexchange.com/questions/209549", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/79884/" ]
i'm using this function in my Wordpress index: ``` <?php echo get_the_excerpt(); ?> ``` But if the article contains an image in the first 50 words, I get the link of the image in this form: > > Immagine: [http://i.imgur.com/UUsXR3w.jpg](https://i.imgur.com/UUsXR3w.jpg) > > > How can I exclude images from the excerpt?
Set a button, or dropdown menu, that calls a function to set a cookie and to switch between CSS files which contain the `_style` ID: ``` function switchStyle(style) { var file = $TMPL_URL + '/css/' + style; jQuery('head').append('<link rel="stylesheet" href="' + file + '" type="text/css" />'); jQuery.cookie($TMPL_NAME + '_style', style, { expires: 365, path: '/' }); } ``` `jQuery.cookie` should be replaced with whatever your standard cookie function is. Change `expires: 365` to set whatever duration you wish, so the page remembers which setting was chosen for that user.
209,555
<p>I know javascript pretty well now but I am new to php and wordpress theme building. I have searched a fair bit and can't find a solution to something that seems like a pretty simple task, all I would like to accomplish is get all the grandchildren of a page only, not the direct children, like so:</p> <p><strong>Portfolio</strong></p> <ul> <li>child 1 <ul> <li>grandchild 1A</li> <li>grandchild 1B</li> </ul></li> <li>child 2 <ul> <li>grandchild 2A</li> <li>grandchild 2B</li> </ul></li> </ul> <p>My page is "Portfolio" and I would like to "get_pages" but only the ones that are grandchildren of "Portfolio, so in this case it would return only: -"grandchild 1A", "grandchild 1B", "grandchild 2A", "grandchild 2B". </p> <p>any suggestions?</p>
[ { "answer_id": 209556, "author": "1inMillion", "author_id": 84112, "author_profile": "https://wordpress.stackexchange.com/users/84112", "pm_score": 0, "selected": false, "text": "<p>This for so you can get an idea, havent tested this code but maybe you should try.</p>\n\n<pre><code>&lt;?php\n\n $args = array(\n 'post_parent' =&gt; 0, //post parent id\n 'post_type' =&gt; 'any', \n 'numberposts' =&gt; -1,\n 'post_status' =&gt; 'any' \n); \n $childen = get_children( $args, OBJECT );\n\n foreach($children as $child){\n\n $args = array(\n 'post_parent' =&gt; $child-&gt;ID,\n 'post_type' =&gt; 'any', \n 'numberposts' =&gt; -1,\n 'post_status' =&gt; 'any' \n); \n $grand_children[] = get_children($args, OBJECT);\n}\n</code></pre>\n\n<p>maybe you can try like that.</p>\n" }, { "answer_id": 209557, "author": "John Priestakos", "author_id": 81617, "author_profile": "https://wordpress.stackexchange.com/users/81617", "pm_score": 1, "selected": false, "text": "<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/get_page_children\" rel=\"nofollow\"><code>get_page_children</code></a></p>\n\n<pre><code>$all_wp_pages = get_all_page_ids();\n\n// Get the page as an Object\n$portfolio = get_page_by_title('Portfolio');\n\n// Filter through all pages and find Portfolio's children\n$portfolio_children = get_page_children($portfolio-&gt;ID, $all_wp_pages);\n\nforeach ($portfolio_children as $child) {\n\n $post_data = array('child_of' =&gt; $child-&gt;ID);\n $grandchild = get_pages($post_data);\n}\n\n// echo what we get back from WP to the browser\necho '&lt;pre&gt;' . print_r($grandchild, true) . '&lt;/pre&gt;';\n</code></pre>\n" }, { "answer_id": 209590, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>There is no native way to do this AFAIK. The easiest way will be:</p>\n\n<ul>\n<li><p>to simply query all the pages in the hierarchy of the page ID passed</p></li>\n<li><p>then return all the parent ID's (<em>$post_parent property of the post object</em>) from all pages in an array</p></li>\n<li><p>loop through the pages and compare the page ID against the ID's in the parent ID's array</p></li>\n<li><p>any page which has its ID in the parent ID's array we will simply skip and exclude</p></li>\n<li><p>any page which ID is not in the parent ID array, we will use this to build a new array, these pages will be the lowest level pages</p></li>\n</ul>\n\n<p>The easiest will be to build our own custom function which we can call in any page template. Here is the function:</p>\n\n<pre><code>function get_lowest_level_pages( $page_id = '' )\n{\n // Check if we have a page id, if not, return false\n if ( !$page_id )\n return false;\n\n // Validate the page id\n $page_id = filter_var( $page_id, FILTER_VALIDATE_INT );\n\n // Check if this is a page, if not, return false\n if ( !is_page() )\n return false;\n\n // Get all pages in hierarchy of the current page\n $args = [\n 'child_of' =&gt; $page_id,\n ];\n $q = get_pages( $args );\n\n // Check if there are pages, if not, return false\n if ( !$q )\n return false;\n\n // Use wp_list_pluck to get all the post parents from all return pages\n $parents = wp_list_pluck( $q, 'post_parent' );\n // Set the $new__page_array variable that will hold grandchildren/lowest level pages\n $new__page_array = [];\n\n // Loop through all the pages\n foreach ( $q as $page_object ) {\n // Simply skip any page if it has child page\n if ( in_array( $page_object-&gt;ID, $parents ) )\n continue;\n\n // Create a new array holding only grandchild pages\n $new__page_array[] = $page_object;\n }\n\n return $new__page_array; \n}\n</code></pre>\n\n<p>You can then use it as follow: (<em>Just remember to pass the id of the parent page you need to get the grand children from</em>)</p>\n\n<pre><code>$page_id = get_queried_object_id(); // Returns the current page ID\n$q = get_lowest_level_pages( $page_id );\n\nif ( $q ) {\n foreach ( $q as $post ) {\n setup_postdata( $post );\n\n the_title();\n\n }\n wp_reset_postdata();\n}\n</code></pre>\n" } ]
2015/11/23
[ "https://wordpress.stackexchange.com/questions/209555", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84107/" ]
I know javascript pretty well now but I am new to php and wordpress theme building. I have searched a fair bit and can't find a solution to something that seems like a pretty simple task, all I would like to accomplish is get all the grandchildren of a page only, not the direct children, like so: **Portfolio** * child 1 + grandchild 1A + grandchild 1B * child 2 + grandchild 2A + grandchild 2B My page is "Portfolio" and I would like to "get\_pages" but only the ones that are grandchildren of "Portfolio, so in this case it would return only: -"grandchild 1A", "grandchild 1B", "grandchild 2A", "grandchild 2B". any suggestions?
There is no native way to do this AFAIK. The easiest way will be: * to simply query all the pages in the hierarchy of the page ID passed * then return all the parent ID's (*$post\_parent property of the post object*) from all pages in an array * loop through the pages and compare the page ID against the ID's in the parent ID's array * any page which has its ID in the parent ID's array we will simply skip and exclude * any page which ID is not in the parent ID array, we will use this to build a new array, these pages will be the lowest level pages The easiest will be to build our own custom function which we can call in any page template. Here is the function: ``` function get_lowest_level_pages( $page_id = '' ) { // Check if we have a page id, if not, return false if ( !$page_id ) return false; // Validate the page id $page_id = filter_var( $page_id, FILTER_VALIDATE_INT ); // Check if this is a page, if not, return false if ( !is_page() ) return false; // Get all pages in hierarchy of the current page $args = [ 'child_of' => $page_id, ]; $q = get_pages( $args ); // Check if there are pages, if not, return false if ( !$q ) return false; // Use wp_list_pluck to get all the post parents from all return pages $parents = wp_list_pluck( $q, 'post_parent' ); // Set the $new__page_array variable that will hold grandchildren/lowest level pages $new__page_array = []; // Loop through all the pages foreach ( $q as $page_object ) { // Simply skip any page if it has child page if ( in_array( $page_object->ID, $parents ) ) continue; // Create a new array holding only grandchild pages $new__page_array[] = $page_object; } return $new__page_array; } ``` You can then use it as follow: (*Just remember to pass the id of the parent page you need to get the grand children from*) ``` $page_id = get_queried_object_id(); // Returns the current page ID $q = get_lowest_level_pages( $page_id ); if ( $q ) { foreach ( $q as $post ) { setup_postdata( $post ); the_title(); } wp_reset_postdata(); } ```
209,560
<p>Is it possible that when user submit multipart form for creating a new post in wordpress, all the images are inserted using <code>wp_insert_attachment()</code> to media library with compression so the uploading time will be reduce?</p>
[ { "answer_id": 209556, "author": "1inMillion", "author_id": 84112, "author_profile": "https://wordpress.stackexchange.com/users/84112", "pm_score": 0, "selected": false, "text": "<p>This for so you can get an idea, havent tested this code but maybe you should try.</p>\n\n<pre><code>&lt;?php\n\n $args = array(\n 'post_parent' =&gt; 0, //post parent id\n 'post_type' =&gt; 'any', \n 'numberposts' =&gt; -1,\n 'post_status' =&gt; 'any' \n); \n $childen = get_children( $args, OBJECT );\n\n foreach($children as $child){\n\n $args = array(\n 'post_parent' =&gt; $child-&gt;ID,\n 'post_type' =&gt; 'any', \n 'numberposts' =&gt; -1,\n 'post_status' =&gt; 'any' \n); \n $grand_children[] = get_children($args, OBJECT);\n}\n</code></pre>\n\n<p>maybe you can try like that.</p>\n" }, { "answer_id": 209557, "author": "John Priestakos", "author_id": 81617, "author_profile": "https://wordpress.stackexchange.com/users/81617", "pm_score": 1, "selected": false, "text": "<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/get_page_children\" rel=\"nofollow\"><code>get_page_children</code></a></p>\n\n<pre><code>$all_wp_pages = get_all_page_ids();\n\n// Get the page as an Object\n$portfolio = get_page_by_title('Portfolio');\n\n// Filter through all pages and find Portfolio's children\n$portfolio_children = get_page_children($portfolio-&gt;ID, $all_wp_pages);\n\nforeach ($portfolio_children as $child) {\n\n $post_data = array('child_of' =&gt; $child-&gt;ID);\n $grandchild = get_pages($post_data);\n}\n\n// echo what we get back from WP to the browser\necho '&lt;pre&gt;' . print_r($grandchild, true) . '&lt;/pre&gt;';\n</code></pre>\n" }, { "answer_id": 209590, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>There is no native way to do this AFAIK. The easiest way will be:</p>\n\n<ul>\n<li><p>to simply query all the pages in the hierarchy of the page ID passed</p></li>\n<li><p>then return all the parent ID's (<em>$post_parent property of the post object</em>) from all pages in an array</p></li>\n<li><p>loop through the pages and compare the page ID against the ID's in the parent ID's array</p></li>\n<li><p>any page which has its ID in the parent ID's array we will simply skip and exclude</p></li>\n<li><p>any page which ID is not in the parent ID array, we will use this to build a new array, these pages will be the lowest level pages</p></li>\n</ul>\n\n<p>The easiest will be to build our own custom function which we can call in any page template. Here is the function:</p>\n\n<pre><code>function get_lowest_level_pages( $page_id = '' )\n{\n // Check if we have a page id, if not, return false\n if ( !$page_id )\n return false;\n\n // Validate the page id\n $page_id = filter_var( $page_id, FILTER_VALIDATE_INT );\n\n // Check if this is a page, if not, return false\n if ( !is_page() )\n return false;\n\n // Get all pages in hierarchy of the current page\n $args = [\n 'child_of' =&gt; $page_id,\n ];\n $q = get_pages( $args );\n\n // Check if there are pages, if not, return false\n if ( !$q )\n return false;\n\n // Use wp_list_pluck to get all the post parents from all return pages\n $parents = wp_list_pluck( $q, 'post_parent' );\n // Set the $new__page_array variable that will hold grandchildren/lowest level pages\n $new__page_array = [];\n\n // Loop through all the pages\n foreach ( $q as $page_object ) {\n // Simply skip any page if it has child page\n if ( in_array( $page_object-&gt;ID, $parents ) )\n continue;\n\n // Create a new array holding only grandchild pages\n $new__page_array[] = $page_object;\n }\n\n return $new__page_array; \n}\n</code></pre>\n\n<p>You can then use it as follow: (<em>Just remember to pass the id of the parent page you need to get the grand children from</em>)</p>\n\n<pre><code>$page_id = get_queried_object_id(); // Returns the current page ID\n$q = get_lowest_level_pages( $page_id );\n\nif ( $q ) {\n foreach ( $q as $post ) {\n setup_postdata( $post );\n\n the_title();\n\n }\n wp_reset_postdata();\n}\n</code></pre>\n" } ]
2015/11/23
[ "https://wordpress.stackexchange.com/questions/209560", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84114/" ]
Is it possible that when user submit multipart form for creating a new post in wordpress, all the images are inserted using `wp_insert_attachment()` to media library with compression so the uploading time will be reduce?
There is no native way to do this AFAIK. The easiest way will be: * to simply query all the pages in the hierarchy of the page ID passed * then return all the parent ID's (*$post\_parent property of the post object*) from all pages in an array * loop through the pages and compare the page ID against the ID's in the parent ID's array * any page which has its ID in the parent ID's array we will simply skip and exclude * any page which ID is not in the parent ID array, we will use this to build a new array, these pages will be the lowest level pages The easiest will be to build our own custom function which we can call in any page template. Here is the function: ``` function get_lowest_level_pages( $page_id = '' ) { // Check if we have a page id, if not, return false if ( !$page_id ) return false; // Validate the page id $page_id = filter_var( $page_id, FILTER_VALIDATE_INT ); // Check if this is a page, if not, return false if ( !is_page() ) return false; // Get all pages in hierarchy of the current page $args = [ 'child_of' => $page_id, ]; $q = get_pages( $args ); // Check if there are pages, if not, return false if ( !$q ) return false; // Use wp_list_pluck to get all the post parents from all return pages $parents = wp_list_pluck( $q, 'post_parent' ); // Set the $new__page_array variable that will hold grandchildren/lowest level pages $new__page_array = []; // Loop through all the pages foreach ( $q as $page_object ) { // Simply skip any page if it has child page if ( in_array( $page_object->ID, $parents ) ) continue; // Create a new array holding only grandchild pages $new__page_array[] = $page_object; } return $new__page_array; } ``` You can then use it as follow: (*Just remember to pass the id of the parent page you need to get the grand children from*) ``` $page_id = get_queried_object_id(); // Returns the current page ID $q = get_lowest_level_pages( $page_id ); if ( $q ) { foreach ( $q as $post ) { setup_postdata( $post ); the_title(); } wp_reset_postdata(); } ```
209,570
<p>I would like to replace the <code>permalink</code> for all products in a woocommerce/wp installation with a custom link, if it set in a <code>custom_post_meta</code>.</p> <p>The <code>custom_post_meta</code> is setup and working fine. From all I have read, the function below should do the trick:</p> <pre><code>function eli_changeProductLink($permalink, $post) { if ('product' == $post-&gt;post_type) { $custom_url = get_post_meta($post-&gt;id, '_eli_product_link', true); $permalink = $custom_url ?: $permalink; } return $permalink; } add_filter('post_type_link', 'eli_changeProductLink', 11, 2); </code></pre> <p>I'm giving it priority 11 because I want it run after <code>wc_product_post_type_link()</code>, which has a priority of 10. </p> <p>Can anyone spot what am I missing here? Or come up with possible causes why this might not work as expected? Using WC 2.4.10 with WP 4.3.1 (both latest at the time of posting).</p> <p>Thank you.</p>
[ { "answer_id": 209574, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 0, "selected": false, "text": "<p>Silly me. Haven't used WP in a while and completely forgot ID should be capitalized. </p>\n\n<p>Changed <code>post-&gt;id</code> to <code>post-&gt;ID</code> and it's working as intended.</p>\n\n<p>Sorry for wasting your time.</p>\n" }, { "answer_id": 209766, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 2, "selected": true, "text": "<p>The <code>$post</code> in your callback handler is an object, and object properties, like variables, are <a href=\"http://php.net/manual/en/language.variables.basics.php\" rel=\"nofollow noreferrer\">case sensitive</a>. So you have to use <code>$post-&gt;ID</code>, not <code>$post-&gt;id</code>.</p>\n\n<p>The question here is: <em>How can we prevent errors like this one during development?</em></p>\n\n<p>For objects, there is a simple solution: use <a href=\"http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration\" rel=\"nofollow noreferrer\">type hinting</a> and an IDE that makes use of it.</p>\n\n<p>If you change the signature of your callback handler to this …</p>\n\n<pre><code>function eli_changeProductLink($permalink, \\WP_Post $post)\n</code></pre>\n\n<p>… an IDE like PHPStorm or Eclipse will suggest the correct property names while you are typing:</p>\n\n<p><a href=\"https://i.stack.imgur.com/BjFp6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BjFp6.png\" alt=\"IDE screenshot\"></a></p>\n\n<p>The second lesson we can take from this: Use a <strong>consistent naming scheme</strong> for your own variables and properties, unlike WordPress which is mixing uppercase and lowercase, underscore and hyphens in names. Sticking to just one scheme will make the life of others easier when they have to work with your code.</p>\n" } ]
2015/11/23
[ "https://wordpress.stackexchange.com/questions/209570", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/45169/" ]
I would like to replace the `permalink` for all products in a woocommerce/wp installation with a custom link, if it set in a `custom_post_meta`. The `custom_post_meta` is setup and working fine. From all I have read, the function below should do the trick: ``` function eli_changeProductLink($permalink, $post) { if ('product' == $post->post_type) { $custom_url = get_post_meta($post->id, '_eli_product_link', true); $permalink = $custom_url ?: $permalink; } return $permalink; } add_filter('post_type_link', 'eli_changeProductLink', 11, 2); ``` I'm giving it priority 11 because I want it run after `wc_product_post_type_link()`, which has a priority of 10. Can anyone spot what am I missing here? Or come up with possible causes why this might not work as expected? Using WC 2.4.10 with WP 4.3.1 (both latest at the time of posting). Thank you.
The `$post` in your callback handler is an object, and object properties, like variables, are [case sensitive](http://php.net/manual/en/language.variables.basics.php). So you have to use `$post->ID`, not `$post->id`. The question here is: *How can we prevent errors like this one during development?* For objects, there is a simple solution: use [type hinting](http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration) and an IDE that makes use of it. If you change the signature of your callback handler to this … ``` function eli_changeProductLink($permalink, \WP_Post $post) ``` … an IDE like PHPStorm or Eclipse will suggest the correct property names while you are typing: [![IDE screenshot](https://i.stack.imgur.com/BjFp6.png)](https://i.stack.imgur.com/BjFp6.png) The second lesson we can take from this: Use a **consistent naming scheme** for your own variables and properties, unlike WordPress which is mixing uppercase and lowercase, underscore and hyphens in names. Sticking to just one scheme will make the life of others easier when they have to work with your code.
209,591
<p>I would like to organise users by date registered every time an admin visits the users page, without having to click again from:</p> <pre><code>http://localhost:8888/wp-admin/users.php </code></pre> <p>I can add the date registered column and the sorting but I can't seem to find any documentation on how to pre sort the users without actually clicking the sort button on the column name.</p> <p>I essentially want the users list to always be (unless selected otherwise): </p> <pre><code>/wp-admin/users.php?orderby=registered&amp;order=asc </code></pre>
[ { "answer_id": 239697, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": false, "text": "<p>This code will add the sortable user registration date column and it will handle default sorting of the user table by registration date. </p>\n\n<p>The majority of this code was taken from <a href=\"https://wordpress.org/plugins/recently-registered/\" rel=\"noreferrer\">Mika Epstein's Recently Registered plugin</a>. I added the bit to handle the default sort order which is a tweaked snippet of code from <a href=\"https://wordpress.org/support/topic/one-way-to-set-the-default-order-to-registration-date-descending/\" rel=\"noreferrer\">this post</a>.</p>\n\n<pre><code>/**\n * Registers users by date registered by default. When user clicks\n * other sortable column headers, those will take effect instead.\n */\nadd_action( 'pre_user_query', 'wpse209591_order_users_by_date_registered_by_default' );\nfunction wpse209591_order_users_by_date_registered_by_default( $query ) {\n global $pagenow;\n\n if ( ! is_admin() || 'users.php' !== $pagenow || isset( $_GET['orderby'] ) ) {\n return;\n }\n $query-&gt;query_orderby = 'ORDER BY user_registered ASC';\n}\n\n/**\n * Registers column for display\n */\nadd_filter( 'manage_users_columns', 'wpse209591_users_columns');\nfunction wpse209591_users_columns( $columns ) {\n $columns['registerdate'] = _x( 'Registered', 'user', 'your-text-domain' );\n return $columns;\n}\n\n/**\n * Handles the registered date column output.\n * \n * This uses the same code as column_registered, which is why\n * the date isn't filterable.\n *\n * @global string $mode\n */\nadd_action( 'manage_users_custom_column', 'wpse209591_users_custom_column', 10, 3);\nfunction wpse209591_users_custom_column( $value, $column_name, $user_id ) {\n\n global $mode;\n $mode = empty( $_REQUEST['mode'] ) ? 'list' : $_REQUEST['mode'];\n\n if ( 'registerdate' != $column_name ) {\n return $value;\n } else {\n $user = get_userdata( $user_id );\n\n if ( is_multisite() &amp;&amp; ( 'list' == $mode ) ) {\n $formated_date = __( 'Y/m/d' );\n } else {\n $formated_date = __( 'Y/m/d g:i:s a' );\n }\n\n $registered = strtotime( get_date_from_gmt( $user-&gt;user_registered ) );\n $registerdate = '&lt;span&gt;'. date_i18n( $formated_date, $registered ) .'&lt;/span&gt;' ;\n\n return $registerdate;\n }\n}\n\n/**\n * Makes the column sortable\n */\nadd_filter( 'manage_users_sortable_columns', 'wpse209591_users_sortable_columns' );\nfunction wpse209591_users_sortable_columns( $columns ) {\n\n $custom = array(\n // meta column id =&gt; sortby value used in query\n 'registerdate' =&gt; 'registered',\n );\n\n return wp_parse_args( $custom, $columns );\n}\n\n/**\n * Calculate the order if we sort by date.\n *\n */\nadd_filter( 'request', 'wpse209591_users_orderby_column' );\nfunction wpse209591_users_orderby_column( $vars ) {\n\n if ( isset( $vars['orderby'] ) &amp;&amp; 'registerdate' == $vars['orderby'] ) {\n $vars = array_merge( $vars, array(\n 'meta_key' =&gt; 'registerdate',\n 'orderby' =&gt; 'meta_value'\n ) );\n }\n\n return $vars;\n}\n</code></pre>\n" }, { "answer_id": 368199, "author": "Nic Bug", "author_id": 144969, "author_profile": "https://wordpress.stackexchange.com/users/144969", "pm_score": 3, "selected": false, "text": "<p>why so complicated? just use the default hook for that:</p>\n\n<pre><code>function change_user_order($args){\n $args[\"orderby\"] = \"user_registered\";\n $args[\"order\"] = \"DESC\";\n return $args;\n}\nadd_filter(\"users_list_table_query_args\",\"change_user_order\");\n</code></pre>\n\n<p>from class-wp-user-query.php:</p>\n\n<blockquote>\n <p>May be a single value,\n an array of values, or a multi-dimensional array with fields as\n keys and orders ('ASC' or 'DESC') as values. Accepted values are\n 'ID', 'display_name' (or 'name'), 'include', 'user_login'\n (or 'login'), 'login__in', 'user_nicename' (or 'nicename'),\n 'nicename__in', 'user_email (or 'email'), 'user_url' (or 'url'),\n 'user_registered' (or 'registered'), 'post_count', 'meta_value',\n 'meta_value_num', the value of <code>$meta_key</code>, or an array key of\n <code>$meta_query</code>. To use 'meta_value' or 'meta_value_num', <code>$meta_key</code>\n must be also be defined. Default 'user_login'.</p>\n</blockquote>\n" }, { "answer_id": 382787, "author": "Peter Højlund Andersen", "author_id": 179478, "author_profile": "https://wordpress.stackexchange.com/users/179478", "pm_score": 2, "selected": false, "text": "<p>If you want to overwrite the default setting, you have to check if the args are empty first:</p>\n<pre><code>function default_sort_users( $args ) {\n if ( empty( $args['orderby'] ) ) {\n $args['orderby'] = 'user_registered'; \n }\n return $args;\n}\n\nadd_filter( 'users_list_table_query_args', 'default_sort_users' );\n</code></pre>\n" } ]
2015/11/23
[ "https://wordpress.stackexchange.com/questions/209591", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84127/" ]
I would like to organise users by date registered every time an admin visits the users page, without having to click again from: ``` http://localhost:8888/wp-admin/users.php ``` I can add the date registered column and the sorting but I can't seem to find any documentation on how to pre sort the users without actually clicking the sort button on the column name. I essentially want the users list to always be (unless selected otherwise): ``` /wp-admin/users.php?orderby=registered&order=asc ```
This code will add the sortable user registration date column and it will handle default sorting of the user table by registration date. The majority of this code was taken from [Mika Epstein's Recently Registered plugin](https://wordpress.org/plugins/recently-registered/). I added the bit to handle the default sort order which is a tweaked snippet of code from [this post](https://wordpress.org/support/topic/one-way-to-set-the-default-order-to-registration-date-descending/). ``` /** * Registers users by date registered by default. When user clicks * other sortable column headers, those will take effect instead. */ add_action( 'pre_user_query', 'wpse209591_order_users_by_date_registered_by_default' ); function wpse209591_order_users_by_date_registered_by_default( $query ) { global $pagenow; if ( ! is_admin() || 'users.php' !== $pagenow || isset( $_GET['orderby'] ) ) { return; } $query->query_orderby = 'ORDER BY user_registered ASC'; } /** * Registers column for display */ add_filter( 'manage_users_columns', 'wpse209591_users_columns'); function wpse209591_users_columns( $columns ) { $columns['registerdate'] = _x( 'Registered', 'user', 'your-text-domain' ); return $columns; } /** * Handles the registered date column output. * * This uses the same code as column_registered, which is why * the date isn't filterable. * * @global string $mode */ add_action( 'manage_users_custom_column', 'wpse209591_users_custom_column', 10, 3); function wpse209591_users_custom_column( $value, $column_name, $user_id ) { global $mode; $mode = empty( $_REQUEST['mode'] ) ? 'list' : $_REQUEST['mode']; if ( 'registerdate' != $column_name ) { return $value; } else { $user = get_userdata( $user_id ); if ( is_multisite() && ( 'list' == $mode ) ) { $formated_date = __( 'Y/m/d' ); } else { $formated_date = __( 'Y/m/d g:i:s a' ); } $registered = strtotime( get_date_from_gmt( $user->user_registered ) ); $registerdate = '<span>'. date_i18n( $formated_date, $registered ) .'</span>' ; return $registerdate; } } /** * Makes the column sortable */ add_filter( 'manage_users_sortable_columns', 'wpse209591_users_sortable_columns' ); function wpse209591_users_sortable_columns( $columns ) { $custom = array( // meta column id => sortby value used in query 'registerdate' => 'registered', ); return wp_parse_args( $custom, $columns ); } /** * Calculate the order if we sort by date. * */ add_filter( 'request', 'wpse209591_users_orderby_column' ); function wpse209591_users_orderby_column( $vars ) { if ( isset( $vars['orderby'] ) && 'registerdate' == $vars['orderby'] ) { $vars = array_merge( $vars, array( 'meta_key' => 'registerdate', 'orderby' => 'meta_value' ) ); } return $vars; } ```
209,628
<p>So this works:</p> <pre><code>the_title( '&lt;h1 class="entry-title"&gt;', '&lt;/h1&gt;' ); </code></pre> <p>But this does not:</p> <pre><code>the_date( '&lt;h4 class="entry-date"&gt;', '&lt;/h4&gt;' ); </code></pre> <p>I don't know enough if this is reserved for <code>the_title()</code> or if the twentyfifteen theme has specified this functionality in functions. I don't see it but I could be missing it. Or course, just printing <code>the_date();</code> works as it's supposed to as well as pulling it out of the php block and wrapping it in html myself also works. Just thought there could be a nifty little way to do it like <code>the_title</code> there.</p>
[ { "answer_id": 209630, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 3, "selected": true, "text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/the_date\" rel=\"nofollow\">The Codex</a> ( or <a href=\"https://developer.wordpress.org/reference/functions/the_date/\" rel=\"nofollow\">Developer Resources</a> ) is a fantastic tool when you're unsure about a function. Looking at the parameter list for <a href=\"https://codex.wordpress.org/Function_Reference/the_date\" rel=\"nofollow\"><code>the_date()</code></a> it says:</p>\n\n<pre><code>the_date( $format, $before, $after, $echo );\n</code></pre>\n\n<p>So you need to pass in <a href=\"https://codex.wordpress.org/Formatting_Date_and_Time\" rel=\"nofollow\">a format</a> as the first parameter, then your HTML tags like you have it. An example could look like this:</p>\n\n<pre><code>the_date( 'l, F j, Y', '&lt;h4 class=\"entry-date\"&gt;', '&lt;/h4&gt;' );\n</code></pre>\n" }, { "answer_id": 209631, "author": "Privateer", "author_id": 66020, "author_profile": "https://wordpress.stackexchange.com/users/66020", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"https://codex.wordpress.org/Function_Reference/the_date\" rel=\"nofollow\">the_date</a> function does not work like that.</p>\n\n<p>The first parameter is the <a href=\"http://php.net/manual/en/function.date.php\" rel=\"nofollow\">date format</a> you want to use.</p>\n\n<p>To echo it out</p>\n\n<blockquote>\n <p>the_date( 'F j, Y', '', '', true );</p>\n</blockquote>\n\n<p>To get the result:</p>\n\n<blockquote>\n <p>$result = the_date('F j, Y', '', '', false );</p>\n</blockquote>\n\n<p>You might also want to see <a href=\"https://codex.wordpress.org/Template_Tags/get_the_date\" rel=\"nofollow\">get_the_date</a>.</p>\n" } ]
2015/11/23
[ "https://wordpress.stackexchange.com/questions/209628", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/45709/" ]
So this works: ``` the_title( '<h1 class="entry-title">', '</h1>' ); ``` But this does not: ``` the_date( '<h4 class="entry-date">', '</h4>' ); ``` I don't know enough if this is reserved for `the_title()` or if the twentyfifteen theme has specified this functionality in functions. I don't see it but I could be missing it. Or course, just printing `the_date();` works as it's supposed to as well as pulling it out of the php block and wrapping it in html myself also works. Just thought there could be a nifty little way to do it like `the_title` there.
[The Codex](https://codex.wordpress.org/Function_Reference/the_date) ( or [Developer Resources](https://developer.wordpress.org/reference/functions/the_date/) ) is a fantastic tool when you're unsure about a function. Looking at the parameter list for [`the_date()`](https://codex.wordpress.org/Function_Reference/the_date) it says: ``` the_date( $format, $before, $after, $echo ); ``` So you need to pass in [a format](https://codex.wordpress.org/Formatting_Date_and_Time) as the first parameter, then your HTML tags like you have it. An example could look like this: ``` the_date( 'l, F j, Y', '<h4 class="entry-date">', '</h4>' ); ```
209,634
<p>I want to add HTML5 required for the client side validation on textarea generated by </p> <pre><code>&lt;?php $content = ''; $editor_id = 'YOURID'; wp_editor( $content, $editor_id ); ?&gt; </code></pre> <p>What is the best way to add <code>required</code> on textarea? Thank you.</p>
[ { "answer_id": 209643, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": true, "text": "<p>The visual editor is not a textarea, it is an iframe, therefor even if you could set an attribute it will do nothing. You can set the attribute on the hidden textarea that will be sent to the server but since it is hidden I am not sure how an alert about it not being filled will be displayed and it might be different between browsers (it is hidden so there is no obvious visual anchor for the display of the alert)</p>\n" }, { "answer_id": 276395, "author": "Mario Hendricks", "author_id": 106491, "author_profile": "https://wordpress.stackexchange.com/users/106491", "pm_score": 1, "selected": false, "text": "<p>I have done the following successfully for a plug-in that uses several visual editors (only some of which are required) on an Admin Screen. </p>\n\n<ol>\n<li>When creating the editor, add a class that is unique to my plugin and indicates that content is required in this editor. </li>\n<li>Hook a function to 'the_editor'.</li>\n<li>This function will check if the markup for the editor contains my custom class. If so, it adds the required attribute. </li>\n</ol>\n\n<p>I am able to style the field using </p>\n\n<pre><code>textarea[required]:invalid\n</code></pre>\n\n<p>and the form generates an error if it is submitted while this field is empty (though I've only tested in Safari so far). </p>\n\n<p>Sample code is below (This code was taken from a much larger class).\nFirst, an excerpt from the function that builds the editor. </p>\n\n<pre><code>$addlClass = ($required) ? 'my-required-field' : '';\n$settings = array(\n 'media_buttons' =&gt; false,\n 'textarea_name' =&gt; $fieldName,\n 'editor_class' =&gt; $addlClass\n);\nwp_editor($cleanFld, $fieldId, $settings);\n</code></pre>\n\n<p>Then, my hook:</p>\n\n<pre><code>add_action('the_editor', array($this, 'CheckIfEditorFieldIsRequired'));\n</code></pre>\n\n<p>Finally, that function: </p>\n\n<pre><code>public function CheckIfEditorFieldIsRequired($editorMarkup)\n{\n if (stripos($editorMarkup, 'my-required-field') !== false) {\n $editorMarkup = str_replace('&lt;textarea', '&lt;textarea required', $editorMarkup);\n }\n return $editorMarkup;\n}\n</code></pre>\n" } ]
2015/11/23
[ "https://wordpress.stackexchange.com/questions/209634", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74171/" ]
I want to add HTML5 required for the client side validation on textarea generated by ``` <?php $content = ''; $editor_id = 'YOURID'; wp_editor( $content, $editor_id ); ?> ``` What is the best way to add `required` on textarea? Thank you.
The visual editor is not a textarea, it is an iframe, therefor even if you could set an attribute it will do nothing. You can set the attribute on the hidden textarea that will be sent to the server but since it is hidden I am not sure how an alert about it not being filled will be displayed and it might be different between browsers (it is hidden so there is no obvious visual anchor for the display of the alert)
209,636
<p>I am trying to use this code:</p> <pre><code>&lt;?php if(count(get_post_ancestors($post-&gt;ID)) == 2 ) : ?&gt; &lt;script&gt;...&lt;/script&gt; &lt;?php endif ?&gt; </code></pre> <p>to add a script to a page <strong>but only if</strong> the page is a <strong>grandchild page</strong> (3rd level down, when it has 2 ancestors):</p> <p><strong>Desired Result (with code above):</strong></p> <ul> <li>Parent Page <ul> <li>Child Page <ul> <li>Grandchild Page <strong><em>(show script here only)</em></strong></li> </ul></li> </ul></li> </ul> <p>But the script is showing on child pages as well as grandchild pages. Why would that be?</p> <p><strong>Actual Result (with code above):</strong></p> <ul> <li>Parent Page <ul> <li>Child Page <strong><em>(script is showing here)</em></strong> <ul> <li>Grandchild Page <strong><em>(script is showing here)</em></strong></li> </ul></li> </ul></li> </ul> <hr> <p><strong>EDIT</strong>: this is my query code on the children pages (with a different ID for post_parent, depending on the child page):</p> <pre><code>&lt;?php $args = array('post_parent' =&gt; 21); $loop = new WP_Query( $args ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt; ... &lt;?php endwhile; ?&gt; </code></pre>
[ { "answer_id": 209740, "author": "Douglas.Sesar", "author_id": 19945, "author_profile": "https://wordpress.stackexchange.com/users/19945", "pm_score": 0, "selected": false, "text": "<p>Try checking the $post->ID right at the wp hook:</p>\n\n<pre><code>add_action('wp','your_awesome_function');\n\n\nfunction your_awesome_function()\n{\n global $post;\n if( count(get_post_ancestors($post-&gt;ID)) == 2 )\n add_action('wp_footer','your_grandchild_script');\n}\n\nfunction your_grandchild_script()\n{\n ob_start();\n ?&gt;\n &lt;script&gt;...&lt;/script&gt;\n &lt;?php\n echo ob_get_clean();\n}\n</code></pre>\n" }, { "answer_id": 209787, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": true, "text": "<p>Something is changing your results from <code>get_ancestors()</code> or something is changing your query which \"changes\" your child pages to grandchild pages when queried on the page. It also seems from comments that the post ID's does not stay constant on the page. </p>\n\n<p>What immediately catches my eye from your updated code is that your custom query is not resetted after you are done. You have to remember, <code>the_post()</code> sets the <code>$post</code> global to the current post being looped over in the loop, and once the loop is done, <code>$post</code> will hold the last post object of the loop. </p>\n\n<p>You can add <code>var_dump( $post );</code> before and after your current code and you will see that the value of <code>$post</code> differs. That is why you must <strong>always</strong> reset custom queries after you are done. Simply add <code>wp_reset_postdata();</code> directly after <code>endwhile</code> just before <code>endif</code>. Doing a <code>var_dump( $post );</code> now before and after the loop should render the same value. </p>\n\n<p><code>$post</code> is a global variable that is changed by many things, and bad code (<em>like the code in your question</em>) can change the <code>$post</code> global, which in turn returns wrong info, which in turn have you on a wild goose chase to find out why. A more reliable method is to use <code>get_queried_object()</code> to return the current page object. For an explanation, please feel free to check <a href=\"https://wordpress.stackexchange.com/q/167706/31545\">my question</a> and the answer accepted answer from @gmazzap. Note, however this being reliable, <code>query_posts</code> breaks the main query object which holds the queried object.</p>\n\n<p>I also note that you hardcode ID's, do not do that. Every post/page have a <code>post_parent</code> property. If a post type is non-hierarchical, like posts, the <code>post_parent</code> value will always be <code>0</code> because non-hierarchical post types don't have any hierarchy. Hierarchical post types like pages will either have <code>0</code> as <code>post_parent</code> if it is a top level page or have a numeric value if it is child/grandchild page, the value in <code>post_parent</code> will represent the ID of the page's direct parent.</p>\n\n<ul>\n<li><p>To correctly get the page id of a page being viewed, use <code>get_queried_object()-&gt;ID</code> or <code>get_queried_object_id()</code> instead of <code>$post-&gt;ID</code>. </p></li>\n<li><p>To get the immediate post parent ID of the current page being viewed, use <code>get_queried_object()-&gt;post_parent</code> </p></li>\n<li><p>To get the top level parent, use <code>end( get_ancestors( get_queried_object()-&gt;ID, 'page' ) )</code>. Remember, the top level parent will be the last ID in the array of ID's returned by <code>get_ancestors</code>, the first ID will be the direct parent.</p></li>\n</ul>\n\n<p>To rewrite your code, use something like this to get direct children of the page being viewed:</p>\n\n<pre><code>$page_object = get_queried_object();\n// Check if page is top level or not and set $args accordingly\nif ( $page_object-&gt;post_parent == 0 ) { // Top level page\n $parent_ID = (int) $page_object-&gt;ID;\n} else { // Page is a child/grandchild page\n $parent_ID = (int) $page_object-&gt;post_parent;\n}\n\n// Setup query args\n$args = [\n 'post_parent' =&gt; $parent_ID,\n 'post_type' =&gt; 'page'\n];\n$q = new WP_Query( $args );\nif ( $q-&gt;have_posts() ) {\n while ( $q-&gt;have_posts() ) {\n $q-&gt;the_post();\n\n // Run your code to display posts\n\n }\n wp_reset_postdata(); // EXTEMELY IMPORTANT!!!!!!!\n}\n</code></pre>\n\n<p>To conclude, to determine the current hierarchy of a page, do the following</p>\n\n<pre><code>$current_page = get_queried_object();\nif ( $current_page-&gt;post_parent == 0 ) {\n echo 'This is a parent';\n} else {\n $hierarchy = get_ancestors( $current_page-&gt;ID, 'page' );\n $count = count( $hierarchy );\n $child = ( $count == 1 ) ? 'child' : 'grandchild';\n echo 'This is a ' . $child . ' page';\n}\n</code></pre>\n" } ]
2015/11/23
[ "https://wordpress.stackexchange.com/questions/209636", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40679/" ]
I am trying to use this code: ``` <?php if(count(get_post_ancestors($post->ID)) == 2 ) : ?> <script>...</script> <?php endif ?> ``` to add a script to a page **but only if** the page is a **grandchild page** (3rd level down, when it has 2 ancestors): **Desired Result (with code above):** * Parent Page + Child Page - Grandchild Page ***(show script here only)*** But the script is showing on child pages as well as grandchild pages. Why would that be? **Actual Result (with code above):** * Parent Page + Child Page ***(script is showing here)*** - Grandchild Page ***(script is showing here)*** --- **EDIT**: this is my query code on the children pages (with a different ID for post\_parent, depending on the child page): ``` <?php $args = array('post_parent' => 21); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); ?> ... <?php endwhile; ?> ```
Something is changing your results from `get_ancestors()` or something is changing your query which "changes" your child pages to grandchild pages when queried on the page. It also seems from comments that the post ID's does not stay constant on the page. What immediately catches my eye from your updated code is that your custom query is not resetted after you are done. You have to remember, `the_post()` sets the `$post` global to the current post being looped over in the loop, and once the loop is done, `$post` will hold the last post object of the loop. You can add `var_dump( $post );` before and after your current code and you will see that the value of `$post` differs. That is why you must **always** reset custom queries after you are done. Simply add `wp_reset_postdata();` directly after `endwhile` just before `endif`. Doing a `var_dump( $post );` now before and after the loop should render the same value. `$post` is a global variable that is changed by many things, and bad code (*like the code in your question*) can change the `$post` global, which in turn returns wrong info, which in turn have you on a wild goose chase to find out why. A more reliable method is to use `get_queried_object()` to return the current page object. For an explanation, please feel free to check [my question](https://wordpress.stackexchange.com/q/167706/31545) and the answer accepted answer from @gmazzap. Note, however this being reliable, `query_posts` breaks the main query object which holds the queried object. I also note that you hardcode ID's, do not do that. Every post/page have a `post_parent` property. If a post type is non-hierarchical, like posts, the `post_parent` value will always be `0` because non-hierarchical post types don't have any hierarchy. Hierarchical post types like pages will either have `0` as `post_parent` if it is a top level page or have a numeric value if it is child/grandchild page, the value in `post_parent` will represent the ID of the page's direct parent. * To correctly get the page id of a page being viewed, use `get_queried_object()->ID` or `get_queried_object_id()` instead of `$post->ID`. * To get the immediate post parent ID of the current page being viewed, use `get_queried_object()->post_parent` * To get the top level parent, use `end( get_ancestors( get_queried_object()->ID, 'page' ) )`. Remember, the top level parent will be the last ID in the array of ID's returned by `get_ancestors`, the first ID will be the direct parent. To rewrite your code, use something like this to get direct children of the page being viewed: ``` $page_object = get_queried_object(); // Check if page is top level or not and set $args accordingly if ( $page_object->post_parent == 0 ) { // Top level page $parent_ID = (int) $page_object->ID; } else { // Page is a child/grandchild page $parent_ID = (int) $page_object->post_parent; } // Setup query args $args = [ 'post_parent' => $parent_ID, 'post_type' => 'page' ]; $q = new WP_Query( $args ); if ( $q->have_posts() ) { while ( $q->have_posts() ) { $q->the_post(); // Run your code to display posts } wp_reset_postdata(); // EXTEMELY IMPORTANT!!!!!!! } ``` To conclude, to determine the current hierarchy of a page, do the following ``` $current_page = get_queried_object(); if ( $current_page->post_parent == 0 ) { echo 'This is a parent'; } else { $hierarchy = get_ancestors( $current_page->ID, 'page' ); $count = count( $hierarchy ); $child = ( $count == 1 ) ? 'child' : 'grandchild'; echo 'This is a ' . $child . ' page'; } ```
209,641
<p>I would like to display a list of any users whose emails are detected to have email addresses from an array of domains.</p> <p><code>$domains = array('domain1.com', 'domain2.com', 'domain3.com');</code></p> <p>If any users match those domains they would be listed in an un-ordered list, such as:</p> <p><code>[email protected] [email protected] [email protected] etc</code></p>
[ { "answer_id": 209740, "author": "Douglas.Sesar", "author_id": 19945, "author_profile": "https://wordpress.stackexchange.com/users/19945", "pm_score": 0, "selected": false, "text": "<p>Try checking the $post->ID right at the wp hook:</p>\n\n<pre><code>add_action('wp','your_awesome_function');\n\n\nfunction your_awesome_function()\n{\n global $post;\n if( count(get_post_ancestors($post-&gt;ID)) == 2 )\n add_action('wp_footer','your_grandchild_script');\n}\n\nfunction your_grandchild_script()\n{\n ob_start();\n ?&gt;\n &lt;script&gt;...&lt;/script&gt;\n &lt;?php\n echo ob_get_clean();\n}\n</code></pre>\n" }, { "answer_id": 209787, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": true, "text": "<p>Something is changing your results from <code>get_ancestors()</code> or something is changing your query which \"changes\" your child pages to grandchild pages when queried on the page. It also seems from comments that the post ID's does not stay constant on the page. </p>\n\n<p>What immediately catches my eye from your updated code is that your custom query is not resetted after you are done. You have to remember, <code>the_post()</code> sets the <code>$post</code> global to the current post being looped over in the loop, and once the loop is done, <code>$post</code> will hold the last post object of the loop. </p>\n\n<p>You can add <code>var_dump( $post );</code> before and after your current code and you will see that the value of <code>$post</code> differs. That is why you must <strong>always</strong> reset custom queries after you are done. Simply add <code>wp_reset_postdata();</code> directly after <code>endwhile</code> just before <code>endif</code>. Doing a <code>var_dump( $post );</code> now before and after the loop should render the same value. </p>\n\n<p><code>$post</code> is a global variable that is changed by many things, and bad code (<em>like the code in your question</em>) can change the <code>$post</code> global, which in turn returns wrong info, which in turn have you on a wild goose chase to find out why. A more reliable method is to use <code>get_queried_object()</code> to return the current page object. For an explanation, please feel free to check <a href=\"https://wordpress.stackexchange.com/q/167706/31545\">my question</a> and the answer accepted answer from @gmazzap. Note, however this being reliable, <code>query_posts</code> breaks the main query object which holds the queried object.</p>\n\n<p>I also note that you hardcode ID's, do not do that. Every post/page have a <code>post_parent</code> property. If a post type is non-hierarchical, like posts, the <code>post_parent</code> value will always be <code>0</code> because non-hierarchical post types don't have any hierarchy. Hierarchical post types like pages will either have <code>0</code> as <code>post_parent</code> if it is a top level page or have a numeric value if it is child/grandchild page, the value in <code>post_parent</code> will represent the ID of the page's direct parent.</p>\n\n<ul>\n<li><p>To correctly get the page id of a page being viewed, use <code>get_queried_object()-&gt;ID</code> or <code>get_queried_object_id()</code> instead of <code>$post-&gt;ID</code>. </p></li>\n<li><p>To get the immediate post parent ID of the current page being viewed, use <code>get_queried_object()-&gt;post_parent</code> </p></li>\n<li><p>To get the top level parent, use <code>end( get_ancestors( get_queried_object()-&gt;ID, 'page' ) )</code>. Remember, the top level parent will be the last ID in the array of ID's returned by <code>get_ancestors</code>, the first ID will be the direct parent.</p></li>\n</ul>\n\n<p>To rewrite your code, use something like this to get direct children of the page being viewed:</p>\n\n<pre><code>$page_object = get_queried_object();\n// Check if page is top level or not and set $args accordingly\nif ( $page_object-&gt;post_parent == 0 ) { // Top level page\n $parent_ID = (int) $page_object-&gt;ID;\n} else { // Page is a child/grandchild page\n $parent_ID = (int) $page_object-&gt;post_parent;\n}\n\n// Setup query args\n$args = [\n 'post_parent' =&gt; $parent_ID,\n 'post_type' =&gt; 'page'\n];\n$q = new WP_Query( $args );\nif ( $q-&gt;have_posts() ) {\n while ( $q-&gt;have_posts() ) {\n $q-&gt;the_post();\n\n // Run your code to display posts\n\n }\n wp_reset_postdata(); // EXTEMELY IMPORTANT!!!!!!!\n}\n</code></pre>\n\n<p>To conclude, to determine the current hierarchy of a page, do the following</p>\n\n<pre><code>$current_page = get_queried_object();\nif ( $current_page-&gt;post_parent == 0 ) {\n echo 'This is a parent';\n} else {\n $hierarchy = get_ancestors( $current_page-&gt;ID, 'page' );\n $count = count( $hierarchy );\n $child = ( $count == 1 ) ? 'child' : 'grandchild';\n echo 'This is a ' . $child . ' page';\n}\n</code></pre>\n" } ]
2015/11/24
[ "https://wordpress.stackexchange.com/questions/209641", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84161/" ]
I would like to display a list of any users whose emails are detected to have email addresses from an array of domains. `$domains = array('domain1.com', 'domain2.com', 'domain3.com');` If any users match those domains they would be listed in an un-ordered list, such as: `[email protected] [email protected] [email protected] etc`
Something is changing your results from `get_ancestors()` or something is changing your query which "changes" your child pages to grandchild pages when queried on the page. It also seems from comments that the post ID's does not stay constant on the page. What immediately catches my eye from your updated code is that your custom query is not resetted after you are done. You have to remember, `the_post()` sets the `$post` global to the current post being looped over in the loop, and once the loop is done, `$post` will hold the last post object of the loop. You can add `var_dump( $post );` before and after your current code and you will see that the value of `$post` differs. That is why you must **always** reset custom queries after you are done. Simply add `wp_reset_postdata();` directly after `endwhile` just before `endif`. Doing a `var_dump( $post );` now before and after the loop should render the same value. `$post` is a global variable that is changed by many things, and bad code (*like the code in your question*) can change the `$post` global, which in turn returns wrong info, which in turn have you on a wild goose chase to find out why. A more reliable method is to use `get_queried_object()` to return the current page object. For an explanation, please feel free to check [my question](https://wordpress.stackexchange.com/q/167706/31545) and the answer accepted answer from @gmazzap. Note, however this being reliable, `query_posts` breaks the main query object which holds the queried object. I also note that you hardcode ID's, do not do that. Every post/page have a `post_parent` property. If a post type is non-hierarchical, like posts, the `post_parent` value will always be `0` because non-hierarchical post types don't have any hierarchy. Hierarchical post types like pages will either have `0` as `post_parent` if it is a top level page or have a numeric value if it is child/grandchild page, the value in `post_parent` will represent the ID of the page's direct parent. * To correctly get the page id of a page being viewed, use `get_queried_object()->ID` or `get_queried_object_id()` instead of `$post->ID`. * To get the immediate post parent ID of the current page being viewed, use `get_queried_object()->post_parent` * To get the top level parent, use `end( get_ancestors( get_queried_object()->ID, 'page' ) )`. Remember, the top level parent will be the last ID in the array of ID's returned by `get_ancestors`, the first ID will be the direct parent. To rewrite your code, use something like this to get direct children of the page being viewed: ``` $page_object = get_queried_object(); // Check if page is top level or not and set $args accordingly if ( $page_object->post_parent == 0 ) { // Top level page $parent_ID = (int) $page_object->ID; } else { // Page is a child/grandchild page $parent_ID = (int) $page_object->post_parent; } // Setup query args $args = [ 'post_parent' => $parent_ID, 'post_type' => 'page' ]; $q = new WP_Query( $args ); if ( $q->have_posts() ) { while ( $q->have_posts() ) { $q->the_post(); // Run your code to display posts } wp_reset_postdata(); // EXTEMELY IMPORTANT!!!!!!! } ``` To conclude, to determine the current hierarchy of a page, do the following ``` $current_page = get_queried_object(); if ( $current_page->post_parent == 0 ) { echo 'This is a parent'; } else { $hierarchy = get_ancestors( $current_page->ID, 'page' ); $count = count( $hierarchy ); $child = ( $count == 1 ) ? 'child' : 'grandchild'; echo 'This is a ' . $child . ' page'; } ```
209,649
<p>This is so basic, but i couldn't understand why it's not working, i'm trying to send parameter from add_action(), this is my code in my function.php:</p> <pre><code>function testingID( $testParam) { var_dump($testParam); die(); } add_action( 'init', 'testingID', 1,1); </code></pre> <p>I expect to have the screen print '1' instead just :</p> <pre><code>string(0) "" </code></pre> <p>Wondering what caused this ?</p> <p>Thanks</p>
[ { "answer_id": 209650, "author": "Aparna_29", "author_id": 84165, "author_profile": "https://wordpress.stackexchange.com/users/84165", "pm_score": 0, "selected": false, "text": "<p>Where are you initializing the value of <code>$testParam</code>?</p>\n\n<p><code>add_action( 'init', 'testingID', 1,1);</code> </p>\n\n<p>This specifies that <code>testingID function</code> should be called on init which accepts 1 parameter. But the value of parameter is not defined. Last two 1s defines, priority of function and number of parameters. </p>\n" }, { "answer_id": 209664, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": -1, "selected": false, "text": "<p>Here <code>add_action( string $hook, callback $function_to_add, int $priority = 10, int $accepted_args = 1 )</code> hook function having four arguments:</p>\n\n<p><strong>$hook</strong>: The name of the action to which the <strong>$function_to_add</strong> is hooked.</p>\n\n<p><strong>$function_to_add</strong>: The name of the function you wish to be called.</p>\n\n<p><strong>$priority</strong>: Used to specify the order in which the functions associated with a particular action are executed. Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.</p>\n\n<p><strong>$accepted_args</strong>: The number of arguments the function accepts. Default return 1.</p>\n\n<p>I revised your code and make small change please check it.</p>\n\n<pre><code>function testingID( $testParam) { \n // do stuff here...\n return $testParam;\n}\n\nadd_action( 'init', 'testingID', 1,1);\n</code></pre>\n\n<p>Please review for more: <a href=\"https://codex.wordpress.org/Function_Reference/add_action\" rel=\"nofollow\">codex</a></p>\n" }, { "answer_id": 209669, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 1, "selected": true, "text": "<p>When an action is defined, the parameters passed to the callback are defined as well. For example, you can define an action with 4 parameters:</p>\n\n<pre><code>$a = 1;\n$b = 2;\n$c = 3;\n$d = 4;\ndo_action( 'name_of_my_action', $a, $b, $c, $d );\n</code></pre>\n\n<p>Then, when you hook in that action, you can tell how many of those parameters will be used; the value of those params are the values assigned when the action was defined. For example, you may want to use only 2:</p>\n\n<pre><code>// The fourth parameter is the number of accepted\n// parameters by the callback, in this case want only 2\n// The parameters are passed to the callback in the same order\n// they were set when the action was definied and with the same value\nadd_action( 'name_of_my_action', 'my_action_callback', 10, 2 );\nfunction my_action_callback( $a, $b ) {\n\n // The value of $a is 1\n var_dump( $a );\n\n // The value of $b is 2\n var_dump( $b );\n\n}\n</code></pre>\n\n<p>If you look at the definition of <code>init</code> action, eiter in <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/init\" rel=\"nofollow noreferrer\">docs</a> or <a href=\"https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-settings.php#L353\" rel=\"nofollow noreferrer\">source code</a> (In WodPress 4.3.1 it is in line 353 of wp-settings.php file), there is no parameters passed to the callback.</p>\n\n<p>If you want to pass custom parameters to actions and filters callbacks, you have several options. <a href=\"https://wordpress.stackexchange.com/questions/45901/passing-a-parameter-to-filter-and-action-functions\">I recommend this question and its answer to learn about it</a>. For example, using anonymous functions:</p>\n\n<pre><code>$custom = 1;\nadd_action( 'init', function () use $custom {\n\n // The value of $custom is 1\n var_dump( $custom );\n\n}, 10, 2 );\n</code></pre>\n" } ]
2015/11/24
[ "https://wordpress.stackexchange.com/questions/209649", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83610/" ]
This is so basic, but i couldn't understand why it's not working, i'm trying to send parameter from add\_action(), this is my code in my function.php: ``` function testingID( $testParam) { var_dump($testParam); die(); } add_action( 'init', 'testingID', 1,1); ``` I expect to have the screen print '1' instead just : ``` string(0) "" ``` Wondering what caused this ? Thanks
When an action is defined, the parameters passed to the callback are defined as well. For example, you can define an action with 4 parameters: ``` $a = 1; $b = 2; $c = 3; $d = 4; do_action( 'name_of_my_action', $a, $b, $c, $d ); ``` Then, when you hook in that action, you can tell how many of those parameters will be used; the value of those params are the values assigned when the action was defined. For example, you may want to use only 2: ``` // The fourth parameter is the number of accepted // parameters by the callback, in this case want only 2 // The parameters are passed to the callback in the same order // they were set when the action was definied and with the same value add_action( 'name_of_my_action', 'my_action_callback', 10, 2 ); function my_action_callback( $a, $b ) { // The value of $a is 1 var_dump( $a ); // The value of $b is 2 var_dump( $b ); } ``` If you look at the definition of `init` action, eiter in [docs](https://codex.wordpress.org/Plugin_API/Action_Reference/init) or [source code](https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-settings.php#L353) (In WodPress 4.3.1 it is in line 353 of wp-settings.php file), there is no parameters passed to the callback. If you want to pass custom parameters to actions and filters callbacks, you have several options. [I recommend this question and its answer to learn about it](https://wordpress.stackexchange.com/questions/45901/passing-a-parameter-to-filter-and-action-functions). For example, using anonymous functions: ``` $custom = 1; add_action( 'init', function () use $custom { // The value of $custom is 1 var_dump( $custom ); }, 10, 2 ); ```
209,684
<p>Can I pass dynamically to shortcode attributes like as the following example shows </p> <pre><code>[ authoorsposts author = get_the_author_id(); ] </code></pre>
[ { "answer_id": 209685, "author": "Hans Spieß", "author_id": 27933, "author_profile": "https://wordpress.stackexchange.com/users/27933", "pm_score": 0, "selected": false, "text": "<p>You could access the author object inside the <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow\">shortcode</a> function:</p>\n\n<pre><code>$author = get_the_author();\n// access ID of author object like $author-&gt;ID\n</code></pre>\n\n<p>Since shortcodes are added in the content, your Php code would be escaped and won't execute.</p>\n" }, { "answer_id": 209691, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 3, "selected": true, "text": "<p>Not quite like that, but you can achieve the same result if you use a pre-defined value or argument in your shortcode to act as a \"flag\":</p>\n\n<pre><code>[authoorsposts author=\"post\"]\n</code></pre>\n\n<p>...then in your handler:</p>\n\n<pre><code>function wpse_209684_author( $atts ) {\n if ( ! empty( $atts['author'] ) ) {\n $author = $atts['author'];\n\n if ( $author === 'post' ) // Our flag, make $author the current post author\n $author = get_the_author_id();\n else // Otherwise just accept a hardcoded author ID\n $author = absint( $author );\n }\n}\n</code></pre>\n" } ]
2015/11/24
[ "https://wordpress.stackexchange.com/questions/209684", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84181/" ]
Can I pass dynamically to shortcode attributes like as the following example shows ``` [ authoorsposts author = get_the_author_id(); ] ```
Not quite like that, but you can achieve the same result if you use a pre-defined value or argument in your shortcode to act as a "flag": ``` [authoorsposts author="post"] ``` ...then in your handler: ``` function wpse_209684_author( $atts ) { if ( ! empty( $atts['author'] ) ) { $author = $atts['author']; if ( $author === 'post' ) // Our flag, make $author the current post author $author = get_the_author_id(); else // Otherwise just accept a hardcoded author ID $author = absint( $author ); } } ```
209,694
<p>I have to add a bubble notification in WordPress <code>wp_nav_menu</code> like the following code. </p> <pre><code>&lt;ul&gt; &lt;li&gt; Tickets &lt;span class="unread"&gt;2&lt;/span&gt;&lt;/li&gt; &lt;li&gt; Log-out&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Here I have to add this part in it. </p> <pre><code>&lt;span class="unread"&gt;2&lt;/span&gt; </code></pre> <p>I have seen this one and tried it. </p> <pre><code>add_action( 'walker_nav_menu_start_el', 'wpse_10042_nav_menu_post_count', 10, 4 ); function wpse_10042_nav_menu_post_count( $output, $item, $depth, $args ) { $output .= '&lt;span class="unread"&gt;'.my_function_here().'&lt;/span&gt;'; return $output; } </code></pre> <p>And get it from here <a href="https://wordpress.stackexchange.com/questions/100427/how-to-add-post-count-to-wp-nav-menu">How to add post count to wp_nav_menu?</a></p> <p>But the problem is its adding to every menu link. I want to add it to only one menu item. Not everyone in the list. </p>
[ { "answer_id": 209696, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>For flexibility, you could assign the CSS <em>bubblecount</em> class to the corresponding menu item:</p>\n\n<p><a href=\"https://i.stack.imgur.com/MaDdX.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MaDdX.gif\" alt=\"enter image description here\"></a></p>\n\n<p>and then target it with:</p>\n\n<pre><code>if( in_array( 'bubblecount', (array) $item-&gt;classes ) )\n $output .= '&lt;span class=\"unread\"&gt;'.my_function_here().'&lt;/span&gt;';\n</code></pre>\n\n<p>in your code snippet above.</p>\n" }, { "answer_id": 209697, "author": "jimihenrik", "author_id": 64625, "author_profile": "https://wordpress.stackexchange.com/users/64625", "pm_score": 0, "selected": false, "text": "<p>How about just</p>\n\n<pre><code>function add_bubble_to_nav( $items, $args ) {\n $items .= '&lt;span class=\"unread\"&gt;stuff&lt;/span&gt;';\n return $items;\n}\nadd_filter( 'wp_nav_menu_items', 'add_bubble_to_nav', 10, 2 );\n</code></pre>\n\n<p>No need to use walker here, just go for the filter I think.</p>\n\n<p>This adds it to the end of the menu. If you need it in a specific position you could go for <code>strpos</code> to find the position and then <code>substr_replace</code> to put it in there or something.</p>\n" } ]
2015/11/24
[ "https://wordpress.stackexchange.com/questions/209694", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/43308/" ]
I have to add a bubble notification in WordPress `wp_nav_menu` like the following code. ``` <ul> <li> Tickets <span class="unread">2</span></li> <li> Log-out</li> </ul> ``` Here I have to add this part in it. ``` <span class="unread">2</span> ``` I have seen this one and tried it. ``` add_action( 'walker_nav_menu_start_el', 'wpse_10042_nav_menu_post_count', 10, 4 ); function wpse_10042_nav_menu_post_count( $output, $item, $depth, $args ) { $output .= '<span class="unread">'.my_function_here().'</span>'; return $output; } ``` And get it from here [How to add post count to wp\_nav\_menu?](https://wordpress.stackexchange.com/questions/100427/how-to-add-post-count-to-wp-nav-menu) But the problem is its adding to every menu link. I want to add it to only one menu item. Not everyone in the list.
For flexibility, you could assign the CSS *bubblecount* class to the corresponding menu item: [![enter image description here](https://i.stack.imgur.com/MaDdX.gif)](https://i.stack.imgur.com/MaDdX.gif) and then target it with: ``` if( in_array( 'bubblecount', (array) $item->classes ) ) $output .= '<span class="unread">'.my_function_here().'</span>'; ``` in your code snippet above.
209,700
<p>I am trying to generate a WordPress shortcode which will display a <a href="http://bxslider.com/" rel="nofollow">bxSlider</a>. The shortcode function itself works like a charm; I can pass my data and the shortcode is rendered properly.</p> <p><strong>The problem:</strong></p> <p>In the shortcode I also added an attribute <code>id</code>, which will be used to pass an ID used to call the slider, so for example:</p> <pre><code>$(".myid").bxSlider({ </code></pre> <p>So the <code>"myid"</code> part would be passed like <code>[myshortcode id="myid"]</code>. But as the script needs to be placed in the footer (using: <code>add_action( 'wp_footer', 'myshortcode_function');</code>). So, I have to call the <code>id</code> attribute outside the shortcode function.</p> <p>Could anybody please explain, how to pass that attribute so I can use it in another function? Please do not link me to the documentation. I read it, and I don't understand it.</p>
[ { "answer_id": 209696, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>For flexibility, you could assign the CSS <em>bubblecount</em> class to the corresponding menu item:</p>\n\n<p><a href=\"https://i.stack.imgur.com/MaDdX.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MaDdX.gif\" alt=\"enter image description here\"></a></p>\n\n<p>and then target it with:</p>\n\n<pre><code>if( in_array( 'bubblecount', (array) $item-&gt;classes ) )\n $output .= '&lt;span class=\"unread\"&gt;'.my_function_here().'&lt;/span&gt;';\n</code></pre>\n\n<p>in your code snippet above.</p>\n" }, { "answer_id": 209697, "author": "jimihenrik", "author_id": 64625, "author_profile": "https://wordpress.stackexchange.com/users/64625", "pm_score": 0, "selected": false, "text": "<p>How about just</p>\n\n<pre><code>function add_bubble_to_nav( $items, $args ) {\n $items .= '&lt;span class=\"unread\"&gt;stuff&lt;/span&gt;';\n return $items;\n}\nadd_filter( 'wp_nav_menu_items', 'add_bubble_to_nav', 10, 2 );\n</code></pre>\n\n<p>No need to use walker here, just go for the filter I think.</p>\n\n<p>This adds it to the end of the menu. If you need it in a specific position you could go for <code>strpos</code> to find the position and then <code>substr_replace</code> to put it in there or something.</p>\n" } ]
2015/11/24
[ "https://wordpress.stackexchange.com/questions/209700", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63422/" ]
I am trying to generate a WordPress shortcode which will display a [bxSlider](http://bxslider.com/). The shortcode function itself works like a charm; I can pass my data and the shortcode is rendered properly. **The problem:** In the shortcode I also added an attribute `id`, which will be used to pass an ID used to call the slider, so for example: ``` $(".myid").bxSlider({ ``` So the `"myid"` part would be passed like `[myshortcode id="myid"]`. But as the script needs to be placed in the footer (using: `add_action( 'wp_footer', 'myshortcode_function');`). So, I have to call the `id` attribute outside the shortcode function. Could anybody please explain, how to pass that attribute so I can use it in another function? Please do not link me to the documentation. I read it, and I don't understand it.
For flexibility, you could assign the CSS *bubblecount* class to the corresponding menu item: [![enter image description here](https://i.stack.imgur.com/MaDdX.gif)](https://i.stack.imgur.com/MaDdX.gif) and then target it with: ``` if( in_array( 'bubblecount', (array) $item->classes ) ) $output .= '<span class="unread">'.my_function_here().'</span>'; ``` in your code snippet above.
209,706
<p>I'm working on a plugin that modifies user capabilities and turns off a lot of things in the Admin pages. I'm having some problems with order of execution with my code, so I want to refactor it and make sure I completely understand when action hooks fire in WP, so I can tie my code to those hooks correctly.</p> <p>I did a simple trace of actions I'm interested in. I was a little surprised by the <strong>frequency</strong> of hooks firing. For example <strong>wp_loaded</strong> - you would think that happens once, but it must happen over and over again as the user traverses the admin pages. I don't understand that.</p> <p>Here's my trace, I am hoping someone can explain why it looks this way (questions embedded):</p> <pre><code>----&gt; At login dialog; enter username and password, click "log in" muplugins_loaded plugins_loaded set_current_user init wp_loaded login_init wp_login (completed login) muplugins_loaded (ok, we are doing this again?) plugins_loaded set_current_user init wp_loaded admin_menu custom_menu_order admin_init admin_bar_init admin_enqueue_scripts admin_head adminmenu in_admin_header admin_bar_menu wp_before_admin_bar_render wp_after_admin_bar_render contextual_help in_admin_footer admin_footer_text admin_footer admin_print_footer_scripts (completed admin page render?) muplugins_loaded (now all over again? - three times, why?) plugins_loaded set_current_user init wp_loaded admin_menu custom_menu_order admin_init admin_bar_init admin_enqueue_scripts admin_head adminmenu in_admin_header admin_bar_menu wp_before_admin_bar_render wp_after_admin_bar_render contextual_help in_admin_footer admin_footer_text admin_footer admin_print_footer_scripts ----&gt; Viewing Admin dashboard </code></pre>
[ { "answer_id": 209709, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>The order of the hooks should not be important. If your plugin relays on the order then maybe you are doing something that is not very stable.</p>\n\n<p>Hooks are fired at extension point, giving you ability to extend the functionality at that specific point. How you arrived there should not matter.</p>\n\n<p>Some hooks like *_head *_init and *_footer have an obvious sequence of events assumption embedded in them, but almost anything other should be execution order independent. </p>\n\n<p>You might think that you know the execution order after you have done the trace, but the order might be different if you come from XML-RPC or REST API or uploading an image or handling ajax.</p>\n\n<p>(and the direct answer to your question is that your code that is doing the trace probably has bugs)</p>\n" }, { "answer_id": 209711, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": true, "text": "<p>I'm not sure if you mean some custom login dialog, but let's do some logging when we are on the <code>wp-login.php</code> page, where we fill the <em>login form</em> and press <kbd>enter</kbd>:</p>\n\n<pre><code>#----------------- \n# Page Load #1\n#----------------- \n2015-11-24: 14:45:41 --- $_SERVER: Array\n(\n [REQUEST_URI] =&gt; /wp-login.php\n [SCRIPT_NAME] =&gt; /wp-login.php\n [DOCUMENT_URI] =&gt; /wp-login.php\n [REDIRECT_STATUS] =&gt; 200\n [SCRIPT_FILENAME] =&gt; /example.tld/wp-login.php\n [HTTP_ORIGIN] =&gt; http://example.tld\n [HTTP_REFERER] =&gt; http://example.tld/wp-login.php\n [PHP_SELF] =&gt; /wp-login.php\n)\n\n2015-11-24: 14:45:41 --- $_GET: Array\n(\n)\n\n2015-11-24: 14:45:41 --- $_POST: Array\n(\n [log] =&gt; user\n [pwd] =&gt; pass\n [wp-submit] =&gt; Log In\n [redirect_to] =&gt; http://exmple.tld/wp-admin/\n [testcookie] =&gt; 1\n)\n\n2015-11-24: 14:45:41 --- do_action: muplugins_loaded\n2015-11-24: 14:45:41 --- do_action: registered_taxonomy\n2015-11-24: 14:45:41 --- do_action: registered_taxonomy\n2015-11-24: 14:45:41 --- do_action: registered_taxonomy\n2015-11-24: 14:45:41 --- do_action: registered_taxonomy\n2015-11-24: 14:45:41 --- do_action: registered_taxonomy\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: plugins_loaded\n2015-11-24: 14:45:41 --- do_action: sanitize_comment_cookies\n2015-11-24: 14:45:41 --- do_action: setup_theme\n2015-11-24: 14:45:41 --- do_action: unload_textdomain\n2015-11-24: 14:45:41 --- do_action: load_textdomain\n2015-11-24: 14:45:41 --- do_action: after_setup_theme\n2015-11-24: 14:45:41 --- do_action: load_textdomain\n2015-11-24: 14:45:41 --- do_action: load_textdomain\n2015-11-24: 14:45:41 --- do_action: auth_cookie_malformed\n2015-11-24: 14:45:41 --- do_action: set_current_user\n2015-11-24: 14:45:41 --- do_action: init\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: registered_taxonomy\n2015-11-24: 14:45:41 --- do_action: registered_taxonomy\n2015-11-24: 14:45:41 --- do_action: registered_taxonomy\n2015-11-24: 14:45:41 --- do_action: registered_taxonomy\n2015-11-24: 14:45:41 --- do_action: registered_taxonomy\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: widgets_init\n2015-11-24: 14:45:41 --- do_action: register_sidebar\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: update_user_meta\n2015-11-24: 14:45:41 --- do_action: updated_user_meta\n2015-11-24: 14:45:41 --- do_action: update_user_meta\n2015-11-24: 14:45:41 --- do_action: remove_user_role\n2015-11-24: 14:45:41 --- do_action: update_user_meta\n2015-11-24: 14:45:41 --- do_action: updated_user_meta\n2015-11-24: 14:45:41 --- do_action: update_user_meta\n2015-11-24: 14:45:41 --- do_action: add_user_role\n2015-11-24: 14:45:41 --- do_action_ref_array: wp_default_scripts\n2015-11-24: 14:45:41 --- do_action_ref_array: wp_default_styles\n2015-11-24: 14:45:41 --- do_action: wp_loaded\n2015-11-24: 14:45:41 --- do_action: login_init\n2015-11-24: 14:45:41 --- do_action: login_form_login\n2015-11-24: 14:45:41 --- do_action_ref_array: wp_authenticate\n2015-11-24: 14:45:41 --- do_action: add_user_meta\n2015-11-24: 14:45:41 --- do_action: added_user_meta\n2015-11-24: 14:45:41 --- do_action: set_auth_cookie\n2015-11-24: 14:45:41 --- do_action: set_logged_in_cookie\n2015-11-24: 14:45:41 --- do_action: wp_login\n2015-11-24: 14:45:41 --- ** Redirect location: http://example.tld/wp-admin/\n2015-11-24: 14:45:41 --- ** Redirect status: 302\n2015-11-24: 14:45:41 --- do_action: shutdown\n\n#----------------- \n# Page Load #2\n#----------------- \n2015-11-24: 14:45:41 --- $_SERVER: Array\n(\n [REQUEST_URI] =&gt; /wp-admin/\n [QUERY_STRING] =&gt; \n [REQUEST_METHOD] =&gt; GET\n [SCRIPT_NAME] =&gt; /wp-admin/index.php\n [DOCUMENT_URI] =&gt; /wp-admin/index.php\n [REDIRECT_STATUS] =&gt; 200\n [SCRIPT_FILENAME] =&gt; /example.tld//wp-admin/index.php\n [HTTP_REFERER] =&gt; http://example.tld/wp-login.php\n [PHP_SELF] =&gt; /wp-admin/index.php\n)\n\n2015-11-24: 14:45:41 --- $_GET: Array\n(\n)\n\n2015-11-24: 14:45:41 --- $_POST: Array\n(\n)\n\n2015-11-24: 14:45:41 --- do_action: muplugins_loaded\n2015-11-24: 14:45:41 --- do_action: registered_taxonomy\n2015-11-24: 14:45:41 --- do_action: registered_taxonomy\n2015-11-24: 14:45:41 --- do_action: registered_taxonomy\n2015-11-24: 14:45:41 --- do_action: registered_taxonomy\n2015-11-24: 14:45:41 --- do_action: registered_taxonomy\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: plugins_loaded\n2015-11-24: 14:45:41 --- do_action: sanitize_comment_cookies\n2015-11-24: 14:45:41 --- do_action: setup_theme\n2015-11-24: 14:45:41 --- do_action: unload_textdomain\n2015-11-24: 14:45:41 --- do_action: load_textdomain\n2015-11-24: 14:45:41 --- do_action: load_textdomain\n2015-11-24: 14:45:41 --- do_action: after_setup_theme\n2015-11-24: 14:45:41 --- do_action: load_textdomain\n2015-11-24: 14:45:41 --- do_action: load_textdomain\n2015-11-24: 14:45:41 --- do_action: auth_cookie_valid\n2015-11-24: 14:45:41 --- do_action: set_current_user\n2015-11-24: 14:45:41 --- do_action: init\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: registered_taxonomy\n2015-11-24: 14:45:41 --- do_action: registered_taxonomy\n2015-11-24: 14:45:41 --- do_action: registered_taxonomy\n2015-11-24: 14:45:41 --- do_action: registered_taxonomy\n2015-11-24: 14:45:41 --- do_action: registered_taxonomy\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: widgets_init\n2015-11-24: 14:45:41 --- do_action: register_sidebar\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget\n2015-11-24: 14:45:41 --- do_action: registered_post_type\n2015-11-24: 14:45:41 --- do_action: update_user_meta\n2015-11-24: 14:45:41 --- do_action: updated_user_meta\n2015-11-24: 14:45:41 --- do_action: update_user_meta\n2015-11-24: 14:45:41 --- do_action: remove_user_role\n2015-11-24: 14:45:41 --- do_action: update_user_meta\n2015-11-24: 14:45:41 --- do_action: updated_user_meta\n2015-11-24: 14:45:41 --- do_action: update_user_meta\n2015-11-24: 14:45:41 --- do_action: add_user_role\n2015-11-24: 14:45:41 --- do_action_ref_array: wp_default_scripts\n2015-11-24: 14:45:41 --- do_action_ref_array: wp_default_styles\n2015-11-24: 14:45:41 --- do_action: load_textdomain\n2015-11-24: 14:45:41 --- do_action: load_textdomain\n2015-11-24: 14:45:41 --- do_action: wp_loaded\n2015-11-24: 14:45:41 --- do_action: auth_cookie_valid\n2015-11-24: 14:45:41 --- do_action: auth_redirect\n2015-11-24: 14:45:41 --- do_action: _admin_menu\n2015-11-24: 14:45:41 --- do_action: admin_menu\n2015-11-24: 14:45:41 --- do_action: admin_init\n2015-11-24: 14:45:41 --- do_action: admin_bar_init\n2015-11-24: 14:45:41 --- do_action: add_admin_bar_menus\n2015-11-24: 14:45:41 --- do_action: test_custom_rewrite\n2015-11-24: 14:45:41 --- do_action: current_screen\n2015-11-24: 14:45:41 --- do_action: load-index.php\n2015-11-24: 14:45:41 --- do_action: wp_dashboard_setup\n2015-11-24: 14:45:41 --- do_action: do_meta_boxes\n2015-11-24: 14:45:41 --- do_action: do_meta_boxes\n2015-11-24: 14:45:41 --- do_action: admin_xml_ns\n2015-11-24: 14:45:41 --- do_action: admin_xml_ns\n2015-11-24: 14:45:41 --- do_action: admin_enqueue_scripts\n2015-11-24: 14:45:41 --- do_action: admin_print_styles-index.php\n2015-11-24: 14:45:41 --- do_action: admin_print_styles\n2015-11-24: 14:45:41 --- do_action: admin_print_scripts-index.php\n2015-11-24: 14:45:41 --- do_action: admin_print_scripts\n2015-11-24: 14:45:41 --- do_action: wp_print_scripts\n2015-11-24: 14:45:41 --- do_action: admin_head-index.php\n2015-11-24: 14:45:41 --- do_action: admin_head\n2015-11-24: 14:45:41 --- do_action: adminmenu\n2015-11-24: 14:45:41 --- do_action: in_admin_header\n2015-11-24: 14:45:41 --- do_action_ref_array: admin_bar_menu\n2015-11-24: 14:45:41 --- do_action: wp_before_admin_bar_render\n2015-11-24: 14:45:41 --- do_action: wp_after_admin_bar_render\n2015-11-24: 14:45:41 --- do_action: admin_notices\n2015-11-24: 14:45:41 --- do_action: all_admin_notices\n2015-11-24: 14:45:41 --- do_action: welcome_panel\n2015-11-24: 14:45:41 --- do_action: rightnow_end\n2015-11-24: 14:45:41 --- do_action: activity_box_end\n2015-11-24: 14:45:41 --- do_action: parse_tax_query\n2015-11-24: 14:45:41 --- do_action_ref_array: parse_query\n2015-11-24: 14:45:41 --- do_action_ref_array: pre_get_posts\n2015-11-24: 14:45:41 --- do_action: parse_tax_query\n2015-11-24: 14:45:41 --- do_action: posts_selection\n2015-11-24: 14:45:41 --- do_action: parse_tax_query\n2015-11-24: 14:45:41 --- do_action_ref_array: parse_query\n2015-11-24: 14:45:41 --- do_action_ref_array: pre_get_posts\n2015-11-24: 14:45:41 --- do_action: parse_tax_query\n2015-11-24: 14:45:41 --- do_action: posts_selection\n2015-11-24: 14:45:41 --- do_action_ref_array: loop_start\n2015-11-24: 14:45:41 --- do_action_ref_array: the_post\n2015-11-24: 14:45:41 --- do_action_ref_array: the_post\n2015-11-24: 14:45:41 --- do_action_ref_array: the_post\n2015-11-24: 14:45:41 --- do_action_ref_array: the_post\n2015-11-24: 14:45:41 --- do_action_ref_array: the_post\n2015-11-24: 14:45:41 --- do_action_ref_array: loop_end\n2015-11-24: 14:45:41 --- do_action_ref_array: parse_comment_query\n2015-11-24: 14:45:41 --- do_action_ref_array: pre_get_comments\n2015-11-24: 14:45:42 --- do_action: parse_tax_query\n2015-11-24: 14:45:42 --- do_action_ref_array: parse_query\n2015-11-24: 14:45:42 --- do_action_ref_array: pre_get_posts\n2015-11-24: 14:45:42 --- do_action: parse_tax_query\n2015-11-24: 14:45:42 --- do_action: posts_selection\n2015-11-24: 14:45:42 --- do_action: in_admin_footer\n2015-11-24: 14:45:42 --- do_action: admin_footer\n2015-11-24: 14:45:42 --- do_action: admin_print_footer_scripts\n2015-11-24: 14:45:42 --- do_action: wp_enqueue_editor\n2015-11-24: 14:45:42 --- do_action: before_wp_tiny_mce\n2015-11-24: 14:45:42 --- do_action: wp_tiny_mce_init\n2015-11-24: 14:45:42 --- do_action: after_wp_tiny_mce\n2015-11-24: 14:45:42 --- do_action: admin_footer-index.php\n2015-11-24: 14:45:42 --- do_action: shutdown\n</code></pre>\n\n<p>We see that we are <strong>redirected</strong> from <code>wp-login.php</code> to <code>/wp-admin/index.php</code> - no surprise there ;-)</p>\n\n<p><em>So a redirection (or ajax calls?) might explain some duplicate part of your logging.</em> </p>\n\n<p><strong>Update:</strong> I marked the redirect call with <code>**</code>.</p>\n" }, { "answer_id": 209757, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<p>The frequency and order of hooks can vary based on each theme or plugin you you have installed/activated, but obviously there is a typical order for core actions and filters. do_action( 'muplugins_loaded' ) is in wp-settings.php so you'll see that event each time PHP includes that file. Any request to WordPress will usually make sure it is loaded.</p>\n\n<p>If you want to know how often and which hooks run on your site then I highly recommend installing the plugin <a href=\"https://wordpress.org/plugins/query-monitor/\" rel=\"nofollow\">Query Monitor</a> for WordPress.</p>\n\n<p><a href=\"https://wordpress.org/plugins/debug-bar/\" rel=\"nofollow\">Debug Bar</a> is another plugin that might help you understand what's going on.</p>\n\n<p>And if you want to see ALL the filters, then you can always add this to your functions.php</p>\n\n<pre><code>if ( !function_exists( 'debug_all_callback')) {\n\nfunction debug_all_callback($arg1 = '')\n{\n global $filters_called;\n $filters_called[] = $arg1;\n}\n\nfunction debug_on_shutdown_callback()\n{\n global $filters_called;\n echo \"&lt;pre&gt;\";\n print_r($filters_called);\n echo \"&lt;/pre&gt;\";\n}\n\n// event collector\nglobal $filters_called;\n$filters_called = array();\n\n// subscribe to all hooks and filters\nadd_filter( \"all\", \"debug_all_callback\");\nadd_action( 'all', \"debug_all_callback\" );\n\n// output list to screen\nadd_action(\"shutdown\", \"debug_on_shutdown_callback\");\n\n}\n</code></pre>\n" } ]
2015/11/24
[ "https://wordpress.stackexchange.com/questions/209706", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83299/" ]
I'm working on a plugin that modifies user capabilities and turns off a lot of things in the Admin pages. I'm having some problems with order of execution with my code, so I want to refactor it and make sure I completely understand when action hooks fire in WP, so I can tie my code to those hooks correctly. I did a simple trace of actions I'm interested in. I was a little surprised by the **frequency** of hooks firing. For example **wp\_loaded** - you would think that happens once, but it must happen over and over again as the user traverses the admin pages. I don't understand that. Here's my trace, I am hoping someone can explain why it looks this way (questions embedded): ``` ----> At login dialog; enter username and password, click "log in" muplugins_loaded plugins_loaded set_current_user init wp_loaded login_init wp_login (completed login) muplugins_loaded (ok, we are doing this again?) plugins_loaded set_current_user init wp_loaded admin_menu custom_menu_order admin_init admin_bar_init admin_enqueue_scripts admin_head adminmenu in_admin_header admin_bar_menu wp_before_admin_bar_render wp_after_admin_bar_render contextual_help in_admin_footer admin_footer_text admin_footer admin_print_footer_scripts (completed admin page render?) muplugins_loaded (now all over again? - three times, why?) plugins_loaded set_current_user init wp_loaded admin_menu custom_menu_order admin_init admin_bar_init admin_enqueue_scripts admin_head adminmenu in_admin_header admin_bar_menu wp_before_admin_bar_render wp_after_admin_bar_render contextual_help in_admin_footer admin_footer_text admin_footer admin_print_footer_scripts ----> Viewing Admin dashboard ```
I'm not sure if you mean some custom login dialog, but let's do some logging when we are on the `wp-login.php` page, where we fill the *login form* and press `enter`: ``` #----------------- # Page Load #1 #----------------- 2015-11-24: 14:45:41 --- $_SERVER: Array ( [REQUEST_URI] => /wp-login.php [SCRIPT_NAME] => /wp-login.php [DOCUMENT_URI] => /wp-login.php [REDIRECT_STATUS] => 200 [SCRIPT_FILENAME] => /example.tld/wp-login.php [HTTP_ORIGIN] => http://example.tld [HTTP_REFERER] => http://example.tld/wp-login.php [PHP_SELF] => /wp-login.php ) 2015-11-24: 14:45:41 --- $_GET: Array ( ) 2015-11-24: 14:45:41 --- $_POST: Array ( [log] => user [pwd] => pass [wp-submit] => Log In [redirect_to] => http://exmple.tld/wp-admin/ [testcookie] => 1 ) 2015-11-24: 14:45:41 --- do_action: muplugins_loaded 2015-11-24: 14:45:41 --- do_action: registered_taxonomy 2015-11-24: 14:45:41 --- do_action: registered_taxonomy 2015-11-24: 14:45:41 --- do_action: registered_taxonomy 2015-11-24: 14:45:41 --- do_action: registered_taxonomy 2015-11-24: 14:45:41 --- do_action: registered_taxonomy 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: plugins_loaded 2015-11-24: 14:45:41 --- do_action: sanitize_comment_cookies 2015-11-24: 14:45:41 --- do_action: setup_theme 2015-11-24: 14:45:41 --- do_action: unload_textdomain 2015-11-24: 14:45:41 --- do_action: load_textdomain 2015-11-24: 14:45:41 --- do_action: after_setup_theme 2015-11-24: 14:45:41 --- do_action: load_textdomain 2015-11-24: 14:45:41 --- do_action: load_textdomain 2015-11-24: 14:45:41 --- do_action: auth_cookie_malformed 2015-11-24: 14:45:41 --- do_action: set_current_user 2015-11-24: 14:45:41 --- do_action: init 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: registered_taxonomy 2015-11-24: 14:45:41 --- do_action: registered_taxonomy 2015-11-24: 14:45:41 --- do_action: registered_taxonomy 2015-11-24: 14:45:41 --- do_action: registered_taxonomy 2015-11-24: 14:45:41 --- do_action: registered_taxonomy 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: widgets_init 2015-11-24: 14:45:41 --- do_action: register_sidebar 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: update_user_meta 2015-11-24: 14:45:41 --- do_action: updated_user_meta 2015-11-24: 14:45:41 --- do_action: update_user_meta 2015-11-24: 14:45:41 --- do_action: remove_user_role 2015-11-24: 14:45:41 --- do_action: update_user_meta 2015-11-24: 14:45:41 --- do_action: updated_user_meta 2015-11-24: 14:45:41 --- do_action: update_user_meta 2015-11-24: 14:45:41 --- do_action: add_user_role 2015-11-24: 14:45:41 --- do_action_ref_array: wp_default_scripts 2015-11-24: 14:45:41 --- do_action_ref_array: wp_default_styles 2015-11-24: 14:45:41 --- do_action: wp_loaded 2015-11-24: 14:45:41 --- do_action: login_init 2015-11-24: 14:45:41 --- do_action: login_form_login 2015-11-24: 14:45:41 --- do_action_ref_array: wp_authenticate 2015-11-24: 14:45:41 --- do_action: add_user_meta 2015-11-24: 14:45:41 --- do_action: added_user_meta 2015-11-24: 14:45:41 --- do_action: set_auth_cookie 2015-11-24: 14:45:41 --- do_action: set_logged_in_cookie 2015-11-24: 14:45:41 --- do_action: wp_login 2015-11-24: 14:45:41 --- ** Redirect location: http://example.tld/wp-admin/ 2015-11-24: 14:45:41 --- ** Redirect status: 302 2015-11-24: 14:45:41 --- do_action: shutdown #----------------- # Page Load #2 #----------------- 2015-11-24: 14:45:41 --- $_SERVER: Array ( [REQUEST_URI] => /wp-admin/ [QUERY_STRING] => [REQUEST_METHOD] => GET [SCRIPT_NAME] => /wp-admin/index.php [DOCUMENT_URI] => /wp-admin/index.php [REDIRECT_STATUS] => 200 [SCRIPT_FILENAME] => /example.tld//wp-admin/index.php [HTTP_REFERER] => http://example.tld/wp-login.php [PHP_SELF] => /wp-admin/index.php ) 2015-11-24: 14:45:41 --- $_GET: Array ( ) 2015-11-24: 14:45:41 --- $_POST: Array ( ) 2015-11-24: 14:45:41 --- do_action: muplugins_loaded 2015-11-24: 14:45:41 --- do_action: registered_taxonomy 2015-11-24: 14:45:41 --- do_action: registered_taxonomy 2015-11-24: 14:45:41 --- do_action: registered_taxonomy 2015-11-24: 14:45:41 --- do_action: registered_taxonomy 2015-11-24: 14:45:41 --- do_action: registered_taxonomy 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: plugins_loaded 2015-11-24: 14:45:41 --- do_action: sanitize_comment_cookies 2015-11-24: 14:45:41 --- do_action: setup_theme 2015-11-24: 14:45:41 --- do_action: unload_textdomain 2015-11-24: 14:45:41 --- do_action: load_textdomain 2015-11-24: 14:45:41 --- do_action: load_textdomain 2015-11-24: 14:45:41 --- do_action: after_setup_theme 2015-11-24: 14:45:41 --- do_action: load_textdomain 2015-11-24: 14:45:41 --- do_action: load_textdomain 2015-11-24: 14:45:41 --- do_action: auth_cookie_valid 2015-11-24: 14:45:41 --- do_action: set_current_user 2015-11-24: 14:45:41 --- do_action: init 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: registered_taxonomy 2015-11-24: 14:45:41 --- do_action: registered_taxonomy 2015-11-24: 14:45:41 --- do_action: registered_taxonomy 2015-11-24: 14:45:41 --- do_action: registered_taxonomy 2015-11-24: 14:45:41 --- do_action: registered_taxonomy 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: widgets_init 2015-11-24: 14:45:41 --- do_action: register_sidebar 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: wp_register_sidebar_widget 2015-11-24: 14:45:41 --- do_action: registered_post_type 2015-11-24: 14:45:41 --- do_action: update_user_meta 2015-11-24: 14:45:41 --- do_action: updated_user_meta 2015-11-24: 14:45:41 --- do_action: update_user_meta 2015-11-24: 14:45:41 --- do_action: remove_user_role 2015-11-24: 14:45:41 --- do_action: update_user_meta 2015-11-24: 14:45:41 --- do_action: updated_user_meta 2015-11-24: 14:45:41 --- do_action: update_user_meta 2015-11-24: 14:45:41 --- do_action: add_user_role 2015-11-24: 14:45:41 --- do_action_ref_array: wp_default_scripts 2015-11-24: 14:45:41 --- do_action_ref_array: wp_default_styles 2015-11-24: 14:45:41 --- do_action: load_textdomain 2015-11-24: 14:45:41 --- do_action: load_textdomain 2015-11-24: 14:45:41 --- do_action: wp_loaded 2015-11-24: 14:45:41 --- do_action: auth_cookie_valid 2015-11-24: 14:45:41 --- do_action: auth_redirect 2015-11-24: 14:45:41 --- do_action: _admin_menu 2015-11-24: 14:45:41 --- do_action: admin_menu 2015-11-24: 14:45:41 --- do_action: admin_init 2015-11-24: 14:45:41 --- do_action: admin_bar_init 2015-11-24: 14:45:41 --- do_action: add_admin_bar_menus 2015-11-24: 14:45:41 --- do_action: test_custom_rewrite 2015-11-24: 14:45:41 --- do_action: current_screen 2015-11-24: 14:45:41 --- do_action: load-index.php 2015-11-24: 14:45:41 --- do_action: wp_dashboard_setup 2015-11-24: 14:45:41 --- do_action: do_meta_boxes 2015-11-24: 14:45:41 --- do_action: do_meta_boxes 2015-11-24: 14:45:41 --- do_action: admin_xml_ns 2015-11-24: 14:45:41 --- do_action: admin_xml_ns 2015-11-24: 14:45:41 --- do_action: admin_enqueue_scripts 2015-11-24: 14:45:41 --- do_action: admin_print_styles-index.php 2015-11-24: 14:45:41 --- do_action: admin_print_styles 2015-11-24: 14:45:41 --- do_action: admin_print_scripts-index.php 2015-11-24: 14:45:41 --- do_action: admin_print_scripts 2015-11-24: 14:45:41 --- do_action: wp_print_scripts 2015-11-24: 14:45:41 --- do_action: admin_head-index.php 2015-11-24: 14:45:41 --- do_action: admin_head 2015-11-24: 14:45:41 --- do_action: adminmenu 2015-11-24: 14:45:41 --- do_action: in_admin_header 2015-11-24: 14:45:41 --- do_action_ref_array: admin_bar_menu 2015-11-24: 14:45:41 --- do_action: wp_before_admin_bar_render 2015-11-24: 14:45:41 --- do_action: wp_after_admin_bar_render 2015-11-24: 14:45:41 --- do_action: admin_notices 2015-11-24: 14:45:41 --- do_action: all_admin_notices 2015-11-24: 14:45:41 --- do_action: welcome_panel 2015-11-24: 14:45:41 --- do_action: rightnow_end 2015-11-24: 14:45:41 --- do_action: activity_box_end 2015-11-24: 14:45:41 --- do_action: parse_tax_query 2015-11-24: 14:45:41 --- do_action_ref_array: parse_query 2015-11-24: 14:45:41 --- do_action_ref_array: pre_get_posts 2015-11-24: 14:45:41 --- do_action: parse_tax_query 2015-11-24: 14:45:41 --- do_action: posts_selection 2015-11-24: 14:45:41 --- do_action: parse_tax_query 2015-11-24: 14:45:41 --- do_action_ref_array: parse_query 2015-11-24: 14:45:41 --- do_action_ref_array: pre_get_posts 2015-11-24: 14:45:41 --- do_action: parse_tax_query 2015-11-24: 14:45:41 --- do_action: posts_selection 2015-11-24: 14:45:41 --- do_action_ref_array: loop_start 2015-11-24: 14:45:41 --- do_action_ref_array: the_post 2015-11-24: 14:45:41 --- do_action_ref_array: the_post 2015-11-24: 14:45:41 --- do_action_ref_array: the_post 2015-11-24: 14:45:41 --- do_action_ref_array: the_post 2015-11-24: 14:45:41 --- do_action_ref_array: the_post 2015-11-24: 14:45:41 --- do_action_ref_array: loop_end 2015-11-24: 14:45:41 --- do_action_ref_array: parse_comment_query 2015-11-24: 14:45:41 --- do_action_ref_array: pre_get_comments 2015-11-24: 14:45:42 --- do_action: parse_tax_query 2015-11-24: 14:45:42 --- do_action_ref_array: parse_query 2015-11-24: 14:45:42 --- do_action_ref_array: pre_get_posts 2015-11-24: 14:45:42 --- do_action: parse_tax_query 2015-11-24: 14:45:42 --- do_action: posts_selection 2015-11-24: 14:45:42 --- do_action: in_admin_footer 2015-11-24: 14:45:42 --- do_action: admin_footer 2015-11-24: 14:45:42 --- do_action: admin_print_footer_scripts 2015-11-24: 14:45:42 --- do_action: wp_enqueue_editor 2015-11-24: 14:45:42 --- do_action: before_wp_tiny_mce 2015-11-24: 14:45:42 --- do_action: wp_tiny_mce_init 2015-11-24: 14:45:42 --- do_action: after_wp_tiny_mce 2015-11-24: 14:45:42 --- do_action: admin_footer-index.php 2015-11-24: 14:45:42 --- do_action: shutdown ``` We see that we are **redirected** from `wp-login.php` to `/wp-admin/index.php` - no surprise there ;-) *So a redirection (or ajax calls?) might explain some duplicate part of your logging.* **Update:** I marked the redirect call with `**`.
209,712
<p>I want to query attachments and exclude all images. </p> <p>I can see how to include <em>only</em> images, using <code>'post_mime_type' =&gt; 'image/*'</code>, but I couldn't find any way of achieving the opposite. Is there any mime_type equivalent of <code>posts__not_in</code>?</p>
[ { "answer_id": 209714, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 5, "selected": true, "text": "<p>Pretty much the solution is to include all mimes <em>except</em> images. WordPress has a nifty little function where it keeps all it's accepted mime-types called <a href=\"https://codex.wordpress.org/Function_Reference/get_allowed_mime_types\"><code>get_allowed_mime_types()</code></a> ( cleverly named ) which returns an Array() of mimes. All we need to do is get the difference between the returned array and the array of mime-types we don't want in our query:</p>\n\n<pre><code>$unsupported_mimes = array( 'image/jpeg', 'image/gif', 'image/png', 'image/bmp', 'image/tiff', 'image/x-icon' );\n$all_mimes = get_allowed_mime_types();\n$accepted_mimes = array_diff( $all_mimes, $unsupported_mimes );\n$attachment_query = new WP_Query( array(\n 'post_type' =&gt; 'attachment',\n 'post_status' =&gt; 'inherit',\n 'post_mime_type' =&gt; $accepted_mimes,\n 'posts_per_page' =&gt; 20,\n) );\n</code></pre>\n" }, { "answer_id": 209715, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>I'm pretty much certain there isn't an equivalent of <code>posts_not_in</code> for mime types.</p>\n\n<p>You could of course query for all attachments that are images. Preferably just returning the IDs via parameter <code>fields</code> set to <code>ids</code>. Then you can use those IDs with <code>posts__not_in</code> on a second query. Drawback being that you need two queries.</p>\n\n<p>Another possibility would be to hook into the <code>posts_where</code> filter and apply some SQL to get your result like you want it.</p>\n" }, { "answer_id": 209720, "author": "SinisterBeard", "author_id": 63673, "author_profile": "https://wordpress.stackexchange.com/users/63673", "pm_score": 2, "selected": false, "text": "<p>If you also want to include post types other than attachments (e.g. posts, pages) that don't have any mime type, you'll have to use the <code>posts_where</code> filter:</p>\n\n<pre><code>add_filter( 'posts_where' , 'remove_images' );\n\nfunction remove_images($where) {\n global $wpdb;\n $where.=' AND '.$wpdb-&gt;posts.'.post_mime_type NOT LIKE \\'image/%\\'';\n return $where;\n}\n</code></pre>\n" } ]
2015/11/24
[ "https://wordpress.stackexchange.com/questions/209712", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63673/" ]
I want to query attachments and exclude all images. I can see how to include *only* images, using `'post_mime_type' => 'image/*'`, but I couldn't find any way of achieving the opposite. Is there any mime\_type equivalent of `posts__not_in`?
Pretty much the solution is to include all mimes *except* images. WordPress has a nifty little function where it keeps all it's accepted mime-types called [`get_allowed_mime_types()`](https://codex.wordpress.org/Function_Reference/get_allowed_mime_types) ( cleverly named ) which returns an Array() of mimes. All we need to do is get the difference between the returned array and the array of mime-types we don't want in our query: ``` $unsupported_mimes = array( 'image/jpeg', 'image/gif', 'image/png', 'image/bmp', 'image/tiff', 'image/x-icon' ); $all_mimes = get_allowed_mime_types(); $accepted_mimes = array_diff( $all_mimes, $unsupported_mimes ); $attachment_query = new WP_Query( array( 'post_type' => 'attachment', 'post_status' => 'inherit', 'post_mime_type' => $accepted_mimes, 'posts_per_page' => 20, ) ); ```
209,717
<p>I'm trying to create a plugin for wordpress where the form stores data in a database. I'm trying to make a submit button to update the status (field) of one row from 0 to 1 but its updating all the column, how can i make to update only the selected one.</p> <p>Look at the code...</p> <pre><code>&lt;table class="widefat"&gt; &lt;thead&gt; &lt;tr&gt;&lt;th class="row-title"&gt;&lt;?php esc_attr_e( 'Application', 'aa' ); ?&gt;&lt;/th&gt; &lt;th class="row-title"&gt;&lt;?php esc_attr_e( 'Name', 'aa' ); ?&gt;&lt;/th&gt; &lt;th&gt;&lt;?php esc_attr_e( 'Email', 'aa' ); ?&gt;&lt;/th&gt; &lt;th&gt;&lt;?php esc_attr_e( 'Message', 'aa' ); ?&gt;&lt;/th&gt; &lt;th&gt;&lt;?php esc_attr_e( 'Time', 'aa' ); ?&gt;&lt;/th&gt; &lt;th&gt;&lt;?php esc_attr_e( 'Birthplace', 'aa' ); ?&gt;&lt;/th&gt; &lt;th&gt;&lt;?php esc_attr_e( 'Birthday', 'aa' ); ?&gt;&lt;/th&gt; &lt;th&gt;&lt;?php esc_attr_e( 'Sex', 'aa' ); ?&gt;&lt;/th&gt; &lt;th&gt;&lt;?php esc_attr_e( 'Status', 'aa' ); ?&gt;&lt;/th&gt; &lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;?php foreach($client_msg as $client): ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php esc_attr_e($client-&gt;name,'aa');?&gt;&lt;/a&gt;&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;&lt;?php esc_attr_e($client-&gt;name,'aa');?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php esc_attr_e($client-&gt;email,'aa');?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php esc_attr_e($client-&gt;msg,'aa');?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php esc_attr_e($client-&gt;time,'aa');?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php esc_attr_e($client-&gt;birthplace,'aa');?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php esc_attr_e($client-&gt;birthday,'aa');?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php esc_attr_e($client-&gt;Sex,'aa');?&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="submit" name="activate" id="activate" value="Activate" onclick="change()" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tr&gt; &lt;?php endforeach;?&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; function change(){ $sql="UPDATE wp_applications SET status = '1'" ; $result = mysql_query($sql) or die(mysql_error()); ?&gt;} &lt;/script&gt; </code></pre> <p>That how it looks in wordpress the form that collects the data from database<a href="https://i.stack.imgur.com/A0apy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A0apy.png" alt="enter image description here"></a></p> <p>I need to change the field in database through that button but when i click as i mention it changes for all records. </p> <p>the idea of this is to create a plugin which will be used for applications and then select candidates for interview.</p>
[ { "answer_id": 209718, "author": "nipeco", "author_id": 84195, "author_profile": "https://wordpress.stackexchange.com/users/84195", "pm_score": 1, "selected": false, "text": "<p>Well I would add another parameter to the <code>change()</code> function like <strong>id</strong>.\nI am a little bit confused that your PHP code is wrapped in JavaScript Tags :D</p>\n\n<p>In PHP i would do it like that:</p>\n\n<pre><code>function change($id) {\n $sql=\"UPDATE wp_applications SET status = '1' WHERE id = '$id'\";\n...\n</code></pre>\n\n<p>In the form i assume the id is stored in id column:</p>\n\n<pre><code>&lt;input type=\"submit\" name=\"activate\" id=\"activate\" value=\"Activate\" onclick=\"change($client-&gt;id)\" /&gt;\n</code></pre>\n" }, { "answer_id": 209726, "author": "jamiek", "author_id": 72968, "author_profile": "https://wordpress.stackexchange.com/users/72968", "pm_score": 0, "selected": false, "text": "<p>Depends on how you plan on storing the data.</p>\n\n<p>If you just want arbitrary data to store via form user input, I use Formidable Pro plugin. It's very powerful and has many options for manipulating and viewing data.</p>\n\n<p>If you are wanting to tie the data to the user meta, i have been playing with this approach: <a href=\"https://patrickshampine.com/2014/updating-user-meta-admin-ajax-frontend/\" rel=\"nofollow\">https://patrickshampine.com/2014/updating-user-meta-admin-ajax-frontend/</a> which allows the front end to edit outside of profile page.</p>\n\n<p>At the same time if you want to use all wordpress provides you, you can do an all inclusive \"profile page,\" since it looks like all your data is user related, and allow users to update their profiles. Add fields to the profile page like this:</p>\n\n<p><a href=\"https://developer.wordpress.org/plugins/users/working-with-user-metadata/\" rel=\"nofollow\">https://developer.wordpress.org/plugins/users/working-with-user-metadata/</a></p>\n\n<p>The last option I have used successfully and it's pretty clean. You'll just need to add fields as desired.</p>\n\n<p>Jamie</p>\n\n<p>PS: usually you want to enqueue any javascript you use within wordpress via enqueue_script().</p>\n" } ]
2015/11/24
[ "https://wordpress.stackexchange.com/questions/209717", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84200/" ]
I'm trying to create a plugin for wordpress where the form stores data in a database. I'm trying to make a submit button to update the status (field) of one row from 0 to 1 but its updating all the column, how can i make to update only the selected one. Look at the code... ``` <table class="widefat"> <thead> <tr><th class="row-title"><?php esc_attr_e( 'Application', 'aa' ); ?></th> <th class="row-title"><?php esc_attr_e( 'Name', 'aa' ); ?></th> <th><?php esc_attr_e( 'Email', 'aa' ); ?></th> <th><?php esc_attr_e( 'Message', 'aa' ); ?></th> <th><?php esc_attr_e( 'Time', 'aa' ); ?></th> <th><?php esc_attr_e( 'Birthplace', 'aa' ); ?></th> <th><?php esc_attr_e( 'Birthday', 'aa' ); ?></th> <th><?php esc_attr_e( 'Sex', 'aa' ); ?></th> <th><?php esc_attr_e( 'Status', 'aa' ); ?></th> </th> </tr> </thead> <tbody> <?php foreach($client_msg as $client): ?> <tr> <td><?php esc_attr_e($client->name,'aa');?></a></strong></td> <td><?php esc_attr_e($client->name,'aa');?></td> <td><?php esc_attr_e($client->email,'aa');?></td> <td><?php esc_attr_e($client->msg,'aa');?></td> <td><?php esc_attr_e($client->time,'aa');?></td> <td><?php esc_attr_e($client->birthplace,'aa');?></td> <td><?php esc_attr_e($client->birthday,'aa');?></td> <td><?php esc_attr_e($client->Sex,'aa');?></td> <td><input type="submit" name="activate" id="activate" value="Activate" onclick="change()" /></td> </tr> </tr> <?php endforeach;?> </tbody> </table> </div> <script type="text/javascript"> function change(){ $sql="UPDATE wp_applications SET status = '1'" ; $result = mysql_query($sql) or die(mysql_error()); ?>} </script> ``` That how it looks in wordpress the form that collects the data from database[![enter image description here](https://i.stack.imgur.com/A0apy.png)](https://i.stack.imgur.com/A0apy.png) I need to change the field in database through that button but when i click as i mention it changes for all records. the idea of this is to create a plugin which will be used for applications and then select candidates for interview.
Well I would add another parameter to the `change()` function like **id**. I am a little bit confused that your PHP code is wrapped in JavaScript Tags :D In PHP i would do it like that: ``` function change($id) { $sql="UPDATE wp_applications SET status = '1' WHERE id = '$id'"; ... ``` In the form i assume the id is stored in id column: ``` <input type="submit" name="activate" id="activate" value="Activate" onclick="change($client->id)" /> ```
209,729
<p>Trying to use <code>admin-ajax.php</code> to upload image from front-end form. I'm keep getting <code>0</code> with below code I have and not sure how to debug this or where it goes wrong.</p> <p>I have HTML input file</p> <pre><code>&lt;input type="file" name="wh_image_upload" id="wh_image_upload" multiple="false" /&gt; </code></pre> <p>and localized script for AJAX request</p> <pre><code>$img_nonce = wp_create_nonce('image_upload_nonce'); wp_localize_script( 'ajax-script', 'ajax_image', array( 'ajax_url' =&gt; admin_url( 'admin-ajax.php' )) ); </code></pre> <p>and PHP function</p> <pre><code>function write_here_featured_image_upload() { var_dump($_FILES); die(); } add_action( 'wp_ajax_write_here_img_upload', 'write_here_featured_image_upload' ); add_action( 'wp_ajax_nopriv_write_here_img_upload', 'write_here_featured_image_upload' ); </code></pre> <p>JS</p> <pre><code>// Featured image upload AJAX $("#wh_image_upload").change(function(){ var userFile = new FormData(); var fileInput = $( "#wh_image_upload" )[0].files[0]; //console.log(fileInput); userFile.append("file", fileInput); userFile.append("action", "write_here_img_upload"); $.ajax({ type: "POST", url: ajax_object.ajax_url, data: userFile, processData: false, contentType: false, error: function(jqXHR, textStatus, errorMessage) { console.log(errorMessage); }, success: function(data) { console.log("Image Uploaded! " + data); } }); }); </code></pre> <p>I get a AJAX success message with response <code>0</code>. <code>Image Uploaded! 0</code></p> <p><strong>Update</strong> I updated my working code.</p>
[ { "answer_id": 209734, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 4, "selected": true, "text": "<h2><a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"noreferrer\">Enable Debugging</a></h2>\n\n<p>WordPress has constants defined in <code>wp-config.php</code> where you can print errors to the screen and log them in a separate file located <code>/wp-content/debug.log</code>. It looks like this:</p>\n\n<pre><code>define( 'WP_DEBUG', true );\ndefine( 'WP_DEBUG_DISPLAY', true );\ndefine( 'WP_DEBUG_LOG', true );\n</code></pre>\n\n<p>You can then print your own information to the debug log at specific point and find out exactly where ( or if the function is even getting hit at all ) the function is erroring out:</p>\n\n<pre><code>function write_here_featured_image_upload() {\n error_log( 'Made it into the Ajax function safe and sound!' );\n /** ... Rest of your code ... **/\n}\n</code></pre>\n\n<h2>Check Dev Tools Console</h2>\n\n<p>Almost all browsers in this modern day have <a href=\"https://developer.mozilla.org/en-US/Learn/Discover_browser_developer_tools\" rel=\"noreferrer\">Developer Tools</a> and a <a href=\"https://codex.wordpress.org/Using_Your_Browser_to_Diagnose_JavaScript_Errors#Step_3:_Diagnosis\" rel=\"noreferrer\">Console</a> where Javascrpit errors are output to. If you see an error in your Dev Tools console you'll need to fix that first and foremost.</p>\n\n<hr>\n\n<p>As for a possible solution, you have this conditional which is preventing you from running ajax on the front-end of the website:</p>\n\n<pre><code>if ( is_admin() ) {\n add_action( 'wp_ajax_write_here_img_upload', 'write_here_featured_image_upload' );\n add_action( 'wp_ajax_nopriv_write_here_img_upload', 'write_here_featured_image_upload' );\n}\n</code></pre>\n\n<p>The function <a href=\"https://codex.wordpress.org/Function_Reference/is_admin\" rel=\"noreferrer\"><code>is_admin()</code></a> tells WordPress to <strong>only</strong> run those actions whenever in the Admin Panel / Dashboard so you would never see anything happen on the front-end of your website. Try removing the conditional and just adding the action as is:</p>\n\n<pre><code>add_action( 'wp_ajax_write_here_img_upload', 'write_here_featured_image_upload' );\nadd_action( 'wp_ajax_nopriv_write_here_img_upload', 'write_here_featured_image_upload' );\n</code></pre>\n" }, { "answer_id": 364243, "author": "Salvatore", "author_id": 186239, "author_profile": "https://wordpress.stackexchange.com/users/186239", "pm_score": 0, "selected": false, "text": "<p>Add this inside admin-ajax.php</p>\n\n<pre><code>ini_set('display_errors', 1); \nini_set('display_startup_errors', 1); \nerror_reporting(E_ALL);\n</code></pre>\n" } ]
2015/11/24
[ "https://wordpress.stackexchange.com/questions/209729", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74171/" ]
Trying to use `admin-ajax.php` to upload image from front-end form. I'm keep getting `0` with below code I have and not sure how to debug this or where it goes wrong. I have HTML input file ``` <input type="file" name="wh_image_upload" id="wh_image_upload" multiple="false" /> ``` and localized script for AJAX request ``` $img_nonce = wp_create_nonce('image_upload_nonce'); wp_localize_script( 'ajax-script', 'ajax_image', array( 'ajax_url' => admin_url( 'admin-ajax.php' )) ); ``` and PHP function ``` function write_here_featured_image_upload() { var_dump($_FILES); die(); } add_action( 'wp_ajax_write_here_img_upload', 'write_here_featured_image_upload' ); add_action( 'wp_ajax_nopriv_write_here_img_upload', 'write_here_featured_image_upload' ); ``` JS ``` // Featured image upload AJAX $("#wh_image_upload").change(function(){ var userFile = new FormData(); var fileInput = $( "#wh_image_upload" )[0].files[0]; //console.log(fileInput); userFile.append("file", fileInput); userFile.append("action", "write_here_img_upload"); $.ajax({ type: "POST", url: ajax_object.ajax_url, data: userFile, processData: false, contentType: false, error: function(jqXHR, textStatus, errorMessage) { console.log(errorMessage); }, success: function(data) { console.log("Image Uploaded! " + data); } }); }); ``` I get a AJAX success message with response `0`. `Image Uploaded! 0` **Update** I updated my working code.
[Enable Debugging](https://codex.wordpress.org/Debugging_in_WordPress) ---------------------------------------------------------------------- WordPress has constants defined in `wp-config.php` where you can print errors to the screen and log them in a separate file located `/wp-content/debug.log`. It looks like this: ``` define( 'WP_DEBUG', true ); define( 'WP_DEBUG_DISPLAY', true ); define( 'WP_DEBUG_LOG', true ); ``` You can then print your own information to the debug log at specific point and find out exactly where ( or if the function is even getting hit at all ) the function is erroring out: ``` function write_here_featured_image_upload() { error_log( 'Made it into the Ajax function safe and sound!' ); /** ... Rest of your code ... **/ } ``` Check Dev Tools Console ----------------------- Almost all browsers in this modern day have [Developer Tools](https://developer.mozilla.org/en-US/Learn/Discover_browser_developer_tools) and a [Console](https://codex.wordpress.org/Using_Your_Browser_to_Diagnose_JavaScript_Errors#Step_3:_Diagnosis) where Javascrpit errors are output to. If you see an error in your Dev Tools console you'll need to fix that first and foremost. --- As for a possible solution, you have this conditional which is preventing you from running ajax on the front-end of the website: ``` if ( is_admin() ) { add_action( 'wp_ajax_write_here_img_upload', 'write_here_featured_image_upload' ); add_action( 'wp_ajax_nopriv_write_here_img_upload', 'write_here_featured_image_upload' ); } ``` The function [`is_admin()`](https://codex.wordpress.org/Function_Reference/is_admin) tells WordPress to **only** run those actions whenever in the Admin Panel / Dashboard so you would never see anything happen on the front-end of your website. Try removing the conditional and just adding the action as is: ``` add_action( 'wp_ajax_write_here_img_upload', 'write_here_featured_image_upload' ); add_action( 'wp_ajax_nopriv_write_here_img_upload', 'write_here_featured_image_upload' ); ```
209,743
<p>Hypothetical example but real world applicability (for someone learning, like me).</p> <p>Given this code:</p> <pre><code>&lt;?php function send_money_to_grandma() { internetofThings("send grandma","$1"); } add_action('init','send_money_to_grandma'); add_action('init','send_money_to_grandma'); </code></pre> <p>ok, now I bring up my WP site and log in. I traverse a few pages in Admin. The action 'init' fires a total of <strong>100 times</strong> before my laptop battery dies.</p> <p><strong>First questions:</strong> How much money did we send to grandma? Is it $1, $2, $100 or $200 (or something else?)</p> <p>If you could also explain your answer that would be awesome.</p> <p><strong>Second questions:</strong> If we want to make sure we only send grandma $1, what's the best way to do that? Global variable (semaphore) that gets set 'true' the first time we send $1? Or is there some other test to see if an action happened already and prevent it from firing multiple times?</p> <p><strong>Third question:</strong> Is this something that plugin developers worry about? I realize my example is silly but I was thinking of both performance issues and other unexpected side effects (e.g. if the function updates/inserts to the database).</p>
[ { "answer_id": 209751, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 2, "selected": false, "text": "<p>You can't add the <strong>same action</strong> to the <strong>same action hook</strong>, with the <strong>same priority</strong>.</p>\n\n<p>This is done to prevent multiple plugins relying on a third party plugins' action to happen more than once (think woocommerce and all it's third party plugins, like gateway payment integrations, etc). \nSo without specifying priority, Grandma remains poor:</p>\n\n<pre><code>add_action('init','print_a_buck');\nadd_action('init','print_a_buck');\n\nfunction print_a_buck() {\n echo '$1&lt;/br&gt;';\n}\nadd_action('wp', 'die_hard');\nfunction die_hard() {\n die('hard');\n}\n</code></pre>\n\n<p>However, if you add priority to those actions: </p>\n\n<pre><code>add_action('init','print_a_buck', 1);\nadd_action('init','print_a_buck', 2);\nadd_action('init','print_a_buck', 3);\n</code></pre>\n\n<p>Grandma now dies with $4 in her pocket (1, 2, 3 and the default: 10).</p>\n" }, { "answer_id": 209753, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 5, "selected": true, "text": "<p>Here are some random thoughts on this:</p>\n\n<h2>Question #1</h2>\n\n<blockquote>\n <p>How much money did we send to grandma?</p>\n</blockquote>\n\n<p>For 100 page loads, we sent her 100 x $1 = $100.</p>\n\n<p><em>Here we actually mean <code>100 x do_action( 'init' )</code> calls.</em> </p>\n\n<p>It didn't matter that we added it twice with:</p>\n\n<pre><code>add_action( 'init','send_money_to_grandma' );\nadd_action( 'init','send_money_to_grandma' );\n</code></pre>\n\n<p>because the <em>callbacks</em> and <em>priorities</em> (default 10) are <strong>identical</strong>.</p>\n\n<p>We can check how the <code>add_action</code> is just a wrapper for <code>add_filter</code> that constructs the global <code>$wp_filter</code> array:</p>\n\n<pre><code>function add_filter( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) {\n global $wp_filter, $merged_filters;\n\n $idx = _wp_filter_build_unique_id($tag, $function_to_add, $priority);\n $wp_filter[$tag][$priority][$idx] = array(\n 'function' =&gt; $function_to_add, \n 'accepted_args' =&gt; $accepted_args\n );\n unset( $merged_filters[ $tag ] );\n return true;\n}\n</code></pre>\n\n<p>If we did however change the priority:</p>\n\n<pre><code>add_action( 'init','send_money_to_grandma', 9 );\nadd_action( 'init','send_money_to_grandma', 10 );\n</code></pre>\n\n<p>then we would send her 2 x $1 per page load or $200 for 100 page loads.</p>\n\n<p>Same if the callbacks where different:</p>\n\n<pre><code>add_action( 'init','send_money_to_grandma_1_dollar' );\nadd_action( 'init','send_money_to_grandma_also_1_dollar' );\n</code></pre>\n\n<h2>Question #2</h2>\n\n<blockquote>\n <p>If we want to make sure we only send grandma $1</p>\n</blockquote>\n\n<p>If we only want to send it <em>once per page load</em>, then this should do it:</p>\n\n<pre><code>add_action( 'init','send_money_to_grandma' );\n</code></pre>\n\n<p>because the <code>init</code> hook is only fired once. We might have other hooks that fires up many times per page load.</p>\n\n<p>Let's call:</p>\n\n<pre><code>add_action( 'someaction ','send_money_to_grandma' );\n</code></pre>\n\n<p>but what happens if <code>someaction</code> fires 10 times per page load?</p>\n\n<p>We could adjust the <code>send_money_to_grandma()</code> function with</p>\n\n<pre><code>function send_money_to_grandma() \n{\n if( ! did_action( 'someaction' ) )\n internetofThings(\"send grandma\",\"$1\");\n}\n</code></pre>\n\n<p>or use a <em>static</em> variable as a counter:</p>\n\n<pre><code>function send_money_to_grandma() \n{\n static $counter = 0;\n if( 0 === $counter++ )\n internetofThings(\"send grandma\",\"$1\");\n}\n</code></pre>\n\n<p>If we only want to run it once (ever!), then we might register an option in the <code>wp_options</code> table via the <a href=\"https://codex.wordpress.org/Options_API\">Options API</a>:</p>\n\n<pre><code>function send_money_to_grandma() \n{\n if( 'no' === get_option( 'sent_grandma_money', 'no' ) )\n {\n update_option( 'sent_grandma_money', 'yes' );\n internetofThings( \"send grandma\",\"$1\" );\n }\n}\n</code></pre>\n\n<p>If we want to send her money once every day, then we can use the <a href=\"https://codex.wordpress.org/Transients_API\">Transient API</a></p>\n\n<pre><code>function send_money_to_grandma() \n{\n if ( false === get_transient( 'sent_grandma_money' ) ) )\n {\n internetofThings( \"send grandma\",\"$1\" );\n set_transient( 'sent_grandma_money', 'yes', DAY_IN_SECONDS );\n }\n}\n</code></pre>\n\n<p>or even use the wp-cron. </p>\n\n<p>Note that you might have ajax calls. as well.</p>\n\n<p>There are ways to check for those, e.g. with <code>DOING_AJAX</code></p>\n\n<p>There might also be redirections, that could interrupt the flow.</p>\n\n<p>Then we might want to restrict to the backend only, <code>is_admin()</code> or not: <code>! is_admin()</code>.</p>\n\n<h2>Question #3</h2>\n\n<blockquote>\n <p>Is this something that plugin developers worry about?</p>\n</blockquote>\n\n<p>yes this is important.</p>\n\n<p>If we want to make our grandma very happy we would do:</p>\n\n<pre><code>add_action( 'all','send_money_to_grandma' );\n</code></pre>\n\n<p>but this would be very bad for performance ... and our wallet ;-)</p>\n" }, { "answer_id": 209829, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 3, "selected": false, "text": "<p>This is more a comment to the very good <a href=\"https://wordpress.stackexchange.com/a/209753/35541\">Birgire's answer</a> than a complete answer, but having to write code, comments don't fit.</p>\n\n<p>From the answer it may seems that the only reason why action is added once in OP sample code, even if <code>add_action()</code> is called twice, is the fact that the same priority is used. That's not true.</p>\n\n<p>In the code of <code>add_filter</code> an important part is <a href=\"https://developer.wordpress.org/reference/functions/_wp_filter_build_unique_id/\" rel=\"nofollow noreferrer\"><code>_wp_filter_build_unique_id()</code></a> function call, that creates an unique id per <em>callback</em>.</p>\n\n<p>If you use a simple variable, like a string that holds a function name, e.g. <code>\"send_money_to_grandma\"</code>, then the id will be equal to the string itself, so if priority is the same, being id the same as well, the callback is added once.</p>\n\n<p>However, things are not always simple like that. Callbacks may be anything that is <code>callable</code> in PHP:</p>\n\n<ul>\n<li>function names</li>\n<li>static class methods</li>\n<li>dynamic class methods</li>\n<li>invokable objects</li>\n<li>closures (anonymous functions)</li>\n</ul>\n\n<p>The first two are represented, respectively, by a string and an array of 2 strings (<code>'send_money_to_grandma'</code> and <code>array('MoneySender', 'send_to_grandma')</code>) so the id is always the same, and you can be sure that callback is added once if priority is the same.</p>\n\n<p>In all the other 3 cases, the id depends on object instances (an anonymous function is an object in PHP) so the callback is added once only if the object is the same <em>instance</em>, and it is important to note that <em>same instance</em> and <em>same class</em> are two different things.</p>\n\n<p>Take this example:</p>\n\n<pre><code>class MoneySender {\n\n public function sent_to_grandma( $amount = 1 ) {\n // things happen here\n }\n\n}\n\n$sender1 = new MoneySender();\n$sender2 = new MoneySender();\n\nadd_action( 'init', array( $sender1, 'sent_to_grandma' ) );\nadd_action( 'init', array( $sender1, 'sent_to_grandma' ) );\nadd_action( 'init', array( $sender2, 'sent_to_grandma' ) );\n</code></pre>\n\n<p>How many dollars are we sending per page load?</p>\n\n<p>Answer is 2, because the id WordPress generates for <code>$sender1</code> and <code>$sender2</code> are different.</p>\n\n<p>The same happen in this case:</p>\n\n<pre><code>add_action( 'init', function() {\n sent_to_grandma();\n} );\n\nadd_action( 'init', function() {\n sent_to_grandma();\n} );\n</code></pre>\n\n<p>Above I used the function <code>sent_to_grandma</code> inside closures, and even if the code is identical, the 2 closures are 2 different instance of <code>\\Closure</code> object, so WP will create 2 different ids, which will cause the action be added twice, even if priority is the same.</p>\n" } ]
2015/11/24
[ "https://wordpress.stackexchange.com/questions/209743", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83299/" ]
Hypothetical example but real world applicability (for someone learning, like me). Given this code: ``` <?php function send_money_to_grandma() { internetofThings("send grandma","$1"); } add_action('init','send_money_to_grandma'); add_action('init','send_money_to_grandma'); ``` ok, now I bring up my WP site and log in. I traverse a few pages in Admin. The action 'init' fires a total of **100 times** before my laptop battery dies. **First questions:** How much money did we send to grandma? Is it $1, $2, $100 or $200 (or something else?) If you could also explain your answer that would be awesome. **Second questions:** If we want to make sure we only send grandma $1, what's the best way to do that? Global variable (semaphore) that gets set 'true' the first time we send $1? Or is there some other test to see if an action happened already and prevent it from firing multiple times? **Third question:** Is this something that plugin developers worry about? I realize my example is silly but I was thinking of both performance issues and other unexpected side effects (e.g. if the function updates/inserts to the database).
Here are some random thoughts on this: Question #1 ----------- > > How much money did we send to grandma? > > > For 100 page loads, we sent her 100 x $1 = $100. *Here we actually mean `100 x do_action( 'init' )` calls.* It didn't matter that we added it twice with: ``` add_action( 'init','send_money_to_grandma' ); add_action( 'init','send_money_to_grandma' ); ``` because the *callbacks* and *priorities* (default 10) are **identical**. We can check how the `add_action` is just a wrapper for `add_filter` that constructs the global `$wp_filter` array: ``` function add_filter( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) { global $wp_filter, $merged_filters; $idx = _wp_filter_build_unique_id($tag, $function_to_add, $priority); $wp_filter[$tag][$priority][$idx] = array( 'function' => $function_to_add, 'accepted_args' => $accepted_args ); unset( $merged_filters[ $tag ] ); return true; } ``` If we did however change the priority: ``` add_action( 'init','send_money_to_grandma', 9 ); add_action( 'init','send_money_to_grandma', 10 ); ``` then we would send her 2 x $1 per page load or $200 for 100 page loads. Same if the callbacks where different: ``` add_action( 'init','send_money_to_grandma_1_dollar' ); add_action( 'init','send_money_to_grandma_also_1_dollar' ); ``` Question #2 ----------- > > If we want to make sure we only send grandma $1 > > > If we only want to send it *once per page load*, then this should do it: ``` add_action( 'init','send_money_to_grandma' ); ``` because the `init` hook is only fired once. We might have other hooks that fires up many times per page load. Let's call: ``` add_action( 'someaction ','send_money_to_grandma' ); ``` but what happens if `someaction` fires 10 times per page load? We could adjust the `send_money_to_grandma()` function with ``` function send_money_to_grandma() { if( ! did_action( 'someaction' ) ) internetofThings("send grandma","$1"); } ``` or use a *static* variable as a counter: ``` function send_money_to_grandma() { static $counter = 0; if( 0 === $counter++ ) internetofThings("send grandma","$1"); } ``` If we only want to run it once (ever!), then we might register an option in the `wp_options` table via the [Options API](https://codex.wordpress.org/Options_API): ``` function send_money_to_grandma() { if( 'no' === get_option( 'sent_grandma_money', 'no' ) ) { update_option( 'sent_grandma_money', 'yes' ); internetofThings( "send grandma","$1" ); } } ``` If we want to send her money once every day, then we can use the [Transient API](https://codex.wordpress.org/Transients_API) ``` function send_money_to_grandma() { if ( false === get_transient( 'sent_grandma_money' ) ) ) { internetofThings( "send grandma","$1" ); set_transient( 'sent_grandma_money', 'yes', DAY_IN_SECONDS ); } } ``` or even use the wp-cron. Note that you might have ajax calls. as well. There are ways to check for those, e.g. with `DOING_AJAX` There might also be redirections, that could interrupt the flow. Then we might want to restrict to the backend only, `is_admin()` or not: `! is_admin()`. Question #3 ----------- > > Is this something that plugin developers worry about? > > > yes this is important. If we want to make our grandma very happy we would do: ``` add_action( 'all','send_money_to_grandma' ); ``` but this would be very bad for performance ... and our wallet ;-)
209,768
<p>We can easily asses a user's role using <code>current_user_can()</code>, but it doesn't support an array of user roles but a single role. So we have to check each of the role multiple times:</p> <pre><code>if( current_user_can('administrator') || current_user_can('editor') ) { //do this } </code></pre> <p>I'm making a WordPress Plugin, I need the administrator should choose the minimum privilege to administer the plugin. If the roles are hierarchical then they are like so (for single site):</p> <ul> <li>Administrator</li> <li>Editor</li> <li>Author</li> <li>Contributor</li> <li>Subscriber</li> </ul> <p>If the admin choose author, then I have to do 3 OR checks as shown above (<em>if x || y || z</em>).</p> <p>Is there any smart way I can choose for this purpose so that I can let them choose the minimum privilege but I can handle it smartly too.</p> <p>Thank you.</p>
[ { "answer_id": 209751, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 2, "selected": false, "text": "<p>You can't add the <strong>same action</strong> to the <strong>same action hook</strong>, with the <strong>same priority</strong>.</p>\n\n<p>This is done to prevent multiple plugins relying on a third party plugins' action to happen more than once (think woocommerce and all it's third party plugins, like gateway payment integrations, etc). \nSo without specifying priority, Grandma remains poor:</p>\n\n<pre><code>add_action('init','print_a_buck');\nadd_action('init','print_a_buck');\n\nfunction print_a_buck() {\n echo '$1&lt;/br&gt;';\n}\nadd_action('wp', 'die_hard');\nfunction die_hard() {\n die('hard');\n}\n</code></pre>\n\n<p>However, if you add priority to those actions: </p>\n\n<pre><code>add_action('init','print_a_buck', 1);\nadd_action('init','print_a_buck', 2);\nadd_action('init','print_a_buck', 3);\n</code></pre>\n\n<p>Grandma now dies with $4 in her pocket (1, 2, 3 and the default: 10).</p>\n" }, { "answer_id": 209753, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 5, "selected": true, "text": "<p>Here are some random thoughts on this:</p>\n\n<h2>Question #1</h2>\n\n<blockquote>\n <p>How much money did we send to grandma?</p>\n</blockquote>\n\n<p>For 100 page loads, we sent her 100 x $1 = $100.</p>\n\n<p><em>Here we actually mean <code>100 x do_action( 'init' )</code> calls.</em> </p>\n\n<p>It didn't matter that we added it twice with:</p>\n\n<pre><code>add_action( 'init','send_money_to_grandma' );\nadd_action( 'init','send_money_to_grandma' );\n</code></pre>\n\n<p>because the <em>callbacks</em> and <em>priorities</em> (default 10) are <strong>identical</strong>.</p>\n\n<p>We can check how the <code>add_action</code> is just a wrapper for <code>add_filter</code> that constructs the global <code>$wp_filter</code> array:</p>\n\n<pre><code>function add_filter( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) {\n global $wp_filter, $merged_filters;\n\n $idx = _wp_filter_build_unique_id($tag, $function_to_add, $priority);\n $wp_filter[$tag][$priority][$idx] = array(\n 'function' =&gt; $function_to_add, \n 'accepted_args' =&gt; $accepted_args\n );\n unset( $merged_filters[ $tag ] );\n return true;\n}\n</code></pre>\n\n<p>If we did however change the priority:</p>\n\n<pre><code>add_action( 'init','send_money_to_grandma', 9 );\nadd_action( 'init','send_money_to_grandma', 10 );\n</code></pre>\n\n<p>then we would send her 2 x $1 per page load or $200 for 100 page loads.</p>\n\n<p>Same if the callbacks where different:</p>\n\n<pre><code>add_action( 'init','send_money_to_grandma_1_dollar' );\nadd_action( 'init','send_money_to_grandma_also_1_dollar' );\n</code></pre>\n\n<h2>Question #2</h2>\n\n<blockquote>\n <p>If we want to make sure we only send grandma $1</p>\n</blockquote>\n\n<p>If we only want to send it <em>once per page load</em>, then this should do it:</p>\n\n<pre><code>add_action( 'init','send_money_to_grandma' );\n</code></pre>\n\n<p>because the <code>init</code> hook is only fired once. We might have other hooks that fires up many times per page load.</p>\n\n<p>Let's call:</p>\n\n<pre><code>add_action( 'someaction ','send_money_to_grandma' );\n</code></pre>\n\n<p>but what happens if <code>someaction</code> fires 10 times per page load?</p>\n\n<p>We could adjust the <code>send_money_to_grandma()</code> function with</p>\n\n<pre><code>function send_money_to_grandma() \n{\n if( ! did_action( 'someaction' ) )\n internetofThings(\"send grandma\",\"$1\");\n}\n</code></pre>\n\n<p>or use a <em>static</em> variable as a counter:</p>\n\n<pre><code>function send_money_to_grandma() \n{\n static $counter = 0;\n if( 0 === $counter++ )\n internetofThings(\"send grandma\",\"$1\");\n}\n</code></pre>\n\n<p>If we only want to run it once (ever!), then we might register an option in the <code>wp_options</code> table via the <a href=\"https://codex.wordpress.org/Options_API\">Options API</a>:</p>\n\n<pre><code>function send_money_to_grandma() \n{\n if( 'no' === get_option( 'sent_grandma_money', 'no' ) )\n {\n update_option( 'sent_grandma_money', 'yes' );\n internetofThings( \"send grandma\",\"$1\" );\n }\n}\n</code></pre>\n\n<p>If we want to send her money once every day, then we can use the <a href=\"https://codex.wordpress.org/Transients_API\">Transient API</a></p>\n\n<pre><code>function send_money_to_grandma() \n{\n if ( false === get_transient( 'sent_grandma_money' ) ) )\n {\n internetofThings( \"send grandma\",\"$1\" );\n set_transient( 'sent_grandma_money', 'yes', DAY_IN_SECONDS );\n }\n}\n</code></pre>\n\n<p>or even use the wp-cron. </p>\n\n<p>Note that you might have ajax calls. as well.</p>\n\n<p>There are ways to check for those, e.g. with <code>DOING_AJAX</code></p>\n\n<p>There might also be redirections, that could interrupt the flow.</p>\n\n<p>Then we might want to restrict to the backend only, <code>is_admin()</code> or not: <code>! is_admin()</code>.</p>\n\n<h2>Question #3</h2>\n\n<blockquote>\n <p>Is this something that plugin developers worry about?</p>\n</blockquote>\n\n<p>yes this is important.</p>\n\n<p>If we want to make our grandma very happy we would do:</p>\n\n<pre><code>add_action( 'all','send_money_to_grandma' );\n</code></pre>\n\n<p>but this would be very bad for performance ... and our wallet ;-)</p>\n" }, { "answer_id": 209829, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 3, "selected": false, "text": "<p>This is more a comment to the very good <a href=\"https://wordpress.stackexchange.com/a/209753/35541\">Birgire's answer</a> than a complete answer, but having to write code, comments don't fit.</p>\n\n<p>From the answer it may seems that the only reason why action is added once in OP sample code, even if <code>add_action()</code> is called twice, is the fact that the same priority is used. That's not true.</p>\n\n<p>In the code of <code>add_filter</code> an important part is <a href=\"https://developer.wordpress.org/reference/functions/_wp_filter_build_unique_id/\" rel=\"nofollow noreferrer\"><code>_wp_filter_build_unique_id()</code></a> function call, that creates an unique id per <em>callback</em>.</p>\n\n<p>If you use a simple variable, like a string that holds a function name, e.g. <code>\"send_money_to_grandma\"</code>, then the id will be equal to the string itself, so if priority is the same, being id the same as well, the callback is added once.</p>\n\n<p>However, things are not always simple like that. Callbacks may be anything that is <code>callable</code> in PHP:</p>\n\n<ul>\n<li>function names</li>\n<li>static class methods</li>\n<li>dynamic class methods</li>\n<li>invokable objects</li>\n<li>closures (anonymous functions)</li>\n</ul>\n\n<p>The first two are represented, respectively, by a string and an array of 2 strings (<code>'send_money_to_grandma'</code> and <code>array('MoneySender', 'send_to_grandma')</code>) so the id is always the same, and you can be sure that callback is added once if priority is the same.</p>\n\n<p>In all the other 3 cases, the id depends on object instances (an anonymous function is an object in PHP) so the callback is added once only if the object is the same <em>instance</em>, and it is important to note that <em>same instance</em> and <em>same class</em> are two different things.</p>\n\n<p>Take this example:</p>\n\n<pre><code>class MoneySender {\n\n public function sent_to_grandma( $amount = 1 ) {\n // things happen here\n }\n\n}\n\n$sender1 = new MoneySender();\n$sender2 = new MoneySender();\n\nadd_action( 'init', array( $sender1, 'sent_to_grandma' ) );\nadd_action( 'init', array( $sender1, 'sent_to_grandma' ) );\nadd_action( 'init', array( $sender2, 'sent_to_grandma' ) );\n</code></pre>\n\n<p>How many dollars are we sending per page load?</p>\n\n<p>Answer is 2, because the id WordPress generates for <code>$sender1</code> and <code>$sender2</code> are different.</p>\n\n<p>The same happen in this case:</p>\n\n<pre><code>add_action( 'init', function() {\n sent_to_grandma();\n} );\n\nadd_action( 'init', function() {\n sent_to_grandma();\n} );\n</code></pre>\n\n<p>Above I used the function <code>sent_to_grandma</code> inside closures, and even if the code is identical, the 2 closures are 2 different instance of <code>\\Closure</code> object, so WP will create 2 different ids, which will cause the action be added twice, even if priority is the same.</p>\n" } ]
2015/11/25
[ "https://wordpress.stackexchange.com/questions/209768", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84224/" ]
We can easily asses a user's role using `current_user_can()`, but it doesn't support an array of user roles but a single role. So we have to check each of the role multiple times: ``` if( current_user_can('administrator') || current_user_can('editor') ) { //do this } ``` I'm making a WordPress Plugin, I need the administrator should choose the minimum privilege to administer the plugin. If the roles are hierarchical then they are like so (for single site): * Administrator * Editor * Author * Contributor * Subscriber If the admin choose author, then I have to do 3 OR checks as shown above (*if x || y || z*). Is there any smart way I can choose for this purpose so that I can let them choose the minimum privilege but I can handle it smartly too. Thank you.
Here are some random thoughts on this: Question #1 ----------- > > How much money did we send to grandma? > > > For 100 page loads, we sent her 100 x $1 = $100. *Here we actually mean `100 x do_action( 'init' )` calls.* It didn't matter that we added it twice with: ``` add_action( 'init','send_money_to_grandma' ); add_action( 'init','send_money_to_grandma' ); ``` because the *callbacks* and *priorities* (default 10) are **identical**. We can check how the `add_action` is just a wrapper for `add_filter` that constructs the global `$wp_filter` array: ``` function add_filter( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) { global $wp_filter, $merged_filters; $idx = _wp_filter_build_unique_id($tag, $function_to_add, $priority); $wp_filter[$tag][$priority][$idx] = array( 'function' => $function_to_add, 'accepted_args' => $accepted_args ); unset( $merged_filters[ $tag ] ); return true; } ``` If we did however change the priority: ``` add_action( 'init','send_money_to_grandma', 9 ); add_action( 'init','send_money_to_grandma', 10 ); ``` then we would send her 2 x $1 per page load or $200 for 100 page loads. Same if the callbacks where different: ``` add_action( 'init','send_money_to_grandma_1_dollar' ); add_action( 'init','send_money_to_grandma_also_1_dollar' ); ``` Question #2 ----------- > > If we want to make sure we only send grandma $1 > > > If we only want to send it *once per page load*, then this should do it: ``` add_action( 'init','send_money_to_grandma' ); ``` because the `init` hook is only fired once. We might have other hooks that fires up many times per page load. Let's call: ``` add_action( 'someaction ','send_money_to_grandma' ); ``` but what happens if `someaction` fires 10 times per page load? We could adjust the `send_money_to_grandma()` function with ``` function send_money_to_grandma() { if( ! did_action( 'someaction' ) ) internetofThings("send grandma","$1"); } ``` or use a *static* variable as a counter: ``` function send_money_to_grandma() { static $counter = 0; if( 0 === $counter++ ) internetofThings("send grandma","$1"); } ``` If we only want to run it once (ever!), then we might register an option in the `wp_options` table via the [Options API](https://codex.wordpress.org/Options_API): ``` function send_money_to_grandma() { if( 'no' === get_option( 'sent_grandma_money', 'no' ) ) { update_option( 'sent_grandma_money', 'yes' ); internetofThings( "send grandma","$1" ); } } ``` If we want to send her money once every day, then we can use the [Transient API](https://codex.wordpress.org/Transients_API) ``` function send_money_to_grandma() { if ( false === get_transient( 'sent_grandma_money' ) ) ) { internetofThings( "send grandma","$1" ); set_transient( 'sent_grandma_money', 'yes', DAY_IN_SECONDS ); } } ``` or even use the wp-cron. Note that you might have ajax calls. as well. There are ways to check for those, e.g. with `DOING_AJAX` There might also be redirections, that could interrupt the flow. Then we might want to restrict to the backend only, `is_admin()` or not: `! is_admin()`. Question #3 ----------- > > Is this something that plugin developers worry about? > > > yes this is important. If we want to make our grandma very happy we would do: ``` add_action( 'all','send_money_to_grandma' ); ``` but this would be very bad for performance ... and our wallet ;-)
209,770
<p>Here's a very simple plugin, which I drop into mu_plugins in my multisite installation:</p> <pre><code>&lt;?php /* Plugin Name: Test */ class myclass { function __construct() { error_log("I just punched myself in the head."); } } // end of class definition /* start of plugin functions */ function run_plugin() { static $counter = 0; if (0 === $counter++) $i = new myclass(); } /* start of execution code */ add_action('init','run_plugin'); </code></pre> <p>OK - I log into WP admin, and I switch pages twice -- go to media library then themes. Counting the first landing on index.php there are three page renderings total.</p> <p>Output of this plugin:</p> <pre><code>I just punched myself in the head. I just punched myself in the head. I just punched myself in the head. </code></pre> <p>So, given the static counter in the calling function - why is the constructor getting called three times? Or, is WP destroying my plugin and reloading it with every page load?</p> <p>I'm very confused.</p>
[ { "answer_id": 209751, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 2, "selected": false, "text": "<p>You can't add the <strong>same action</strong> to the <strong>same action hook</strong>, with the <strong>same priority</strong>.</p>\n\n<p>This is done to prevent multiple plugins relying on a third party plugins' action to happen more than once (think woocommerce and all it's third party plugins, like gateway payment integrations, etc). \nSo without specifying priority, Grandma remains poor:</p>\n\n<pre><code>add_action('init','print_a_buck');\nadd_action('init','print_a_buck');\n\nfunction print_a_buck() {\n echo '$1&lt;/br&gt;';\n}\nadd_action('wp', 'die_hard');\nfunction die_hard() {\n die('hard');\n}\n</code></pre>\n\n<p>However, if you add priority to those actions: </p>\n\n<pre><code>add_action('init','print_a_buck', 1);\nadd_action('init','print_a_buck', 2);\nadd_action('init','print_a_buck', 3);\n</code></pre>\n\n<p>Grandma now dies with $4 in her pocket (1, 2, 3 and the default: 10).</p>\n" }, { "answer_id": 209753, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 5, "selected": true, "text": "<p>Here are some random thoughts on this:</p>\n\n<h2>Question #1</h2>\n\n<blockquote>\n <p>How much money did we send to grandma?</p>\n</blockquote>\n\n<p>For 100 page loads, we sent her 100 x $1 = $100.</p>\n\n<p><em>Here we actually mean <code>100 x do_action( 'init' )</code> calls.</em> </p>\n\n<p>It didn't matter that we added it twice with:</p>\n\n<pre><code>add_action( 'init','send_money_to_grandma' );\nadd_action( 'init','send_money_to_grandma' );\n</code></pre>\n\n<p>because the <em>callbacks</em> and <em>priorities</em> (default 10) are <strong>identical</strong>.</p>\n\n<p>We can check how the <code>add_action</code> is just a wrapper for <code>add_filter</code> that constructs the global <code>$wp_filter</code> array:</p>\n\n<pre><code>function add_filter( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) {\n global $wp_filter, $merged_filters;\n\n $idx = _wp_filter_build_unique_id($tag, $function_to_add, $priority);\n $wp_filter[$tag][$priority][$idx] = array(\n 'function' =&gt; $function_to_add, \n 'accepted_args' =&gt; $accepted_args\n );\n unset( $merged_filters[ $tag ] );\n return true;\n}\n</code></pre>\n\n<p>If we did however change the priority:</p>\n\n<pre><code>add_action( 'init','send_money_to_grandma', 9 );\nadd_action( 'init','send_money_to_grandma', 10 );\n</code></pre>\n\n<p>then we would send her 2 x $1 per page load or $200 for 100 page loads.</p>\n\n<p>Same if the callbacks where different:</p>\n\n<pre><code>add_action( 'init','send_money_to_grandma_1_dollar' );\nadd_action( 'init','send_money_to_grandma_also_1_dollar' );\n</code></pre>\n\n<h2>Question #2</h2>\n\n<blockquote>\n <p>If we want to make sure we only send grandma $1</p>\n</blockquote>\n\n<p>If we only want to send it <em>once per page load</em>, then this should do it:</p>\n\n<pre><code>add_action( 'init','send_money_to_grandma' );\n</code></pre>\n\n<p>because the <code>init</code> hook is only fired once. We might have other hooks that fires up many times per page load.</p>\n\n<p>Let's call:</p>\n\n<pre><code>add_action( 'someaction ','send_money_to_grandma' );\n</code></pre>\n\n<p>but what happens if <code>someaction</code> fires 10 times per page load?</p>\n\n<p>We could adjust the <code>send_money_to_grandma()</code> function with</p>\n\n<pre><code>function send_money_to_grandma() \n{\n if( ! did_action( 'someaction' ) )\n internetofThings(\"send grandma\",\"$1\");\n}\n</code></pre>\n\n<p>or use a <em>static</em> variable as a counter:</p>\n\n<pre><code>function send_money_to_grandma() \n{\n static $counter = 0;\n if( 0 === $counter++ )\n internetofThings(\"send grandma\",\"$1\");\n}\n</code></pre>\n\n<p>If we only want to run it once (ever!), then we might register an option in the <code>wp_options</code> table via the <a href=\"https://codex.wordpress.org/Options_API\">Options API</a>:</p>\n\n<pre><code>function send_money_to_grandma() \n{\n if( 'no' === get_option( 'sent_grandma_money', 'no' ) )\n {\n update_option( 'sent_grandma_money', 'yes' );\n internetofThings( \"send grandma\",\"$1\" );\n }\n}\n</code></pre>\n\n<p>If we want to send her money once every day, then we can use the <a href=\"https://codex.wordpress.org/Transients_API\">Transient API</a></p>\n\n<pre><code>function send_money_to_grandma() \n{\n if ( false === get_transient( 'sent_grandma_money' ) ) )\n {\n internetofThings( \"send grandma\",\"$1\" );\n set_transient( 'sent_grandma_money', 'yes', DAY_IN_SECONDS );\n }\n}\n</code></pre>\n\n<p>or even use the wp-cron. </p>\n\n<p>Note that you might have ajax calls. as well.</p>\n\n<p>There are ways to check for those, e.g. with <code>DOING_AJAX</code></p>\n\n<p>There might also be redirections, that could interrupt the flow.</p>\n\n<p>Then we might want to restrict to the backend only, <code>is_admin()</code> or not: <code>! is_admin()</code>.</p>\n\n<h2>Question #3</h2>\n\n<blockquote>\n <p>Is this something that plugin developers worry about?</p>\n</blockquote>\n\n<p>yes this is important.</p>\n\n<p>If we want to make our grandma very happy we would do:</p>\n\n<pre><code>add_action( 'all','send_money_to_grandma' );\n</code></pre>\n\n<p>but this would be very bad for performance ... and our wallet ;-)</p>\n" }, { "answer_id": 209829, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 3, "selected": false, "text": "<p>This is more a comment to the very good <a href=\"https://wordpress.stackexchange.com/a/209753/35541\">Birgire's answer</a> than a complete answer, but having to write code, comments don't fit.</p>\n\n<p>From the answer it may seems that the only reason why action is added once in OP sample code, even if <code>add_action()</code> is called twice, is the fact that the same priority is used. That's not true.</p>\n\n<p>In the code of <code>add_filter</code> an important part is <a href=\"https://developer.wordpress.org/reference/functions/_wp_filter_build_unique_id/\" rel=\"nofollow noreferrer\"><code>_wp_filter_build_unique_id()</code></a> function call, that creates an unique id per <em>callback</em>.</p>\n\n<p>If you use a simple variable, like a string that holds a function name, e.g. <code>\"send_money_to_grandma\"</code>, then the id will be equal to the string itself, so if priority is the same, being id the same as well, the callback is added once.</p>\n\n<p>However, things are not always simple like that. Callbacks may be anything that is <code>callable</code> in PHP:</p>\n\n<ul>\n<li>function names</li>\n<li>static class methods</li>\n<li>dynamic class methods</li>\n<li>invokable objects</li>\n<li>closures (anonymous functions)</li>\n</ul>\n\n<p>The first two are represented, respectively, by a string and an array of 2 strings (<code>'send_money_to_grandma'</code> and <code>array('MoneySender', 'send_to_grandma')</code>) so the id is always the same, and you can be sure that callback is added once if priority is the same.</p>\n\n<p>In all the other 3 cases, the id depends on object instances (an anonymous function is an object in PHP) so the callback is added once only if the object is the same <em>instance</em>, and it is important to note that <em>same instance</em> and <em>same class</em> are two different things.</p>\n\n<p>Take this example:</p>\n\n<pre><code>class MoneySender {\n\n public function sent_to_grandma( $amount = 1 ) {\n // things happen here\n }\n\n}\n\n$sender1 = new MoneySender();\n$sender2 = new MoneySender();\n\nadd_action( 'init', array( $sender1, 'sent_to_grandma' ) );\nadd_action( 'init', array( $sender1, 'sent_to_grandma' ) );\nadd_action( 'init', array( $sender2, 'sent_to_grandma' ) );\n</code></pre>\n\n<p>How many dollars are we sending per page load?</p>\n\n<p>Answer is 2, because the id WordPress generates for <code>$sender1</code> and <code>$sender2</code> are different.</p>\n\n<p>The same happen in this case:</p>\n\n<pre><code>add_action( 'init', function() {\n sent_to_grandma();\n} );\n\nadd_action( 'init', function() {\n sent_to_grandma();\n} );\n</code></pre>\n\n<p>Above I used the function <code>sent_to_grandma</code> inside closures, and even if the code is identical, the 2 closures are 2 different instance of <code>\\Closure</code> object, so WP will create 2 different ids, which will cause the action be added twice, even if priority is the same.</p>\n" } ]
2015/11/25
[ "https://wordpress.stackexchange.com/questions/209770", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83299/" ]
Here's a very simple plugin, which I drop into mu\_plugins in my multisite installation: ``` <?php /* Plugin Name: Test */ class myclass { function __construct() { error_log("I just punched myself in the head."); } } // end of class definition /* start of plugin functions */ function run_plugin() { static $counter = 0; if (0 === $counter++) $i = new myclass(); } /* start of execution code */ add_action('init','run_plugin'); ``` OK - I log into WP admin, and I switch pages twice -- go to media library then themes. Counting the first landing on index.php there are three page renderings total. Output of this plugin: ``` I just punched myself in the head. I just punched myself in the head. I just punched myself in the head. ``` So, given the static counter in the calling function - why is the constructor getting called three times? Or, is WP destroying my plugin and reloading it with every page load? I'm very confused.
Here are some random thoughts on this: Question #1 ----------- > > How much money did we send to grandma? > > > For 100 page loads, we sent her 100 x $1 = $100. *Here we actually mean `100 x do_action( 'init' )` calls.* It didn't matter that we added it twice with: ``` add_action( 'init','send_money_to_grandma' ); add_action( 'init','send_money_to_grandma' ); ``` because the *callbacks* and *priorities* (default 10) are **identical**. We can check how the `add_action` is just a wrapper for `add_filter` that constructs the global `$wp_filter` array: ``` function add_filter( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) { global $wp_filter, $merged_filters; $idx = _wp_filter_build_unique_id($tag, $function_to_add, $priority); $wp_filter[$tag][$priority][$idx] = array( 'function' => $function_to_add, 'accepted_args' => $accepted_args ); unset( $merged_filters[ $tag ] ); return true; } ``` If we did however change the priority: ``` add_action( 'init','send_money_to_grandma', 9 ); add_action( 'init','send_money_to_grandma', 10 ); ``` then we would send her 2 x $1 per page load or $200 for 100 page loads. Same if the callbacks where different: ``` add_action( 'init','send_money_to_grandma_1_dollar' ); add_action( 'init','send_money_to_grandma_also_1_dollar' ); ``` Question #2 ----------- > > If we want to make sure we only send grandma $1 > > > If we only want to send it *once per page load*, then this should do it: ``` add_action( 'init','send_money_to_grandma' ); ``` because the `init` hook is only fired once. We might have other hooks that fires up many times per page load. Let's call: ``` add_action( 'someaction ','send_money_to_grandma' ); ``` but what happens if `someaction` fires 10 times per page load? We could adjust the `send_money_to_grandma()` function with ``` function send_money_to_grandma() { if( ! did_action( 'someaction' ) ) internetofThings("send grandma","$1"); } ``` or use a *static* variable as a counter: ``` function send_money_to_grandma() { static $counter = 0; if( 0 === $counter++ ) internetofThings("send grandma","$1"); } ``` If we only want to run it once (ever!), then we might register an option in the `wp_options` table via the [Options API](https://codex.wordpress.org/Options_API): ``` function send_money_to_grandma() { if( 'no' === get_option( 'sent_grandma_money', 'no' ) ) { update_option( 'sent_grandma_money', 'yes' ); internetofThings( "send grandma","$1" ); } } ``` If we want to send her money once every day, then we can use the [Transient API](https://codex.wordpress.org/Transients_API) ``` function send_money_to_grandma() { if ( false === get_transient( 'sent_grandma_money' ) ) ) { internetofThings( "send grandma","$1" ); set_transient( 'sent_grandma_money', 'yes', DAY_IN_SECONDS ); } } ``` or even use the wp-cron. Note that you might have ajax calls. as well. There are ways to check for those, e.g. with `DOING_AJAX` There might also be redirections, that could interrupt the flow. Then we might want to restrict to the backend only, `is_admin()` or not: `! is_admin()`. Question #3 ----------- > > Is this something that plugin developers worry about? > > > yes this is important. If we want to make our grandma very happy we would do: ``` add_action( 'all','send_money_to_grandma' ); ``` but this would be very bad for performance ... and our wallet ;-)
209,774
<p>I have a folder with name:</p> <pre><code>wordpress_install/dev/abc </code></pre> <p>Now, I have created a index.php in abc folder and I want all the urls like:</p> <pre><code>wordpress_install/dev/abc/asdfasdfsdf (a 404 page) </code></pre> <p>to be redirected to </p> <pre><code>wordpress_install/dev/abc/index.php </code></pre> <p>My motive that any request (404 or anyt other) should go to index.php in subfolder. But, the original wordpress should run as it is.</p> <p>My current .htaccess in subfolder is:</p> <pre><code>RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^?]*)$ /index.php?path=$1 [NC,L,QSA] ErrorDocument 404 /index.php </code></pre> <p>The Wordpress .htaccess is as it is.</p>
[ { "answer_id": 209751, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 2, "selected": false, "text": "<p>You can't add the <strong>same action</strong> to the <strong>same action hook</strong>, with the <strong>same priority</strong>.</p>\n\n<p>This is done to prevent multiple plugins relying on a third party plugins' action to happen more than once (think woocommerce and all it's third party plugins, like gateway payment integrations, etc). \nSo without specifying priority, Grandma remains poor:</p>\n\n<pre><code>add_action('init','print_a_buck');\nadd_action('init','print_a_buck');\n\nfunction print_a_buck() {\n echo '$1&lt;/br&gt;';\n}\nadd_action('wp', 'die_hard');\nfunction die_hard() {\n die('hard');\n}\n</code></pre>\n\n<p>However, if you add priority to those actions: </p>\n\n<pre><code>add_action('init','print_a_buck', 1);\nadd_action('init','print_a_buck', 2);\nadd_action('init','print_a_buck', 3);\n</code></pre>\n\n<p>Grandma now dies with $4 in her pocket (1, 2, 3 and the default: 10).</p>\n" }, { "answer_id": 209753, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 5, "selected": true, "text": "<p>Here are some random thoughts on this:</p>\n\n<h2>Question #1</h2>\n\n<blockquote>\n <p>How much money did we send to grandma?</p>\n</blockquote>\n\n<p>For 100 page loads, we sent her 100 x $1 = $100.</p>\n\n<p><em>Here we actually mean <code>100 x do_action( 'init' )</code> calls.</em> </p>\n\n<p>It didn't matter that we added it twice with:</p>\n\n<pre><code>add_action( 'init','send_money_to_grandma' );\nadd_action( 'init','send_money_to_grandma' );\n</code></pre>\n\n<p>because the <em>callbacks</em> and <em>priorities</em> (default 10) are <strong>identical</strong>.</p>\n\n<p>We can check how the <code>add_action</code> is just a wrapper for <code>add_filter</code> that constructs the global <code>$wp_filter</code> array:</p>\n\n<pre><code>function add_filter( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) {\n global $wp_filter, $merged_filters;\n\n $idx = _wp_filter_build_unique_id($tag, $function_to_add, $priority);\n $wp_filter[$tag][$priority][$idx] = array(\n 'function' =&gt; $function_to_add, \n 'accepted_args' =&gt; $accepted_args\n );\n unset( $merged_filters[ $tag ] );\n return true;\n}\n</code></pre>\n\n<p>If we did however change the priority:</p>\n\n<pre><code>add_action( 'init','send_money_to_grandma', 9 );\nadd_action( 'init','send_money_to_grandma', 10 );\n</code></pre>\n\n<p>then we would send her 2 x $1 per page load or $200 for 100 page loads.</p>\n\n<p>Same if the callbacks where different:</p>\n\n<pre><code>add_action( 'init','send_money_to_grandma_1_dollar' );\nadd_action( 'init','send_money_to_grandma_also_1_dollar' );\n</code></pre>\n\n<h2>Question #2</h2>\n\n<blockquote>\n <p>If we want to make sure we only send grandma $1</p>\n</blockquote>\n\n<p>If we only want to send it <em>once per page load</em>, then this should do it:</p>\n\n<pre><code>add_action( 'init','send_money_to_grandma' );\n</code></pre>\n\n<p>because the <code>init</code> hook is only fired once. We might have other hooks that fires up many times per page load.</p>\n\n<p>Let's call:</p>\n\n<pre><code>add_action( 'someaction ','send_money_to_grandma' );\n</code></pre>\n\n<p>but what happens if <code>someaction</code> fires 10 times per page load?</p>\n\n<p>We could adjust the <code>send_money_to_grandma()</code> function with</p>\n\n<pre><code>function send_money_to_grandma() \n{\n if( ! did_action( 'someaction' ) )\n internetofThings(\"send grandma\",\"$1\");\n}\n</code></pre>\n\n<p>or use a <em>static</em> variable as a counter:</p>\n\n<pre><code>function send_money_to_grandma() \n{\n static $counter = 0;\n if( 0 === $counter++ )\n internetofThings(\"send grandma\",\"$1\");\n}\n</code></pre>\n\n<p>If we only want to run it once (ever!), then we might register an option in the <code>wp_options</code> table via the <a href=\"https://codex.wordpress.org/Options_API\">Options API</a>:</p>\n\n<pre><code>function send_money_to_grandma() \n{\n if( 'no' === get_option( 'sent_grandma_money', 'no' ) )\n {\n update_option( 'sent_grandma_money', 'yes' );\n internetofThings( \"send grandma\",\"$1\" );\n }\n}\n</code></pre>\n\n<p>If we want to send her money once every day, then we can use the <a href=\"https://codex.wordpress.org/Transients_API\">Transient API</a></p>\n\n<pre><code>function send_money_to_grandma() \n{\n if ( false === get_transient( 'sent_grandma_money' ) ) )\n {\n internetofThings( \"send grandma\",\"$1\" );\n set_transient( 'sent_grandma_money', 'yes', DAY_IN_SECONDS );\n }\n}\n</code></pre>\n\n<p>or even use the wp-cron. </p>\n\n<p>Note that you might have ajax calls. as well.</p>\n\n<p>There are ways to check for those, e.g. with <code>DOING_AJAX</code></p>\n\n<p>There might also be redirections, that could interrupt the flow.</p>\n\n<p>Then we might want to restrict to the backend only, <code>is_admin()</code> or not: <code>! is_admin()</code>.</p>\n\n<h2>Question #3</h2>\n\n<blockquote>\n <p>Is this something that plugin developers worry about?</p>\n</blockquote>\n\n<p>yes this is important.</p>\n\n<p>If we want to make our grandma very happy we would do:</p>\n\n<pre><code>add_action( 'all','send_money_to_grandma' );\n</code></pre>\n\n<p>but this would be very bad for performance ... and our wallet ;-)</p>\n" }, { "answer_id": 209829, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 3, "selected": false, "text": "<p>This is more a comment to the very good <a href=\"https://wordpress.stackexchange.com/a/209753/35541\">Birgire's answer</a> than a complete answer, but having to write code, comments don't fit.</p>\n\n<p>From the answer it may seems that the only reason why action is added once in OP sample code, even if <code>add_action()</code> is called twice, is the fact that the same priority is used. That's not true.</p>\n\n<p>In the code of <code>add_filter</code> an important part is <a href=\"https://developer.wordpress.org/reference/functions/_wp_filter_build_unique_id/\" rel=\"nofollow noreferrer\"><code>_wp_filter_build_unique_id()</code></a> function call, that creates an unique id per <em>callback</em>.</p>\n\n<p>If you use a simple variable, like a string that holds a function name, e.g. <code>\"send_money_to_grandma\"</code>, then the id will be equal to the string itself, so if priority is the same, being id the same as well, the callback is added once.</p>\n\n<p>However, things are not always simple like that. Callbacks may be anything that is <code>callable</code> in PHP:</p>\n\n<ul>\n<li>function names</li>\n<li>static class methods</li>\n<li>dynamic class methods</li>\n<li>invokable objects</li>\n<li>closures (anonymous functions)</li>\n</ul>\n\n<p>The first two are represented, respectively, by a string and an array of 2 strings (<code>'send_money_to_grandma'</code> and <code>array('MoneySender', 'send_to_grandma')</code>) so the id is always the same, and you can be sure that callback is added once if priority is the same.</p>\n\n<p>In all the other 3 cases, the id depends on object instances (an anonymous function is an object in PHP) so the callback is added once only if the object is the same <em>instance</em>, and it is important to note that <em>same instance</em> and <em>same class</em> are two different things.</p>\n\n<p>Take this example:</p>\n\n<pre><code>class MoneySender {\n\n public function sent_to_grandma( $amount = 1 ) {\n // things happen here\n }\n\n}\n\n$sender1 = new MoneySender();\n$sender2 = new MoneySender();\n\nadd_action( 'init', array( $sender1, 'sent_to_grandma' ) );\nadd_action( 'init', array( $sender1, 'sent_to_grandma' ) );\nadd_action( 'init', array( $sender2, 'sent_to_grandma' ) );\n</code></pre>\n\n<p>How many dollars are we sending per page load?</p>\n\n<p>Answer is 2, because the id WordPress generates for <code>$sender1</code> and <code>$sender2</code> are different.</p>\n\n<p>The same happen in this case:</p>\n\n<pre><code>add_action( 'init', function() {\n sent_to_grandma();\n} );\n\nadd_action( 'init', function() {\n sent_to_grandma();\n} );\n</code></pre>\n\n<p>Above I used the function <code>sent_to_grandma</code> inside closures, and even if the code is identical, the 2 closures are 2 different instance of <code>\\Closure</code> object, so WP will create 2 different ids, which will cause the action be added twice, even if priority is the same.</p>\n" } ]
2015/11/25
[ "https://wordpress.stackexchange.com/questions/209774", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75662/" ]
I have a folder with name: ``` wordpress_install/dev/abc ``` Now, I have created a index.php in abc folder and I want all the urls like: ``` wordpress_install/dev/abc/asdfasdfsdf (a 404 page) ``` to be redirected to ``` wordpress_install/dev/abc/index.php ``` My motive that any request (404 or anyt other) should go to index.php in subfolder. But, the original wordpress should run as it is. My current .htaccess in subfolder is: ``` RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^?]*)$ /index.php?path=$1 [NC,L,QSA] ErrorDocument 404 /index.php ``` The Wordpress .htaccess is as it is.
Here are some random thoughts on this: Question #1 ----------- > > How much money did we send to grandma? > > > For 100 page loads, we sent her 100 x $1 = $100. *Here we actually mean `100 x do_action( 'init' )` calls.* It didn't matter that we added it twice with: ``` add_action( 'init','send_money_to_grandma' ); add_action( 'init','send_money_to_grandma' ); ``` because the *callbacks* and *priorities* (default 10) are **identical**. We can check how the `add_action` is just a wrapper for `add_filter` that constructs the global `$wp_filter` array: ``` function add_filter( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) { global $wp_filter, $merged_filters; $idx = _wp_filter_build_unique_id($tag, $function_to_add, $priority); $wp_filter[$tag][$priority][$idx] = array( 'function' => $function_to_add, 'accepted_args' => $accepted_args ); unset( $merged_filters[ $tag ] ); return true; } ``` If we did however change the priority: ``` add_action( 'init','send_money_to_grandma', 9 ); add_action( 'init','send_money_to_grandma', 10 ); ``` then we would send her 2 x $1 per page load or $200 for 100 page loads. Same if the callbacks where different: ``` add_action( 'init','send_money_to_grandma_1_dollar' ); add_action( 'init','send_money_to_grandma_also_1_dollar' ); ``` Question #2 ----------- > > If we want to make sure we only send grandma $1 > > > If we only want to send it *once per page load*, then this should do it: ``` add_action( 'init','send_money_to_grandma' ); ``` because the `init` hook is only fired once. We might have other hooks that fires up many times per page load. Let's call: ``` add_action( 'someaction ','send_money_to_grandma' ); ``` but what happens if `someaction` fires 10 times per page load? We could adjust the `send_money_to_grandma()` function with ``` function send_money_to_grandma() { if( ! did_action( 'someaction' ) ) internetofThings("send grandma","$1"); } ``` or use a *static* variable as a counter: ``` function send_money_to_grandma() { static $counter = 0; if( 0 === $counter++ ) internetofThings("send grandma","$1"); } ``` If we only want to run it once (ever!), then we might register an option in the `wp_options` table via the [Options API](https://codex.wordpress.org/Options_API): ``` function send_money_to_grandma() { if( 'no' === get_option( 'sent_grandma_money', 'no' ) ) { update_option( 'sent_grandma_money', 'yes' ); internetofThings( "send grandma","$1" ); } } ``` If we want to send her money once every day, then we can use the [Transient API](https://codex.wordpress.org/Transients_API) ``` function send_money_to_grandma() { if ( false === get_transient( 'sent_grandma_money' ) ) ) { internetofThings( "send grandma","$1" ); set_transient( 'sent_grandma_money', 'yes', DAY_IN_SECONDS ); } } ``` or even use the wp-cron. Note that you might have ajax calls. as well. There are ways to check for those, e.g. with `DOING_AJAX` There might also be redirections, that could interrupt the flow. Then we might want to restrict to the backend only, `is_admin()` or not: `! is_admin()`. Question #3 ----------- > > Is this something that plugin developers worry about? > > > yes this is important. If we want to make our grandma very happy we would do: ``` add_action( 'all','send_money_to_grandma' ); ``` but this would be very bad for performance ... and our wallet ;-)
209,792
<p>I need to make a shortcode to display some HTML on a page based on site admins "role"? Not the logged in user but the site admin's role. By default the role is 'administrator' and the only other role is 'pro_user'. So if they are a "pro_user" I want to echo the the first "HTML type 1" and if not to output "HTML type 2" as you can see below: </p> <p>I tried this but did something wrong &amp; get blank output on the page. </p> <pre><code>add_shortcode( 'add_my_form', 'get_form_on_role' ); function get_form_on_role() { if( ! is_user_logged_in() ) { $user = new WP_User( get_current_user_id() ); $roles = $user-&gt;roles; if( $roles[0] == 'pro_user' ) { echo 'HTML type 1'; }elseif( $roles[0] == 'administrator' ) { echo 'HTML type 2'; } } } </code></pre>
[ { "answer_id": 209825, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 1, "selected": false, "text": "<p>I think below line of code is unnecessary, which is wrong if you looking for logged in user result. </p>\n\n<pre><code>if( ! is_user_logged_in() )\n</code></pre>\n\n<p>Please use below code, I make some changes for solution.</p>\n\n<pre><code>//Add a hook for a shortcode 'add_my_form' tag...\nadd_shortcode( 'add_my_form', 'get_form_on_role' );\n\n//Create sortcode API used function...\nfunction get_form_on_role() {\n if(is_user_logged_in() ) {//If user is logged in...\n\n //Get current user role information...\n $user = new WP_User( get_current_user_id() );\n $roles = $user-&gt;roles;\n\n $returnTxt = '';//Initialize return text variable...\n\n if( $roles[0] == 'pro_user' ) {//If user having 'pro_user' role...\n $returnTxt = 'HTML type 1';\n }elseif( $roles[0] == 'administrator' ) {//If user having 'administrator' role...\n $returnTxt = 'HTML type 2';\n }\n return $returnTxt;\n }\n}\n\n\n/*\n This will display 'HTML type 1' is user logged in with 'pro_user' role, \n If logged in user with 'administrator' then it will print 'HTML type 2'...\n*/\n//You can use sortcode by API like... \n&lt;?php echo do_shortcode(\"[add_my_form]\");?&gt;\n</code></pre>\n\n<p>Reference: <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow\">Shortcode_API</a></p>\n\n<p>Let me know if there is any doubt/query regarding this.</p>\n" }, { "answer_id": 209869, "author": "George B", "author_id": 63757, "author_profile": "https://wordpress.stackexchange.com/users/63757", "pm_score": 0, "selected": false, "text": "<p>Thank you! This does work if the user is logged in however this is for a public page in a multisite setting so if possible I would like it to display to all users and base the output on the site admin/owners role. </p>\n\n<p>Sorry if I was using the wrong code that checked if logged in and that misled you as to what I needed.</p>\n\n<p>What I would like is 'HTML type 1' above to return if the sites admin for that pages role is 'pro_user'. It does that now but only if that admin is logged in.</p>\n\n<p>Then if not 'pro_user' or if role='admin' to display 'HTML type 2'.</p>\n\n<p>Is that possible to get the site admins role and not the logged in users role?\nThe page authors role also would not work in this case.</p>\n\n<p>thank you for your help!!</p>\n" } ]
2015/11/25
[ "https://wordpress.stackexchange.com/questions/209792", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63757/" ]
I need to make a shortcode to display some HTML on a page based on site admins "role"? Not the logged in user but the site admin's role. By default the role is 'administrator' and the only other role is 'pro\_user'. So if they are a "pro\_user" I want to echo the the first "HTML type 1" and if not to output "HTML type 2" as you can see below: I tried this but did something wrong & get blank output on the page. ``` add_shortcode( 'add_my_form', 'get_form_on_role' ); function get_form_on_role() { if( ! is_user_logged_in() ) { $user = new WP_User( get_current_user_id() ); $roles = $user->roles; if( $roles[0] == 'pro_user' ) { echo 'HTML type 1'; }elseif( $roles[0] == 'administrator' ) { echo 'HTML type 2'; } } } ```
I think below line of code is unnecessary, which is wrong if you looking for logged in user result. ``` if( ! is_user_logged_in() ) ``` Please use below code, I make some changes for solution. ``` //Add a hook for a shortcode 'add_my_form' tag... add_shortcode( 'add_my_form', 'get_form_on_role' ); //Create sortcode API used function... function get_form_on_role() { if(is_user_logged_in() ) {//If user is logged in... //Get current user role information... $user = new WP_User( get_current_user_id() ); $roles = $user->roles; $returnTxt = '';//Initialize return text variable... if( $roles[0] == 'pro_user' ) {//If user having 'pro_user' role... $returnTxt = 'HTML type 1'; }elseif( $roles[0] == 'administrator' ) {//If user having 'administrator' role... $returnTxt = 'HTML type 2'; } return $returnTxt; } } /* This will display 'HTML type 1' is user logged in with 'pro_user' role, If logged in user with 'administrator' then it will print 'HTML type 2'... */ //You can use sortcode by API like... <?php echo do_shortcode("[add_my_form]");?> ``` Reference: [Shortcode\_API](https://codex.wordpress.org/Shortcode_API) Let me know if there is any doubt/query regarding this.
209,818
<p>So I have this <a href="http://workteamfun.ro/wp2/" rel="nofollow">site</a> and on the bottom of the site you can see the map and search. I have 2 problems with that:</p> <ol> <li>The search if offset not in line with the other elements.</li> <li>I want/need it to be full width just like in the Take a Quick and FREE Tour page (scroll down a bit to see the map).</li> </ol> <p>The thing is the theme does not allow me to add widgets where I want in the site only specific pages. The second link is the template for the "homepage" after I select this template I can't edit like the rest of the pages only add or delete widgets and the other problem is with the white space between the picture and the start of the blue background where the map is on the first link. </p> <p>I tried to take the code from the page with the map widget and paste it in the area with blue which is a call to action div in all pages and templates. This is the <a href="http://textuploader.com/5ce27" rel="nofollow">code</a>(hopefully it's the full code).</p> <p>Is there a way to add widgets anywhere in a site, is there a short-code mapper or a plugin, I found a few plugins but none with the desired result.</p>
[ { "answer_id": 209825, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 1, "selected": false, "text": "<p>I think below line of code is unnecessary, which is wrong if you looking for logged in user result. </p>\n\n<pre><code>if( ! is_user_logged_in() )\n</code></pre>\n\n<p>Please use below code, I make some changes for solution.</p>\n\n<pre><code>//Add a hook for a shortcode 'add_my_form' tag...\nadd_shortcode( 'add_my_form', 'get_form_on_role' );\n\n//Create sortcode API used function...\nfunction get_form_on_role() {\n if(is_user_logged_in() ) {//If user is logged in...\n\n //Get current user role information...\n $user = new WP_User( get_current_user_id() );\n $roles = $user-&gt;roles;\n\n $returnTxt = '';//Initialize return text variable...\n\n if( $roles[0] == 'pro_user' ) {//If user having 'pro_user' role...\n $returnTxt = 'HTML type 1';\n }elseif( $roles[0] == 'administrator' ) {//If user having 'administrator' role...\n $returnTxt = 'HTML type 2';\n }\n return $returnTxt;\n }\n}\n\n\n/*\n This will display 'HTML type 1' is user logged in with 'pro_user' role, \n If logged in user with 'administrator' then it will print 'HTML type 2'...\n*/\n//You can use sortcode by API like... \n&lt;?php echo do_shortcode(\"[add_my_form]\");?&gt;\n</code></pre>\n\n<p>Reference: <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow\">Shortcode_API</a></p>\n\n<p>Let me know if there is any doubt/query regarding this.</p>\n" }, { "answer_id": 209869, "author": "George B", "author_id": 63757, "author_profile": "https://wordpress.stackexchange.com/users/63757", "pm_score": 0, "selected": false, "text": "<p>Thank you! This does work if the user is logged in however this is for a public page in a multisite setting so if possible I would like it to display to all users and base the output on the site admin/owners role. </p>\n\n<p>Sorry if I was using the wrong code that checked if logged in and that misled you as to what I needed.</p>\n\n<p>What I would like is 'HTML type 1' above to return if the sites admin for that pages role is 'pro_user'. It does that now but only if that admin is logged in.</p>\n\n<p>Then if not 'pro_user' or if role='admin' to display 'HTML type 2'.</p>\n\n<p>Is that possible to get the site admins role and not the logged in users role?\nThe page authors role also would not work in this case.</p>\n\n<p>thank you for your help!!</p>\n" } ]
2015/11/25
[ "https://wordpress.stackexchange.com/questions/209818", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83780/" ]
So I have this [site](http://workteamfun.ro/wp2/) and on the bottom of the site you can see the map and search. I have 2 problems with that: 1. The search if offset not in line with the other elements. 2. I want/need it to be full width just like in the Take a Quick and FREE Tour page (scroll down a bit to see the map). The thing is the theme does not allow me to add widgets where I want in the site only specific pages. The second link is the template for the "homepage" after I select this template I can't edit like the rest of the pages only add or delete widgets and the other problem is with the white space between the picture and the start of the blue background where the map is on the first link. I tried to take the code from the page with the map widget and paste it in the area with blue which is a call to action div in all pages and templates. This is the [code](http://textuploader.com/5ce27)(hopefully it's the full code). Is there a way to add widgets anywhere in a site, is there a short-code mapper or a plugin, I found a few plugins but none with the desired result.
I think below line of code is unnecessary, which is wrong if you looking for logged in user result. ``` if( ! is_user_logged_in() ) ``` Please use below code, I make some changes for solution. ``` //Add a hook for a shortcode 'add_my_form' tag... add_shortcode( 'add_my_form', 'get_form_on_role' ); //Create sortcode API used function... function get_form_on_role() { if(is_user_logged_in() ) {//If user is logged in... //Get current user role information... $user = new WP_User( get_current_user_id() ); $roles = $user->roles; $returnTxt = '';//Initialize return text variable... if( $roles[0] == 'pro_user' ) {//If user having 'pro_user' role... $returnTxt = 'HTML type 1'; }elseif( $roles[0] == 'administrator' ) {//If user having 'administrator' role... $returnTxt = 'HTML type 2'; } return $returnTxt; } } /* This will display 'HTML type 1' is user logged in with 'pro_user' role, If logged in user with 'administrator' then it will print 'HTML type 2'... */ //You can use sortcode by API like... <?php echo do_shortcode("[add_my_form]");?> ``` Reference: [Shortcode\_API](https://codex.wordpress.org/Shortcode_API) Let me know if there is any doubt/query regarding this.
209,823
<p>I'm trying to send a query to a database, WHERE works fine if I'm querying for a number but not for a string. Example, if I try: </p> <pre><code>$all_pages = $wpdb-&gt;get_results('SELECT post_title, guid FROM wp_11_posts WHERE ID = 30', OBJECT); I get a result, no problem </code></pre> <p>However when I try a string, eg</p> <pre><code>$all_pages = $wpdb-&gt;get_results('SELECT post_title, guid FROM wp_11_posts WHERE post_title = Office Home', OBJECT); </code></pre> <p>it doesn't return anything, wonder if anyone can spot the reason why? column name is correct and the value does exist in the database. </p>
[ { "answer_id": 209831, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": -1, "selected": false, "text": "<p>Answer for: <strong><em>it doesn't return anything, wonder if anyone can spot the reason why?</em></strong></p>\n\n<p>MySQL is a lot like PHP, and will auto-convert data types as best it can. Since you're working with an int field (left-hand side), it'll try to transparently convert the right-hand-side of the argument into an int as well, so '9' just becomes 9.</p>\n\n<p>Strictly speaking, the quotes are unnecessary, and force MySQL to do a typecasting/conversion, so it wastes a bit of CPU time. In practice, unless you're running a Google-sized operation, such conversion overhead is going to be microscopically small.</p>\n\n<p>I changes your query code as per requirement. Please check it.</p>\n\n<pre><code>$strTitle = \"Office Home\";\n$all_pages = $wpdb-&gt;get_results('SELECT post_title, guid FROM wp_posts WHERE post_title = \"'. $strTitle .'\"', OBJECT);\n</code></pre>\n\n<p>Let me know if there is any query/doubt from this.</p>\n" }, { "answer_id": 209850, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 1, "selected": false, "text": "<p>You do not need to use quotes around some data types in SQL, integers being one of those types. That is why the first block of code works. It is a perfectly valid SQL statement. </p>\n\n<p>You do need to quote strings in SQL. That is why your second block of code does not work. The correct form would be:</p>\n\n<pre><code>$all_pages = $wpdb-&gt;get_results(\n 'SELECT post_title, guid FROM wp_11_posts WHERE post_title = \"Office Home\"', \n OBJECT\n);\n</code></pre>\n\n<p>If your data is in any way subject to user input you should use <code>prepare()</code>.</p>\n\n<pre><code>$string = \"Office Home\"; // if coming from $_POST or $_GET data or other user manipulatable sources\n$sql = 'SELECT post_title, guid FROM wp_11_posts WHERE post_title = %s';\n$sql = $wpdb-&gt;prepare($sql,$string);\n$all_pages = $wpdb-&gt;get_results($sql,OBJECT);\n</code></pre>\n\n<p><code>prepare()</code> will add the quotes as needed based on the data type indicated by the placeholder-- <code>%s</code>.</p>\n" } ]
2015/11/25
[ "https://wordpress.stackexchange.com/questions/209823", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83847/" ]
I'm trying to send a query to a database, WHERE works fine if I'm querying for a number but not for a string. Example, if I try: ``` $all_pages = $wpdb->get_results('SELECT post_title, guid FROM wp_11_posts WHERE ID = 30', OBJECT); I get a result, no problem ``` However when I try a string, eg ``` $all_pages = $wpdb->get_results('SELECT post_title, guid FROM wp_11_posts WHERE post_title = Office Home', OBJECT); ``` it doesn't return anything, wonder if anyone can spot the reason why? column name is correct and the value does exist in the database.
You do not need to use quotes around some data types in SQL, integers being one of those types. That is why the first block of code works. It is a perfectly valid SQL statement. You do need to quote strings in SQL. That is why your second block of code does not work. The correct form would be: ``` $all_pages = $wpdb->get_results( 'SELECT post_title, guid FROM wp_11_posts WHERE post_title = "Office Home"', OBJECT ); ``` If your data is in any way subject to user input you should use `prepare()`. ``` $string = "Office Home"; // if coming from $_POST or $_GET data or other user manipulatable sources $sql = 'SELECT post_title, guid FROM wp_11_posts WHERE post_title = %s'; $sql = $wpdb->prepare($sql,$string); $all_pages = $wpdb->get_results($sql,OBJECT); ``` `prepare()` will add the quotes as needed based on the data type indicated by the placeholder-- `%s`.
209,840
<p>I created a sub page to "users.php" where I can add a user in a customized way. I used a lot of the code from "<strong>user-new.php</strong>". However, user-new.php seems to rely on some javascript file to display the password when clicking the button, and to display errors, and maybe more.</p> <p>How do I know what script files "user-new.php" uses, where they are enqueued, and how I can enqueue it for my custom page?</p> <p>I suppose I need to use "admin_enqueue_scripts" somehow?</p>
[ { "answer_id": 209842, "author": "Aparna_29", "author_id": 84165, "author_profile": "https://wordpress.stackexchange.com/users/84165", "pm_score": 1, "selected": false, "text": "<p>You must have created submenu page using add_submenu_page() hook, so you can use wp_enqueue_script inside callback function of add_submenu_page hook. It will load script only on your submenu page.</p>\n\n<pre><code>add_submenu_page( $parent_slug, $page_title, $menu_title, $capability, $menu_slug,'callback');\n\nfunction callback()\n{\n//enqueue script\n}\n</code></pre>\n\n<p>Or if you want to enqueue script in dashboard(all pages) then you can enqueue script in admin_init hook</p>\n\n<pre><code>add_action( 'admin_init', 'function_name' );\nfunction function_name()\n{\n//enqueue script\n}\n</code></pre>\n" }, { "answer_id": 209855, "author": "Galivan", "author_id": 82394, "author_profile": "https://wordpress.stackexchange.com/users/82394", "pm_score": 0, "selected": false, "text": "<p>It turned out that there was more important code in \"user-new.php\" that I needed to copy, and the code for enqueuing the scripts were actually in that same file. So I needed these lines, particularly the second one:</p>\n\n<pre><code>wp_enqueue_script('wp-ajax-response');\nwp_enqueue_script( 'user-profile' );\n</code></pre>\n\n<p>(plus some more of the code to display errors - I just copied it).</p>\n" } ]
2015/11/25
[ "https://wordpress.stackexchange.com/questions/209840", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82394/" ]
I created a sub page to "users.php" where I can add a user in a customized way. I used a lot of the code from "**user-new.php**". However, user-new.php seems to rely on some javascript file to display the password when clicking the button, and to display errors, and maybe more. How do I know what script files "user-new.php" uses, where they are enqueued, and how I can enqueue it for my custom page? I suppose I need to use "admin\_enqueue\_scripts" somehow?
You must have created submenu page using add\_submenu\_page() hook, so you can use wp\_enqueue\_script inside callback function of add\_submenu\_page hook. It will load script only on your submenu page. ``` add_submenu_page( $parent_slug, $page_title, $menu_title, $capability, $menu_slug,'callback'); function callback() { //enqueue script } ``` Or if you want to enqueue script in dashboard(all pages) then you can enqueue script in admin\_init hook ``` add_action( 'admin_init', 'function_name' ); function function_name() { //enqueue script } ```
209,860
<p>I'm currently building a custom WordPress template and I've run into a problem with the search box.</p> <p>When I use the searchbox from the homepage, it works as intended. It also works as long as Permalinks are set to default. (<code>url.com/?page_id=1</code>) </p> <p>However, when I use the searchbox from another page when using pretty permalinks, the URL looks something like this: <code>http://url.com/pretty-page-title/?s=query</code> and a 404 page appears. </p> <p>My search box code looks like this</p> <p><code>&lt;form id="search-query"&gt; &lt;div class="search-box"&gt; &lt;form role="search" method="get" id="searchform" class="searchform" action="/index.php"&gt; &lt;div&gt; &lt;label class="screen-reader-text" for="s"&gt;&lt;?php _x( 'Search for:', 'label' ); ?&gt;&lt;/label&gt; &lt;input type="text" value="&lt;?php echo get_search_query(); ?&gt;" name="s" id="s" /&gt; &lt;input type="submit" id="searchsubmit" value="&lt;?php echo esc_attr_x( 'Search', 'submit button' ); ?&gt;" /&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/form&gt;</code></p> <p>Here's the site's URL if anyone's want to take a look: <a href="http://hermodsgymnasiet-develop.kaigan.modxcloud.com/" rel="nofollow">http://hermodsgymnasiet-develop.kaigan.modxcloud.com/</a></p> <p>Any help is very appreciated!</p>
[ { "answer_id": 209867, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": true, "text": "<p>Currently your form looks like:</p>\n\n<pre><code>&lt;form id=\"search-query\"&gt;\n &lt;p class=\"in-english\"&gt;&lt;a href=\"http://localhost/hermodswp/?page_id=76\"&gt;Information in English&lt;/a&gt;&lt;/p&gt;\n &lt;div class=\"search-box\"&gt; \n &lt;div&gt;\n &lt;label class=\"screen-reader-text\" for=\"s\"&gt;&lt;/label&gt;\n &lt;input type=\"text\" value=\"sdf\" name=\"s\" id=\"s\" style=\"width: 293px;\"&gt;\n &lt;input type=\"submit\" id=\"searchsubmit\" value=\"Sök\"&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>Try adjusting your submit action to point to your home_url().</p>\n\n<pre><code>action=\"&lt;?php echo home_url(); ?&gt;\"\n</code></pre>\n\n<p>You can edit the page in Chrome to see that this works fine.</p>\n\n<pre><code>&lt;form role=\"search\" id=\"search-query\" method=\"get\" action=\"http://hermodsgymnasiet-develop.kaigan.modxcloud.com/\"&gt;\n &lt;p class=\"in-english\"&gt;&lt;a href=\"http://localhost/hermodswp/?page_id=76\"&gt;Information in English&lt;/a&gt;&lt;/p&gt;\n &lt;div class=\"search-box\"&gt; \n &lt;div&gt;\n &lt;label class=\"screen-reader-text\" for=\"s\"&gt;&lt;/label&gt;\n &lt;input type=\"text\" value=\"\" name=\"s\" id=\"s\" style=\"width: 293px;\"&gt;\n &lt;input type=\"submit\" id=\"searchsubmit\" value=\"Sök\"&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/form&gt;\n</code></pre>\n" }, { "answer_id": 363161, "author": "Amirhossein Rahmati", "author_id": 185376, "author_profile": "https://wordpress.stackexchange.com/users/185376", "pm_score": 1, "selected": false, "text": "<p>Simply add <code>action=\"/\"</code>to your form!</p>\n" } ]
2015/11/25
[ "https://wordpress.stackexchange.com/questions/209860", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82005/" ]
I'm currently building a custom WordPress template and I've run into a problem with the search box. When I use the searchbox from the homepage, it works as intended. It also works as long as Permalinks are set to default. (`url.com/?page_id=1`) However, when I use the searchbox from another page when using pretty permalinks, the URL looks something like this: `http://url.com/pretty-page-title/?s=query` and a 404 page appears. My search box code looks like this `<form id="search-query"> <div class="search-box"> <form role="search" method="get" id="searchform" class="searchform" action="/index.php"> <div> <label class="screen-reader-text" for="s"><?php _x( 'Search for:', 'label' ); ?></label> <input type="text" value="<?php echo get_search_query(); ?>" name="s" id="s" /> <input type="submit" id="searchsubmit" value="<?php echo esc_attr_x( 'Search', 'submit button' ); ?>" /> </div> </form> </div> </form>` Here's the site's URL if anyone's want to take a look: <http://hermodsgymnasiet-develop.kaigan.modxcloud.com/> Any help is very appreciated!
Currently your form looks like: ``` <form id="search-query"> <p class="in-english"><a href="http://localhost/hermodswp/?page_id=76">Information in English</a></p> <div class="search-box"> <div> <label class="screen-reader-text" for="s"></label> <input type="text" value="sdf" name="s" id="s" style="width: 293px;"> <input type="submit" id="searchsubmit" value="Sök"> </div> </div> </form> ``` Try adjusting your submit action to point to your home\_url(). ``` action="<?php echo home_url(); ?>" ``` You can edit the page in Chrome to see that this works fine. ``` <form role="search" id="search-query" method="get" action="http://hermodsgymnasiet-develop.kaigan.modxcloud.com/"> <p class="in-english"><a href="http://localhost/hermodswp/?page_id=76">Information in English</a></p> <div class="search-box"> <div> <label class="screen-reader-text" for="s"></label> <input type="text" value="" name="s" id="s" style="width: 293px;"> <input type="submit" id="searchsubmit" value="Sök"> </div> </div> </form> ```
209,870
<p>I am wondering how to write code to order a list of posts by their terms from custom taxonomies?</p> <p><strong>Here is what I have so far</strong>:</p> <ul> <li>I have a page that lists all the posts in a Custom Post Type, on one page.</li> <li>Under each CPT Post, I have retrieved the Custom Taxonomies to show.</li> <li>I have allowed for the CPT posts to be sorted by Alpha, ASC and DESC.</li> </ul> <p>In the end, it looks like this: <a href="https://i.stack.imgur.com/oOu4R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oOu4R.png" alt="enter image description here"></a></p> <p><strong>The Goal</strong>:</p> <p>I would like to add a couple links with the "Sort By Title" ones I already have.</p> <p>Specifically, I would like to order by (alpha) Director, Studio, and Episodes, because I know these are either strings or numeric. </p> <p>I would also like to order by the Season Premiered, by year, but I may need to change the way I named those terms (It'll probably just spit out Winter 2011, Winter 2012 with the way it currently is). </p> <p>Sorting by Genre is another matter entirely that I am not going to tackle because of the multiple terms. </p> <p>I am not too sure how to go about this and could use the help.</p> <p><strong>The Page's Current Code</strong>:</p> <pre><code>&lt;div class="content-container"&gt; &lt;a href="?sort=titleup"&gt;Sort By Title A-Z&lt;/a&gt; &lt;a href="?sort=titledown"&gt;Sort By Title Z-A&lt;/a&gt; &lt;hr&gt; &lt;?php $type = 'animes'; $args=array( 'post_type' =&gt; $type, 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1, 'caller_get_posts'=&gt; 1 ); if( isset( $_GET['sort'] ) &amp;&amp; "titleup" == $_GET['sort'] ){ $args['orderby'] = 'title'; $args['order'] = 'ASC'; } if( isset( $_GET['sort'] ) &amp;&amp; "titledown" == $_GET['sort'] ){ $args['orderby'] = 'title'; $args['order'] = 'DESC'; } $my_query = new WP_Query($args); if( $my_query-&gt;have_posts() ) { while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post(); ?&gt; &lt;div class="anime-title"&gt;&lt;a href="&lt;?php the_permalink() ?&gt;" title="&lt;?php the_title_attribute(); ?&gt; Page"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/div&gt; &lt;br&gt;&lt;span&gt;Director:&lt;/span&gt; &lt;?php $taxonomy = 'director'; // get the term IDs assigned to post. $post_terms = wp_get_object_terms( $post-&gt;ID, $taxonomy, array( 'fields' =&gt; 'ids' ) ); // separator between links $separator = ', '; if ( !empty( $post_terms ) &amp;&amp; !is_wp_error( $post_terms ) ) { $term_ids = implode( ',' , $post_terms ); $terms = wp_list_categories( 'title_li=&amp;style=none&amp;echo=0&amp;taxonomy=' . $taxonomy . '&amp;include=' . $term_ids ); $terms = rtrim( trim( str_replace( '&lt;br /&gt;', $separator, $terms ) ), $separator ); // display post categories echo $terms; } ?&gt; &lt;br&gt;&lt;span&gt;Studio:&lt;/span&gt; &lt;?php $taxonomy = 'studio'; // get the term IDs assigned to post. $post_terms = wp_get_object_terms( $post-&gt;ID, $taxonomy, array( 'fields' =&gt; 'ids' ) ); // separator between links $separator = ', '; if ( !empty( $post_terms ) &amp;&amp; !is_wp_error( $post_terms ) ) { $term_ids = implode( ',' , $post_terms ); $terms = wp_list_categories( 'title_li=&amp;style=none&amp;echo=0&amp;taxonomy=' . $taxonomy . '&amp;include=' . $term_ids ); $terms = rtrim( trim( str_replace( '&lt;br /&gt;', $separator, $terms ) ), $separator ); // display post categories echo $terms; } ?&gt; &lt;br&gt;&lt;span&gt;Season Premiered:&lt;/span&gt; &lt;?php $taxonomy = 'season'; // get the term IDs assigned to post. $post_terms = wp_get_object_terms( $post-&gt;ID, $taxonomy, array( 'fields' =&gt; 'ids' ) ); // separator between links $separator = ', '; if ( !empty( $post_terms ) &amp;&amp; !is_wp_error( $post_terms ) ) { $term_ids = implode( ',' , $post_terms ); $terms = wp_list_categories( 'title_li=&amp;style=none&amp;echo=0&amp;taxonomy=' . $taxonomy . '&amp;include=' . $term_ids ); $terms = rtrim( trim( str_replace( '&lt;br /&gt;', $separator, $terms ) ), $separator ); // display post categories echo $terms; } ?&gt; &lt;br&gt;&lt;span&gt;Episodes:&lt;/span&gt; &lt;?php $taxonomy = 'episodes'; // get the term IDs assigned to post. $post_terms = wp_get_object_terms( $post-&gt;ID, $taxonomy, array( 'fields' =&gt; 'ids' ) ); // separator between links $separator = ', '; if ( !empty( $post_terms ) &amp;&amp; !is_wp_error( $post_terms ) ) { $term_ids = implode( ',' , $post_terms ); $terms = wp_list_categories( 'title_li=&amp;style=none&amp;echo=0&amp;taxonomy=' . $taxonomy . '&amp;include=' . $term_ids ); $terms = rtrim( trim( str_replace( '&lt;br /&gt;', $separator, $terms ) ), $separator ); // display post categories echo $terms; } ?&gt; &lt;br&gt;&lt;span&gt;Genres:&lt;/span&gt; &lt;?php $taxonomy = 'genre'; // get the term IDs assigned to post. $post_terms = wp_get_object_terms( $post-&gt;ID, $taxonomy, array( 'fields' =&gt; 'ids' ) ); // separator between links $separator = ', '; if ( !empty( $post_terms ) &amp;&amp; !is_wp_error( $post_terms ) ) { $term_ids = implode( ',' , $post_terms ); $terms = wp_list_categories( 'title_li=&amp;style=none&amp;echo=0&amp;taxonomy=' . $taxonomy . '&amp;include=' . $term_ids ); $terms = rtrim( trim( str_replace( '&lt;br /&gt;', $separator, $terms ) ), $separator ); // display post categories echo $terms; } ?&gt; &lt;hr&gt; &lt;?php endwhile; } wp_reset_query(); // Restore global post data stomped by the_post(). ?&gt; </code></pre> <p><strong>Other Information</strong>:</p> <p>Upon clicking the Title of the Show, it'll bring the reader to another page that shows an image of the show, the custom taxonomies listed again, and all other posts related to that Show (connected by Tag being the name of the Show). e.g, If there is a Review or Discussion post tagged with the Show "Boys and Girls", it'll show up on this page.</p> <p>Upon clicking the taxonomy terms, the reader will be taken to the page that lists all the Shows that are related to that term. e.g, All the shows that have been made by that Studio, all the shows with 12 episodes, all the shows under the Genre 'Action'.</p> <p>This above can potentially bring into question the overall structure of how I setup this up. I am very new to web development and wordpress, so I have done my best based on the research I've done. </p> <p>I have a couple of other unanswered Stack Exchange posts that go further into details and questions about structuring this part of the website. Help there is appreciated as well, or if you need further clarification on what I am trying to attempt. </p> <p><a href="https://wordpress.stackexchange.com/questions/209346/custom-post-type-and-taxonomies-structures">Custom Post Type and Taxonomies Structure</a></p> <p><a href="https://wordpress.stackexchange.com/questions/209383/creating-a-sortable-table-of-posts-by-taxonomies">Creating a Sortable Table by Taxonomy Terms</a></p> <p>Thank you very much for your time and the help you have all given me so far. </p>
[ { "answer_id": 210346, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 3, "selected": true, "text": "<p>WordPress core (as expressed by involved people on multiple occasions) strongly discourages sort by terms. It sees terms as exclusively <em>grouping</em> mechanism, with no ordering capabilities implied.</p>\n\n<p>So in your specific case WP would understand that there are different directors, that there are groups of shows done by those directors, but won't at all understand that there is some expectation of how order of shows can be impacted by directors assigned.</p>\n\n<p>Of course in practical development people <em>do</em> need to sort by terms in different circumstances. In practice this means some very custom SQL to make it happen.</p>\n\n<p>One of the most useful examples of implementation I know is covered by <a href=\"http://scribu.net/wordpress/sortable-taxonomy-columns.html\" rel=\"nofollow\">Sortable Taxonomy Columns</a> blog post.</p>\n\n<p>So to make it happen you would have to write/adapt necessary SQL and then incorporate it into your queries.</p>\n" }, { "answer_id": 210350, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 2, "selected": false, "text": "<p>While <a href=\"https://wordpress.stackexchange.com/a/210346/45169\">Rarst's answer</a> is correct, helpful and really gives you room to improve your understanding about the subject, the shortest practical answer to ordering any WP_Query by a <code>custom_post_meta</code> is:</p>\n\n<pre><code>$args = array(\n 'meta_key' =&gt; 'name', //custom field name here\n 'orderby' =&gt; 'meta_value', \n 'order' =&gt; 'ASC') // the sort order\n // the rest of your arguments here...\n);\n</code></pre>\n\n<p>If you need a custom sort order, other than <code>ASC</code> or <code>DESC</code>, you need to build a <a href=\"http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query\" rel=\"nofollow noreferrer\">custom Query</a>.</p>\n\n<hr>\n\n<p>UPDATE: My answer has nothing to do with the question. I simply missread it. Sorry. </p>\n\n<p>I won't delete it though, as the comments hold useful information for anyone who didn't yet decide between using <code>custom_post_meta</code> or <code>taxonomy</code> for a certain attribute. Sorting by taxonomy term is possible, as Rarst has pointed out, using Scribu's query (3rd, improved version). But you should avoid it, as it will take a toll on the speed of your queries. </p>\n\n<p>Use <code>terms</code> to group and <code>meta</code> to sort. Your site will be a lot faster, even with a lot of entries.</p>\n" } ]
2015/11/25
[ "https://wordpress.stackexchange.com/questions/209870", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83426/" ]
I am wondering how to write code to order a list of posts by their terms from custom taxonomies? **Here is what I have so far**: * I have a page that lists all the posts in a Custom Post Type, on one page. * Under each CPT Post, I have retrieved the Custom Taxonomies to show. * I have allowed for the CPT posts to be sorted by Alpha, ASC and DESC. In the end, it looks like this: [![enter image description here](https://i.stack.imgur.com/oOu4R.png)](https://i.stack.imgur.com/oOu4R.png) **The Goal**: I would like to add a couple links with the "Sort By Title" ones I already have. Specifically, I would like to order by (alpha) Director, Studio, and Episodes, because I know these are either strings or numeric. I would also like to order by the Season Premiered, by year, but I may need to change the way I named those terms (It'll probably just spit out Winter 2011, Winter 2012 with the way it currently is). Sorting by Genre is another matter entirely that I am not going to tackle because of the multiple terms. I am not too sure how to go about this and could use the help. **The Page's Current Code**: ``` <div class="content-container"> <a href="?sort=titleup">Sort By Title A-Z</a> <a href="?sort=titledown">Sort By Title Z-A</a> <hr> <?php $type = 'animes'; $args=array( 'post_type' => $type, 'post_status' => 'publish', 'posts_per_page' => -1, 'caller_get_posts'=> 1 ); if( isset( $_GET['sort'] ) && "titleup" == $_GET['sort'] ){ $args['orderby'] = 'title'; $args['order'] = 'ASC'; } if( isset( $_GET['sort'] ) && "titledown" == $_GET['sort'] ){ $args['orderby'] = 'title'; $args['order'] = 'DESC'; } $my_query = new WP_Query($args); if( $my_query->have_posts() ) { while ($my_query->have_posts()) : $my_query->the_post(); ?> <div class="anime-title"><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?> Page"><?php the_title(); ?></a></div> <br><span>Director:</span> <?php $taxonomy = 'director'; // get the term IDs assigned to post. $post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) ); // separator between links $separator = ', '; if ( !empty( $post_terms ) && !is_wp_error( $post_terms ) ) { $term_ids = implode( ',' , $post_terms ); $terms = wp_list_categories( 'title_li=&style=none&echo=0&taxonomy=' . $taxonomy . '&include=' . $term_ids ); $terms = rtrim( trim( str_replace( '<br />', $separator, $terms ) ), $separator ); // display post categories echo $terms; } ?> <br><span>Studio:</span> <?php $taxonomy = 'studio'; // get the term IDs assigned to post. $post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) ); // separator between links $separator = ', '; if ( !empty( $post_terms ) && !is_wp_error( $post_terms ) ) { $term_ids = implode( ',' , $post_terms ); $terms = wp_list_categories( 'title_li=&style=none&echo=0&taxonomy=' . $taxonomy . '&include=' . $term_ids ); $terms = rtrim( trim( str_replace( '<br />', $separator, $terms ) ), $separator ); // display post categories echo $terms; } ?> <br><span>Season Premiered:</span> <?php $taxonomy = 'season'; // get the term IDs assigned to post. $post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) ); // separator between links $separator = ', '; if ( !empty( $post_terms ) && !is_wp_error( $post_terms ) ) { $term_ids = implode( ',' , $post_terms ); $terms = wp_list_categories( 'title_li=&style=none&echo=0&taxonomy=' . $taxonomy . '&include=' . $term_ids ); $terms = rtrim( trim( str_replace( '<br />', $separator, $terms ) ), $separator ); // display post categories echo $terms; } ?> <br><span>Episodes:</span> <?php $taxonomy = 'episodes'; // get the term IDs assigned to post. $post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) ); // separator between links $separator = ', '; if ( !empty( $post_terms ) && !is_wp_error( $post_terms ) ) { $term_ids = implode( ',' , $post_terms ); $terms = wp_list_categories( 'title_li=&style=none&echo=0&taxonomy=' . $taxonomy . '&include=' . $term_ids ); $terms = rtrim( trim( str_replace( '<br />', $separator, $terms ) ), $separator ); // display post categories echo $terms; } ?> <br><span>Genres:</span> <?php $taxonomy = 'genre'; // get the term IDs assigned to post. $post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) ); // separator between links $separator = ', '; if ( !empty( $post_terms ) && !is_wp_error( $post_terms ) ) { $term_ids = implode( ',' , $post_terms ); $terms = wp_list_categories( 'title_li=&style=none&echo=0&taxonomy=' . $taxonomy . '&include=' . $term_ids ); $terms = rtrim( trim( str_replace( '<br />', $separator, $terms ) ), $separator ); // display post categories echo $terms; } ?> <hr> <?php endwhile; } wp_reset_query(); // Restore global post data stomped by the_post(). ?> ``` **Other Information**: Upon clicking the Title of the Show, it'll bring the reader to another page that shows an image of the show, the custom taxonomies listed again, and all other posts related to that Show (connected by Tag being the name of the Show). e.g, If there is a Review or Discussion post tagged with the Show "Boys and Girls", it'll show up on this page. Upon clicking the taxonomy terms, the reader will be taken to the page that lists all the Shows that are related to that term. e.g, All the shows that have been made by that Studio, all the shows with 12 episodes, all the shows under the Genre 'Action'. This above can potentially bring into question the overall structure of how I setup this up. I am very new to web development and wordpress, so I have done my best based on the research I've done. I have a couple of other unanswered Stack Exchange posts that go further into details and questions about structuring this part of the website. Help there is appreciated as well, or if you need further clarification on what I am trying to attempt. [Custom Post Type and Taxonomies Structure](https://wordpress.stackexchange.com/questions/209346/custom-post-type-and-taxonomies-structures) [Creating a Sortable Table by Taxonomy Terms](https://wordpress.stackexchange.com/questions/209383/creating-a-sortable-table-of-posts-by-taxonomies) Thank you very much for your time and the help you have all given me so far.
WordPress core (as expressed by involved people on multiple occasions) strongly discourages sort by terms. It sees terms as exclusively *grouping* mechanism, with no ordering capabilities implied. So in your specific case WP would understand that there are different directors, that there are groups of shows done by those directors, but won't at all understand that there is some expectation of how order of shows can be impacted by directors assigned. Of course in practical development people *do* need to sort by terms in different circumstances. In practice this means some very custom SQL to make it happen. One of the most useful examples of implementation I know is covered by [Sortable Taxonomy Columns](http://scribu.net/wordpress/sortable-taxonomy-columns.html) blog post. So to make it happen you would have to write/adapt necessary SQL and then incorporate it into your queries.
209,890
<p>I am converting a custom built site into a WordPress site. Unfortunately, the custom site has a completely different URL structure, which we would like to set up 301 redirects for. The site receives upwards of 300k unique visitors per month, therefore we wish to minimise the loss of traffic - especially the articles linked to from major news sites throughout the World.</p> <p>So, an example of a URL is as follows:-</p> <pre><code>.com/front/news/view.asp?cate=A06&amp;subcate=D006&amp;cNewsArti=201403402 </code></pre> <p>There are a total of around 30 categories (including parent and child), but close to 11,000 articles.</p> <p>I was thinking we could use the cNewsArti values as the 'post_slug' which would be easily imported into WP. However, this would still leave difficult in the remainder of the string, as we will likely use the following WP permalink:-</p> <pre><code>/%category%/%postname%/ </code></pre> <p>My thoughts are this would produce:-</p> <pre><code>.com/categoryname/subcatname/201403402 </code></pre> <p>So, how could I do the rest of the redirection? As you can gather, creating custom 301's for 11,000 articles is probably out of the equation.</p> <p>Any ideas?</p> <p>Thanks in advance!</p> <p>Edit:- The data has already been imported into the WordPress database, which all works OK - we assigned all posts to a bunch of random categories to ensure everything works in Wordpress as expected, no problems found.</p>
[ { "answer_id": 209924, "author": "Envision eCommerce", "author_id": 84031, "author_profile": "https://wordpress.stackexchange.com/users/84031", "pm_score": 0, "selected": false, "text": "<p>Solution, Permalink > Common Settings > Custom Structure </p>\n\n<p>Use this slug: <code>/%category%/</code></p>\n\n<p>Select only sub-category for the post. There is no need to select Parent Category for a post.</p>\n" }, { "answer_id": 209990, "author": "StuartM", "author_id": 82478, "author_profile": "https://wordpress.stackexchange.com/users/82478", "pm_score": 4, "selected": true, "text": "<p>The cause of this issue for future reference was the '.' in the category base, which was added to resolve a previous issue. Removing this and using /category/postname (per question) works, so will look for an alternative resolution to the category base issue.</p>\n" }, { "answer_id": 272665, "author": "Omar Chehab", "author_id": 123394, "author_profile": "https://wordpress.stackexchange.com/users/123394", "pm_score": -1, "selected": false, "text": "<h1>Workaround</h1>\n\n<p><strong>Settings</strong> > <strong>Permalinks</strong> > <strong>Common Settings</strong></p>\n\n<p><em>Custom Structure</em> <code>/%category%/%post_id%/%postname%/</code></p>\n\n<p><strong>Settings</strong> > <strong>Permalinks</strong> > <strong>Optional</strong></p>\n\n<p><em>Category base</em> <code>.</code></p>\n\n<p>Tested with WordPress version 4.8</p>\n" }, { "answer_id": 339407, "author": "Eduilson Rodrigues da Silva", "author_id": 164045, "author_profile": "https://wordpress.stackexchange.com/users/164045", "pm_score": 1, "selected": false, "text": "<p>You can change your permalinks, adding some extension at the end:</p>\n\n<pre><code>/%category%/%postname%.html\n</code></pre>\n" } ]
2015/11/25
[ "https://wordpress.stackexchange.com/questions/209890", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84275/" ]
I am converting a custom built site into a WordPress site. Unfortunately, the custom site has a completely different URL structure, which we would like to set up 301 redirects for. The site receives upwards of 300k unique visitors per month, therefore we wish to minimise the loss of traffic - especially the articles linked to from major news sites throughout the World. So, an example of a URL is as follows:- ``` .com/front/news/view.asp?cate=A06&subcate=D006&cNewsArti=201403402 ``` There are a total of around 30 categories (including parent and child), but close to 11,000 articles. I was thinking we could use the cNewsArti values as the 'post\_slug' which would be easily imported into WP. However, this would still leave difficult in the remainder of the string, as we will likely use the following WP permalink:- ``` /%category%/%postname%/ ``` My thoughts are this would produce:- ``` .com/categoryname/subcatname/201403402 ``` So, how could I do the rest of the redirection? As you can gather, creating custom 301's for 11,000 articles is probably out of the equation. Any ideas? Thanks in advance! Edit:- The data has already been imported into the WordPress database, which all works OK - we assigned all posts to a bunch of random categories to ensure everything works in Wordpress as expected, no problems found.
The cause of this issue for future reference was the '.' in the category base, which was added to resolve a previous issue. Removing this and using /category/postname (per question) works, so will look for an alternative resolution to the category base issue.
209,920
<p>Can you please take a Look at <a href="http://rumioptical.com/new-arrivals/" rel="nofollow noreferrer">this page</a> (please hove over the image to see the paragraph) and let me know why the <code>the_content()</code> is jumping out of paragraph tag?</p> <pre><code> echo '&lt;p style="color:#fff !important; font-size:16px; line-height:18;"&gt;'.the_content().'&lt;/p&gt;'; </code></pre> <p>Here us the whole code</p> <pre><code> &lt;div class="row"&gt; &lt;?php $args = array( 'post_type' =&gt; 'newArraivalsCPT', 'posts_per_page' =&gt; 1000 ); $loop = new WP_Query( $args ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); $thumb_id = get_post_thumbnail_id(); $thumb_url_array = wp_get_attachment_image_src($thumb_id, 'thumbnail-size', true); $thumb_url = $thumb_url_array[0]; echo '&lt;div class="col-sm-6 col-md-4"&gt;'; echo '&lt;div class="thumbnail text-center demo-3"&gt;'; echo '&lt;figure&gt;'; the_post_thumbnail('', array('class' =&gt; 'img-responsive', 'href' =&gt;$thumb_url)); // echo '&lt;img src="images/image1.jpg" alt=""/&gt;'; // echo '&lt;img src="images/image1.jpg" alt=""/&gt;'; echo '&lt;figcaption class="text-center"&gt;'; ?&gt; &lt;h3 class=""&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt; &lt;?php echo '&lt;p style="color:#fff !important; font-size:16px; line-height:18;"&gt;'.the_content().'&lt;/p&gt;'; echo '&lt;/figcaption&gt;'; echo '&lt;/figure&gt;'; echo '&lt;br /&gt;'; echo '&lt;p&gt;&lt;a href="'.$thumb_url.'" class="btn btn-sm btn-brown group1" title="Rumi Optical" role="button"&gt;Large Image&lt;/a&gt;&lt;/p&gt;'; echo '&lt;/div&gt;'; echo '&lt;/div&gt;'; echo '&lt;/div&gt;'; endwhile; ?&gt; </code></pre> <p> <a href="https://i.stack.imgur.com/VoXEq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VoXEq.png" alt="enter image description here"></a></p> <blockquote> <p>Here is an image from Chrome console</p> </blockquote>
[ { "answer_id": 209922, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": 3, "selected": true, "text": "<p>The function <code>the_content()</code> prints the content with a <code>p</code> tag itself. I mean, if you use </p>\n\n<pre><code>echo '&lt;p class=\"our_p\"&gt;' . the_content() . '&lt;/p&gt;;\n</code></pre>\n\n<p>It actually outputs-</p>\n\n<pre><code>&lt;p class=\"our_p\"&gt;&lt;p&gt;lorem ipsum dolor sit amet...&lt;/p&gt;&lt;/p&gt;\n</code></pre>\n\n<p>Use <code>get_the_content()</code> instead. It will return the unfiltered content. Something link this-</p>\n\n<pre><code>echo '&lt;p class=\"our_p\"&gt;' . get_the_content() . '&lt;/p&gt;;\n</code></pre>\n\n<p>Codex: <a href=\"https://codex.wordpress.org/Function_Reference/the_content\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/the_content</a></p>\n" }, { "answer_id": 209969, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": false, "text": "<p>First, you can <em>almost</em> solve this simply by not trying to concatenate the string. </p>\n\n<pre><code>echo '&lt;p style=\"color:#fff !important; font-size:16px; line-height:18;\"&gt;',the_content(),'&lt;/p&gt;';\n</code></pre>\n\n<p>Notice that I have used commas around <code>the_content()</code> instead of periods. <code>echo</code> will take a series of comma separated arguments and print them successively. </p>\n\n<p>However, <code>the_content()</code> runs formatting filters on the post content so you will end up with nested paragraphs tags, which is bad form. </p>\n\n<p>You can use <code>get_the_content()</code> as already suggested in another answer... that is:</p>\n\n<pre><code>echo '&lt;p style=\"color:#fff !important; font-size:16px; line-height:18;\"&gt;'.get_the_content().'&lt;/p&gt;';\n</code></pre>\n\n<p>But ... </p>\n\n<blockquote>\n <p>An important difference from the_content() is that get_the_content()\n does not pass the content through the 'the_content'. This means that\n get_the_content() will not auto-embed videos or expand shortcodes,\n among other things. </p>\n \n <p><a href=\"https://codex.wordpress.org/Function_Reference/get_the_content\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_the_content</a></p>\n</blockquote>\n\n<p>... now embeds and shortcodes don't work, nor do some formatting filters and you've potentially broken some filters added by themes and plugins too. <strong><em>This is not a good solution.</em></strong></p>\n\n<p>What you probably want is something much less complicated:</p>\n\n<pre><code>echo '&lt;div class=\"figcap-content&gt;';\n the_content();\necho '&lt;/div&gt;';\n</code></pre>\n\n<p>Or, if you must cram everything onto one line:</p>\n\n<pre><code>echo '&lt;span class=\"figcap-content&gt;'.the_content().'&lt;/span&gt;';\n</code></pre>\n\n<p>Use rules in your stylesheet to format the content, as you should:</p>\n\n<pre><code>.figcap-content {\n color:#fff !important; \n font-size:16px; \n line-height:18;\n}\n</code></pre>\n" }, { "answer_id": 211751, "author": "Smruti Ranjan", "author_id": 82867, "author_profile": "https://wordpress.stackexchange.com/users/82867", "pm_score": 0, "selected": false, "text": "<p><strong>the_content()</strong> function prints the content with a <strong>p</strong> tag itself.\nyou can use </p>\n\n<p><code>&lt;?php echo $post-&gt;post_content; ?&gt;</code> </p>\n\n<p>for geting the post content.It will not add the P tag automatically.</p>\n" } ]
2015/11/26
[ "https://wordpress.stackexchange.com/questions/209920", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31793/" ]
Can you please take a Look at [this page](http://rumioptical.com/new-arrivals/) (please hove over the image to see the paragraph) and let me know why the `the_content()` is jumping out of paragraph tag? ``` echo '<p style="color:#fff !important; font-size:16px; line-height:18;">'.the_content().'</p>'; ``` Here us the whole code ``` <div class="row"> <?php $args = array( 'post_type' => 'newArraivalsCPT', 'posts_per_page' => 1000 ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); $thumb_id = get_post_thumbnail_id(); $thumb_url_array = wp_get_attachment_image_src($thumb_id, 'thumbnail-size', true); $thumb_url = $thumb_url_array[0]; echo '<div class="col-sm-6 col-md-4">'; echo '<div class="thumbnail text-center demo-3">'; echo '<figure>'; the_post_thumbnail('', array('class' => 'img-responsive', 'href' =>$thumb_url)); // echo '<img src="images/image1.jpg" alt=""/>'; // echo '<img src="images/image1.jpg" alt=""/>'; echo '<figcaption class="text-center">'; ?> <h3 class=""><?php the_title(); ?></h3> <?php echo '<p style="color:#fff !important; font-size:16px; line-height:18;">'.the_content().'</p>'; echo '</figcaption>'; echo '</figure>'; echo '<br />'; echo '<p><a href="'.$thumb_url.'" class="btn btn-sm btn-brown group1" title="Rumi Optical" role="button">Large Image</a></p>'; echo '</div>'; echo '</div>'; echo '</div>'; endwhile; ?> ``` [![enter image description here](https://i.stack.imgur.com/VoXEq.png)](https://i.stack.imgur.com/VoXEq.png) > > Here is an image from Chrome console > > >
The function `the_content()` prints the content with a `p` tag itself. I mean, if you use ``` echo '<p class="our_p">' . the_content() . '</p>; ``` It actually outputs- ``` <p class="our_p"><p>lorem ipsum dolor sit amet...</p></p> ``` Use `get_the_content()` instead. It will return the unfiltered content. Something link this- ``` echo '<p class="our_p">' . get_the_content() . '</p>; ``` Codex: <https://codex.wordpress.org/Function_Reference/the_content>
209,928
<p>I need your help to upload a media image in my wordpress blog via the Wp-rest-api v2 and Oauth2 authentication. </p> <p>I did not find in the REST API documentation the way to send my image data (name of field, sending mode...?).</p> <pre><code>require('OAuth2/Client.php'); require('OAuth2/GrantType/IGrantType.php'); require('OAuth2/GrantType/AuthorizationCode.php'); const CLIENT_ID = 'XXX'; const CLIENT_SECRET = 'XX'; const REDIRECT_URI = 'http://127.0.0.1/test_api_wp/test.php'; const AUTHORIZATION_ENDPOINT = 'http://wordpress.local/oauth/authorize'; const TOKEN_ENDPOINT = 'http://wordpress.local/oauth/token'; $client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET); if (!isset($_GET['code'])) { $auth_url = $client-&gt;getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI); header('Location: ' . $auth_url); die('Redirect'); } else { $params = array('code' =&gt; $_GET['code'], 'redirect_uri' =&gt; REDIRECT_URI); $response = $client-&gt;getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $params); //authorization_code $token = $response['result']['access_token']; $client-&gt;setAccessToken($token); $client-&gt;setAccessTokenType(OAuth2\Client::ACCESS_TOKEN_BEARER); } $values = array( "date" =&gt; "2015-11-26 10:00:00", "date_gmt" =&gt; "2015-11-26 09:00:00", "modified" =&gt; "2015-11-26 10:00:00", "modified_gmt" =&gt; "2015-11-26 09:00:00", "status" =&gt; "future", "title" =&gt; "Titre media", "description" =&gt; "description media", "media_type" =&gt; "image", "source_url" =&gt; "https://www.base64-image.de/build/img/mr-base64-482fa1f767.png" ); $data = $client-&gt;fetch("wordpress.local/wp-json/wp/v2/media", $values, "POST"); echo "&lt;pre&gt;";print_r($data);echo "&lt;/pre&gt;"; </code></pre> <p>The response :</p> <pre><code>Array ( [result] =&gt; Array ( [code] =&gt; rest_upload_no_data [message] =&gt; No data supplied [data] =&gt; Array ( [status] =&gt; 400 ) ) [code] =&gt; 400 [content_type] =&gt; application/json; charset=UTF-8 ) </code></pre> <p>Any idea? Thanks a lot</p>
[ { "answer_id": 217588, "author": "MikeNGarrett", "author_id": 1670, "author_profile": "https://wordpress.stackexchange.com/users/1670", "pm_score": 5, "selected": true, "text": "<p>SO! This is fun. </p>\n\n<p>Keep in mind the WP-API is still very, very much a work-in-progress. </p>\n\n<h2>Content-Disposition</h2>\n\n<p>I found <a href=\"https://github.com/WP-API/WP-API/issues/1744\" rel=\"nofollow noreferrer\">an issue reported on the WP-API issue queue</a> about Content-Disposition. This is a required header for posting new media content and there are some very, very strict requirements when it comes to providing this in the proper format. </p>\n\n<h2>The Purpose of Create Media Endpoint</h2>\n\n<p>First, Let's take a step back. The API assumes at this point you have already uploaded a new file to the correct directory. This endpoint is creating the media content in the database that references this file. </p>\n\n<h2>The solution</h2>\n\n<p>You have to specify the filename of the media file to associate to your new content. This cannot be a remote url. As you can see from the <a href=\"http://v2.wp-api.org/reference/media/\" rel=\"nofollow noreferrer\">v2 documentation</a>, <code>source_url</code> and <code>link</code> are read-only. All you have to do to successfully submit your new content is add the following to your header: </p>\n\n<pre><code>'Content-Disposition' =&gt; 'filename=name-of-file.jpg',\n</code></pre>\n\n<p>As mentioned in the ticket, you cannot add quotes or specify the method you're using to send the file. It <strong>must</strong> be in the format above. At least, this is the case until they change it all around. </p>\n\n<p>Make sure the file type is one of the <a href=\"https://codex.wordpress.org/Uploading_Files\" rel=\"nofollow noreferrer\">accepted file types</a> and you're including the extension of the file is included in the request. Thanks to <a href=\"https://wordpress.stackexchange.com/users/9335/dr-deo\">Dr Deo</a> in the comments.</p>\n\n<p>For the record, I laughed with giddy joy when I finally figured this one out... scared the hell out of my wife. </p>\n" }, { "answer_id": 232672, "author": "pHiL", "author_id": 98588, "author_profile": "https://wordpress.stackexchange.com/users/98588", "pm_score": 2, "selected": false, "text": "<p>For the sake of \"cross-referencing\", see my <a href=\"https://stackoverflow.com/questions/33103707/wp-rest-api-how-to-upload-featured-image/38469742#38469742\">related answer here on StackOverflow</a> about media upload and using that media as \"featured media\" for a post.</p>\n" }, { "answer_id": 386537, "author": "minhhq", "author_id": 204817, "author_profile": "https://wordpress.stackexchange.com/users/204817", "pm_score": 0, "selected": false, "text": "<p>The answer for PHP CURL:</p>\n<pre><code>$curl = curl_init();\n\ncurl_setopt_array($curl, array(\n CURLOPT_URL =&gt; 'EndPoint',\n CURLOPT_RETURNTRANSFER =&gt; true,\n CURLOPT_ENCODING =&gt; '',\n CURLOPT_MAXREDIRS =&gt; 10,\n CURLOPT_TIMEOUT =&gt; 0,\n CURLOPT_FOLLOWLOCATION =&gt; true,\n CURLOPT_HTTP_VERSION =&gt; CURL_HTTP_VERSION_1_1,\n CURLOPT_CUSTOMREQUEST =&gt; 'POST',\n CURLOPT_POSTFIELDS =&gt; array('file'=&gt; new CURLFILE('LocalFilePathHere')),\n CURLOPT_HTTPHEADER =&gt; array(\n 'Content-Disposition: attachment; filename=abc.jpg',\n 'Content-Type: image/jpeg',\n 'Authorization: XXX YYY'\n ),\n));\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\necho $response;\n\n</code></pre>\n<p>If you still face issue &quot;Sorry, this file type is not permitted for security reasons&quot;, you have to add to wp-config.php to disable Fiter for Admin User</p>\n<pre><code>define('ALLOW_UNFILTERED_UPLOADS', true);\n</code></pre>\n" } ]
2015/11/26
[ "https://wordpress.stackexchange.com/questions/209928", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84303/" ]
I need your help to upload a media image in my wordpress blog via the Wp-rest-api v2 and Oauth2 authentication. I did not find in the REST API documentation the way to send my image data (name of field, sending mode...?). ``` require('OAuth2/Client.php'); require('OAuth2/GrantType/IGrantType.php'); require('OAuth2/GrantType/AuthorizationCode.php'); const CLIENT_ID = 'XXX'; const CLIENT_SECRET = 'XX'; const REDIRECT_URI = 'http://127.0.0.1/test_api_wp/test.php'; const AUTHORIZATION_ENDPOINT = 'http://wordpress.local/oauth/authorize'; const TOKEN_ENDPOINT = 'http://wordpress.local/oauth/token'; $client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET); if (!isset($_GET['code'])) { $auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI); header('Location: ' . $auth_url); die('Redirect'); } else { $params = array('code' => $_GET['code'], 'redirect_uri' => REDIRECT_URI); $response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $params); //authorization_code $token = $response['result']['access_token']; $client->setAccessToken($token); $client->setAccessTokenType(OAuth2\Client::ACCESS_TOKEN_BEARER); } $values = array( "date" => "2015-11-26 10:00:00", "date_gmt" => "2015-11-26 09:00:00", "modified" => "2015-11-26 10:00:00", "modified_gmt" => "2015-11-26 09:00:00", "status" => "future", "title" => "Titre media", "description" => "description media", "media_type" => "image", "source_url" => "https://www.base64-image.de/build/img/mr-base64-482fa1f767.png" ); $data = $client->fetch("wordpress.local/wp-json/wp/v2/media", $values, "POST"); echo "<pre>";print_r($data);echo "</pre>"; ``` The response : ``` Array ( [result] => Array ( [code] => rest_upload_no_data [message] => No data supplied [data] => Array ( [status] => 400 ) ) [code] => 400 [content_type] => application/json; charset=UTF-8 ) ``` Any idea? Thanks a lot
SO! This is fun. Keep in mind the WP-API is still very, very much a work-in-progress. Content-Disposition ------------------- I found [an issue reported on the WP-API issue queue](https://github.com/WP-API/WP-API/issues/1744) about Content-Disposition. This is a required header for posting new media content and there are some very, very strict requirements when it comes to providing this in the proper format. The Purpose of Create Media Endpoint ------------------------------------ First, Let's take a step back. The API assumes at this point you have already uploaded a new file to the correct directory. This endpoint is creating the media content in the database that references this file. The solution ------------ You have to specify the filename of the media file to associate to your new content. This cannot be a remote url. As you can see from the [v2 documentation](http://v2.wp-api.org/reference/media/), `source_url` and `link` are read-only. All you have to do to successfully submit your new content is add the following to your header: ``` 'Content-Disposition' => 'filename=name-of-file.jpg', ``` As mentioned in the ticket, you cannot add quotes or specify the method you're using to send the file. It **must** be in the format above. At least, this is the case until they change it all around. Make sure the file type is one of the [accepted file types](https://codex.wordpress.org/Uploading_Files) and you're including the extension of the file is included in the request. Thanks to [Dr Deo](https://wordpress.stackexchange.com/users/9335/dr-deo) in the comments. For the record, I laughed with giddy joy when I finally figured this one out... scared the hell out of my wife.
209,940
<p>I require to retrieve a list of the recently created blog posts or any Query-based usage of WP posts inside my PHP website and not within WP framework.</p> <p>I am new to Wordpress and stucked here. I already tried with include <code>wp-includes/post.php</code> file but i guess its still not working. Facing error regarding <code>undefined constant</code> and <code>function</code>. I don't know whether I am correct or not here. Is there any way to resolve this? </p>
[ { "answer_id": 209941, "author": "Bozidar Sikanjic", "author_id": 84223, "author_profile": "https://wordpress.stackexchange.com/users/84223", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>I require to retrieve a list of the recently created blog posts</p>\n</blockquote>\n\n<ol>\n<li>Connect to WP database (name/user/pass can be fount in wp-config.php) and</li>\n<li>execute SQL query same as with any other DB</li>\n</ol>\n\n<p>This link will help you to find your way around easier.\n<a href=\"https://codex.wordpress.org/Database_Description\" rel=\"nofollow\">https://codex.wordpress.org/Database_Description</a></p>\n\n<p>That of course presuming you know php, not just what few WP functions does... </p>\n" }, { "answer_id": 209943, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 3, "selected": true, "text": "<p>It's just simple, same reply from Error in <a href=\"https://wordpress.stackexchange.com/questions/209919/error-in-wp-update-post/209921#209921\">WP_update_post</a> but in your case there is small change.</p>\n\n<p>Just use <code>wp-load.php</code> as include. No need to include <code>post.php</code>. Once the <code>wp-load.php</code> file is included, the entire wealth of WordPress functions is provided to you. </p>\n\n<p>For pull the recent post, you need to use <code>wp_get_recent_posts()</code> wordpress function which is from WP framework.</p>\n\n<p>So your PHP code will like:</p>\n\n<pre><code>&lt;?php \n\n// Include the wp-load'\ninclude('YOUR_WP_PATH/wp-load.php');\n\n// For example get the last 10 posts\n\n// Returns posts as arrays instead of get_posts' objects\n$recent_posts = wp_get_recent_posts(array(\n 'numberposts' =&gt; 10\n));\n\n?&gt;\n</code></pre>\n\n<p>Let me know if there is any doubt/query from this.</p>\n" }, { "answer_id": 209949, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 0, "selected": false, "text": "<p>Apart from <a href=\"https://wordpress.stackexchange.com/a/209941/45169\">BozidarS</a>'s and <a href=\"https://wordpress.stackexchange.com/a/209943/45169\">AddWeb Solution Pvt Ltd</a>'s solutions which are both good, if you want to access your WP from another domain you will probabbly want to use one of the WordPress API's. There are two good plugins that provide JSON REST API's:</p>\n\n<ul>\n<li><a href=\"https://wordpress.org/plugins/json-rest-api/\" rel=\"nofollow noreferrer\">WP REST API</a> </li>\n<li><a href=\"https://wordpress.org/plugins/json-api/\" rel=\"nofollow noreferrer\">JSON API</a> </li>\n</ul>\n\n<p>I personally prefer the latter, as WP-REST-API currently has a bug with the <code>post__in</code> filter (if you only want a specific list of ids you only have two options: get them one by one (multiple api calls) or get all unpaginated posts and filter out the results; another workaround for this bug is to create categories based on your REST needs and request posts by category). </p>\n\n<p>However, word is out that WP-REST-API might become the \"official\" REST api for WordPress, but I don't have a reliable source to backup this statement. It's just hearsay.</p>\n" } ]
2015/11/26
[ "https://wordpress.stackexchange.com/questions/209940", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84297/" ]
I require to retrieve a list of the recently created blog posts or any Query-based usage of WP posts inside my PHP website and not within WP framework. I am new to Wordpress and stucked here. I already tried with include `wp-includes/post.php` file but i guess its still not working. Facing error regarding `undefined constant` and `function`. I don't know whether I am correct or not here. Is there any way to resolve this?
It's just simple, same reply from Error in [WP\_update\_post](https://wordpress.stackexchange.com/questions/209919/error-in-wp-update-post/209921#209921) but in your case there is small change. Just use `wp-load.php` as include. No need to include `post.php`. Once the `wp-load.php` file is included, the entire wealth of WordPress functions is provided to you. For pull the recent post, you need to use `wp_get_recent_posts()` wordpress function which is from WP framework. So your PHP code will like: ``` <?php // Include the wp-load' include('YOUR_WP_PATH/wp-load.php'); // For example get the last 10 posts // Returns posts as arrays instead of get_posts' objects $recent_posts = wp_get_recent_posts(array( 'numberposts' => 10 )); ?> ``` Let me know if there is any doubt/query from this.
209,979
<p>I have custom post type 'Partnerzy' already set. While adding new 'Partner', you select a category (kredyty, leasingi, etc.). And having that, I need to show them on a page, like this: <a href="https://i.stack.imgur.com/IU0vw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IU0vw.png" alt="enter image description here"></a></p> <p>I figured out that all I need to do is take all 'Partnerzy' posts, group them by category and finally show them on the site.</p> <p>My code looks like this:</p> <pre><code>$catArgs = array( 'type' =&gt; 'post', 'child_of' =&gt; 0, 'parent' =&gt; '', 'orderby' =&gt; 'name', 'order' =&gt; 'ASC', 'hide_empty' =&gt; 1, 'hierarchical' =&gt; 1, 'exclude' =&gt; '', 'include' =&gt; '', 'number' =&gt; '', 'taxonomy' =&gt; 'category', 'pad_counts' =&gt; false ); $categoryList = get_categories( $catArgs ); echo 'Sum: '.count($categoryList); for ($i=0; $i &lt; count($categoryList); $i++) { echo '&lt;br&gt;Number of loop: ' . $i; echo '&lt;br&gt;Category name: ' . $categoryList[$i]-&gt;name; $the_query_partnerzy = new WP_Query( array( post_type=&gt;'Partnerzy', category_name=&gt;$categoryList[$i]-&gt;name ) ); echo count($the_query_partnerzy); if ($the_query_partnerzy-&gt;have_posts()) { echo 'I got it!'; echo '&lt;div class="post-list container"&gt;'; echo '&lt;p class="post-title"&gt;'. $categoryList[$i]-&gt;name .'&lt;/p&gt;'; while ($the_query_partnerzy-&gt;have_posts()) { $the_query_partnerzy-&gt;the_post(); echo the_post_thumbnail(); } // while echo '&lt;/div&gt;'; } // query partnerzy } // for </code></pre> <p>Since I have few categories, I came with an idea to wrap it in a FOR loop. That works as far as this line:</p> <pre><code> if ($the_query_partnerzy-&gt;have_posts()) </code></pre> <p>And what is more interesting.. This line:</p> <pre><code>echo count($the_query_partnerzy); </code></pre> <p>really is counting elements in this query, but shows only 1 (weird). And having that, I'm not able to move further than this.</p> <p>I would appreciate any kind or any form of help.</p>
[ { "answer_id": 209980, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": false, "text": "<p>I honestly don't know what problem you are trying to solve. It is not clear what you are trying to accomplish with this code, but:</p>\n\n<blockquote>\n <p><code>echo count($the_query_partnerzy);</code></p>\n \n <p>really is counting elements in this query, but shows only 1 (weird).\n And having that, I'm not able to move further than this.</p>\n</blockquote>\n\n<p>No, its not. <code>WP_Query</code> returns an object and <a href=\"https://stackoverflow.com/q/1314745\"><code>count</code> doesn't work on Objects, mostly.</a></p>\n\n<p>The actual query results are in <code>$the_query_partnerzy-&gt;posts</code> so <code>count($the_query_partnerzy)</code> would give you what you want, but the <code>WP_Query</code> object already provides that data for you. Use <code>$the_query_partnerzy-&gt;found_posts</code> instead.</p>\n\n<p>I cleaned up your code a bit, and this does work using the 'post' post type (so I could run the code and test it):</p>\n\n<pre><code>$catArgs = array(\n 'type' =&gt; 'post',\n 'child_of' =&gt; 0,\n 'parent' =&gt; '',\n 'orderby' =&gt; 'name',\n 'order' =&gt; 'ASC',\n 'hide_empty' =&gt; 1,\n 'hierarchical' =&gt; 1,\n 'exclude' =&gt; '',\n 'include' =&gt; '',\n 'number' =&gt; '',\n 'taxonomy' =&gt; 'category',\n 'pad_counts' =&gt; false \n); \n\n$categoryList = get_categories( $catArgs );\n\necho 'Sum: '.count($categoryList);\n\n$i = 0;// debugging ?\nfor ($categoryList as $catl) {\n echo '&lt;br&gt;Number of loop: ' . $i; // debugging ?\n echo '&lt;br&gt;Category name: ' . $catl-&gt;name;\n $the_query_partnerzy = new WP_Query( \n array( \n 'post_type' =&gt;'post', \n 'category_name' =&gt; $catl-&gt;name \n ) \n );\n echo $the_query_partnerzy-&gt;found_posts; // debugging ?\n if ($the_query_partnerzy-&gt;have_posts()) {\n echo 'I got it!'; // debugging ?\n echo '&lt;div class=\"post-list container\"&gt;';\n echo '&lt;p class=\"post-title\"&gt;'. $catl-&gt;name .'&lt;/p&gt;';\n while ($the_query_partnerzy-&gt;have_posts()) {\n $the_query_partnerzy-&gt;the_post();\n echo the_post_thumbnail();\n } // while\n echo '&lt;/div&gt;';\n } // query partnerzy\n $i++; // debugging ?\n}\n</code></pre>\n\n<p>A few notes:</p>\n\n<ol>\n<li>The lines marked <code>// debugging ?</code> most certainly should be removed.</li>\n<li>The type of <code>for</code> loop you are using, while valid, is rarely\nnecessary in PHP. There is a much more convenient <code>foreach</code>, and\nthat <code>for</code> loop was causing some errors as (for reasons I have not\ninvestigated) the array given back by <code>get_categories()</code> started\nwith <code>1</code> and not <code>0</code>. With <code>foreach</code> you don't have to worry about\nthat.</li>\n<li><p>You were missing quotes in your query arguments. That is, this:</p>\n\n<pre><code> $the_query_partnerzy = new WP_Query( \n array( \n post_type =&gt; 'post', \n category_name =&gt; $catl-&gt;name \n ) \n );\n</code></pre>\n\n<p>Instead of this:</p>\n\n<pre><code> $the_query_partnerzy = new WP_Query( \n array( \n 'post_type' =&gt; 'post', \n 'category_name' =&gt; $catl-&gt;name \n ) \n );\n</code></pre>\n\n<p>While that should have worked it was spitting out warning like\ncrazy.</p></li>\n<li>You are pulling categories from the <code>post</code> post type, but later are\ntrying to pull posts from a different post type having those\ncategories. Are you sure that the categories are registered for both\npost types and that there are in fact posts that fit that logic?</li>\n</ol>\n\n<p>That said, the code is good and works for me. </p>\n" }, { "answer_id": 210005, "author": "Kacper Knapik", "author_id": 77857, "author_profile": "https://wordpress.stackexchange.com/users/77857", "pm_score": 0, "selected": false, "text": "<p>So thanks to you guys, I've figured out the answer.</p>\n\n<p>Here is my code:</p>\n\n<pre><code>foreach ($categoryList as $thisCategory) {\n\n $query = new WP_Query( array( 'post_type' =&gt; 'partnerzy' ) );\n\n if ($query-&gt;have_posts()) {\n\n echo '&lt;div class=\"post-list container\"&gt;';\n echo '&lt;p class=\"post-partners-title\"&gt;'. $thisCategory-&gt;name .'&lt;/p&gt;';\n echo '&lt;div class=\"row\"&gt;';\n\n while ($query-&gt;have_posts()) {\n\n if (in_category($thisCategory-&gt;slug, $query-&gt;the_post())) {\n\n echo '&lt;div class=\"col-lg-3 col-md-3 col-sm-6 col-xs-12 partner-item\"&gt;';\n echo '&lt;div class=\"col-lg-12 col-md-12 col-sm-12 col-xs-12\"&gt;';\n echo the_post_thumbnail();\n echo the_title('&lt;span&gt;', '&lt;/span&gt;');\n echo '&lt;/div&gt;&lt;/div&gt;';\n\n }\n\n } // while\n\n echo '&lt;/div&gt;&lt;/div&gt;';\n\n } else {\n\n echo '&lt;br&gt;nope&lt;br&gt;&lt;br&gt;';\n\n } // query partnerzy\n\n wp_reset_postdata();\n\n} // foreach\n</code></pre>\n\n<p>Thanks for your time. Cheers</p>\n" } ]
2015/11/26
[ "https://wordpress.stackexchange.com/questions/209979", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77857/" ]
I have custom post type 'Partnerzy' already set. While adding new 'Partner', you select a category (kredyty, leasingi, etc.). And having that, I need to show them on a page, like this: [![enter image description here](https://i.stack.imgur.com/IU0vw.png)](https://i.stack.imgur.com/IU0vw.png) I figured out that all I need to do is take all 'Partnerzy' posts, group them by category and finally show them on the site. My code looks like this: ``` $catArgs = array( 'type' => 'post', 'child_of' => 0, 'parent' => '', 'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => 1, 'hierarchical' => 1, 'exclude' => '', 'include' => '', 'number' => '', 'taxonomy' => 'category', 'pad_counts' => false ); $categoryList = get_categories( $catArgs ); echo 'Sum: '.count($categoryList); for ($i=0; $i < count($categoryList); $i++) { echo '<br>Number of loop: ' . $i; echo '<br>Category name: ' . $categoryList[$i]->name; $the_query_partnerzy = new WP_Query( array( post_type=>'Partnerzy', category_name=>$categoryList[$i]->name ) ); echo count($the_query_partnerzy); if ($the_query_partnerzy->have_posts()) { echo 'I got it!'; echo '<div class="post-list container">'; echo '<p class="post-title">'. $categoryList[$i]->name .'</p>'; while ($the_query_partnerzy->have_posts()) { $the_query_partnerzy->the_post(); echo the_post_thumbnail(); } // while echo '</div>'; } // query partnerzy } // for ``` Since I have few categories, I came with an idea to wrap it in a FOR loop. That works as far as this line: ``` if ($the_query_partnerzy->have_posts()) ``` And what is more interesting.. This line: ``` echo count($the_query_partnerzy); ``` really is counting elements in this query, but shows only 1 (weird). And having that, I'm not able to move further than this. I would appreciate any kind or any form of help.
I honestly don't know what problem you are trying to solve. It is not clear what you are trying to accomplish with this code, but: > > `echo count($the_query_partnerzy);` > > > really is counting elements in this query, but shows only 1 (weird). > And having that, I'm not able to move further than this. > > > No, its not. `WP_Query` returns an object and [`count` doesn't work on Objects, mostly.](https://stackoverflow.com/q/1314745) The actual query results are in `$the_query_partnerzy->posts` so `count($the_query_partnerzy)` would give you what you want, but the `WP_Query` object already provides that data for you. Use `$the_query_partnerzy->found_posts` instead. I cleaned up your code a bit, and this does work using the 'post' post type (so I could run the code and test it): ``` $catArgs = array( 'type' => 'post', 'child_of' => 0, 'parent' => '', 'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => 1, 'hierarchical' => 1, 'exclude' => '', 'include' => '', 'number' => '', 'taxonomy' => 'category', 'pad_counts' => false ); $categoryList = get_categories( $catArgs ); echo 'Sum: '.count($categoryList); $i = 0;// debugging ? for ($categoryList as $catl) { echo '<br>Number of loop: ' . $i; // debugging ? echo '<br>Category name: ' . $catl->name; $the_query_partnerzy = new WP_Query( array( 'post_type' =>'post', 'category_name' => $catl->name ) ); echo $the_query_partnerzy->found_posts; // debugging ? if ($the_query_partnerzy->have_posts()) { echo 'I got it!'; // debugging ? echo '<div class="post-list container">'; echo '<p class="post-title">'. $catl->name .'</p>'; while ($the_query_partnerzy->have_posts()) { $the_query_partnerzy->the_post(); echo the_post_thumbnail(); } // while echo '</div>'; } // query partnerzy $i++; // debugging ? } ``` A few notes: 1. The lines marked `// debugging ?` most certainly should be removed. 2. The type of `for` loop you are using, while valid, is rarely necessary in PHP. There is a much more convenient `foreach`, and that `for` loop was causing some errors as (for reasons I have not investigated) the array given back by `get_categories()` started with `1` and not `0`. With `foreach` you don't have to worry about that. 3. You were missing quotes in your query arguments. That is, this: ``` $the_query_partnerzy = new WP_Query( array( post_type => 'post', category_name => $catl->name ) ); ``` Instead of this: ``` $the_query_partnerzy = new WP_Query( array( 'post_type' => 'post', 'category_name' => $catl->name ) ); ``` While that should have worked it was spitting out warning like crazy. 4. You are pulling categories from the `post` post type, but later are trying to pull posts from a different post type having those categories. Are you sure that the categories are registered for both post types and that there are in fact posts that fit that logic? That said, the code is good and works for me.
210,008
<p>I need help with this. I need repeat taxonomy in two places, are post, and coupones post, this code is in clipper theme.</p> <p>this code put taxonomy stores in coupon.</p> <pre><code>add_action('init', 'clpr_post_type', 0); // remove_action('init', 'create_builtin_taxonomies', 0); // in case we want to remove all default WP taxonomies // register all the custom taxonomies and custom post type function clpr_post_type() { global $wpdb, $app_abbr; //need $wpdb!! // get the slug value for the ad custom post type &amp; taxonomies if(get_option($app_abbr.'_coupon_permalink')) $post_type_base_url = get_option($app_abbr.'_coupon_permalink'); else $post_type_base_url = 'coupon'; if(get_option($app_abbr.'_coupon_cat_tax_permalink')) $cat_tax_base_url = get_option($app_abbr.'_coupon_cat_tax_permalink'); else $cat_tax_base_url = 'coupon-category'; if(get_option($app_abbr.'_coupon_type_tax_permalink')) $type_tax_base_url = get_option($app_abbr.'_coupon_type_tax_permalink'); else $type_tax_base_url = 'coupon-type'; if(get_option($app_abbr.'_coupon_store_tax_permalink')) $store_tax_base_url = get_option($app_abbr.'_coupon_store_tax_permalink'); else $store_tax_base_url = 'store'; if(get_option($app_abbr.'_coupon_tag_tax_permalink')) $tag_tax_base_url = get_option($app_abbr.'_coupon_tag_tax_permalink'); else $tag_tax_base_url = 'coupon-tag'; if(get_option($app_abbr.'_coupon_image_tax_permalink')) $image_tax_base_url = get_option($app_abbr.'_coupon_image_tax_permalink'); else $image_tax_base_url = 'coupon-image'; register_post_type( APP_POST_TYPE, array( 'labels' =&gt; array( 'name' =&gt; __( 'Coupons', 'appthemes' ), 'singular_name' =&gt; __( 'Coupons', 'appthemes' ), 'add_new' =&gt; __( 'Add New', 'appthemes' ), 'add_new_item' =&gt; __( 'Add New Coupon', 'appthemes' ), 'edit' =&gt; __( 'Edit', 'appthemes' ), 'edit_item' =&gt; __( 'Edit Coupon', 'appthemes' ), 'new_item' =&gt; __( 'New Coupon', 'appthemes' ), 'view' =&gt; __( 'View Coupons', 'appthemes' ), 'view_item' =&gt; __( 'View Coupon', 'appthemes' ), 'search_items' =&gt; __( 'Search Coupons', 'appthemes' ), 'not_found' =&gt; __( 'No coupons found', 'appthemes' ), 'not_found_in_trash' =&gt; __( 'No coupons found in trash', 'appthemes' ), 'parent' =&gt; __( 'Parent Coupon', 'appthemes' ), ), 'description' =&gt; __( 'This is where you can create new coupon listings on your site.', 'appthemes' ), 'public' =&gt; true, 'show_ui' =&gt; true, 'capability_type' =&gt; 'post', 'publicly_queryable' =&gt; true, 'exclude_from_search' =&gt; false, 'menu_position' =&gt; 8, 'menu_icon' =&gt; get_template_directory_uri() . '/images/site_icon.png', 'hierarchical' =&gt; false, 'rewrite' =&gt; array( 'slug' =&gt; $post_type_base_url, 'with_front' =&gt; false ), /* Slug set so that permalinks work when just showing post name */ 'query_var' =&gt; true, 'supports' =&gt; array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'sticky' ) ) ); // register post status for unreliable coupons register_post_status( 'unreliable', array( 'label' =&gt; __( 'Unreliable', 'appthemes' ), 'public' =&gt; true, '_builtin' =&gt; true, 'label_count' =&gt; _n_noop( 'Unreliable &lt;span class="count"&gt;(%s)&lt;/span&gt;', 'Unreliable &lt;span class="count"&gt;(%s)&lt;/span&gt;', 'appthemes' ), 'show_in_admin_all_list' =&gt; true, 'show_in_admin_status_list' =&gt; true, 'capability_type' =&gt; APP_POST_TYPE, ) ); // register the newcategory taxonomy register_taxonomy( APP_TAX_CAT, array( APP_POST_TYPE ), array( 'hierarchical' =&gt; true, 'labels' =&gt; array( 'name' =&gt; __( 'Categories', 'appthemes'), 'singular_name' =&gt; __( 'Coupon Category', 'appthemes'), 'search_items' =&gt; __( 'Search Coupon Categories', 'appthemes'), 'all_items' =&gt; __( 'All Coupon Categories', 'appthemes'), 'parent_item' =&gt; __( 'Parent Coupon Category', 'appthemes'), 'parent_item_colon' =&gt; __( 'Parent Coupon Category:', 'appthemes'), 'edit_item' =&gt; __( 'Edit Coupon Category', 'appthemes'), 'update_item' =&gt; __( 'Update Coupon Category', 'appthemes'), 'add_new_item' =&gt; __( 'Add New Coupon Category', 'appthemes'), 'new_item_name' =&gt; __( 'New Coupon Category Name', 'appthemes') ), 'show_ui' =&gt; true, 'query_var' =&gt; true, 'update_count_callback' =&gt; '_update_post_term_count', 'rewrite' =&gt; array( 'slug' =&gt; $cat_tax_base_url, 'with_front' =&gt; false, 'hierarchical' =&gt; true ), ) ); register_taxonomy( APP_TAX_TAG, array( APP_POST_TYPE ), array( 'hierarchical' =&gt; false, 'labels' =&gt; array( 'name' =&gt; __( 'Coupon Tags', 'appthemes'), 'singular_name' =&gt; __( 'Coupon Tag', 'appthemes'), 'search_items' =&gt; __( 'Search Coupon Tags', 'appthemes'), 'all_items' =&gt; __( 'All Coupon Tags', 'appthemes'), 'edit_item' =&gt; __( 'Edit Coupon Tag', 'appthemes'), 'update_item' =&gt; __( 'Update Coupon Tag', 'appthemes'), 'add_new_item' =&gt; __( 'Add New Coupon Tag', 'appthemes'), 'add_or_remove_items' =&gt; __( 'Add or remove Coupon Tags', 'appthemes'), 'separate_items_with_commas' =&gt; __( 'Separate Coupon Tags with commas', 'appthemes'), 'choose_from_most_used' =&gt; __( 'Choose from the most common Coupon Tags', 'appthemes'), 'new_item_name' =&gt; __( 'New Coupon Tag Name', 'appthemes') ), 'show_ui' =&gt; true, 'query_var' =&gt; true, 'update_count_callback' =&gt; '_update_post_term_count', 'rewrite' =&gt; array( 'slug' =&gt; $tag_tax_base_url, 'with_front' =&gt; false, 'hierarchical' =&gt; true ), ) ); register_taxonomy( APP_TAX_STORE, array( APP_POST_TYPE ), array( 'hierarchical' =&gt; true, 'labels' =&gt; array( 'name' =&gt; __( 'Stores', 'appthemes'), 'singular_name' =&gt; __( 'Store', 'appthemes'), 'search_items' =&gt; __( 'Search Stores', 'appthemes'), 'all_items' =&gt; __( 'All Stores', 'appthemes'), 'edit_item' =&gt; __( 'Edit Store', 'appthemes'), 'update_item' =&gt; __( 'Update Store', 'appthemes'), 'add_new_item' =&gt; __( 'Add New Store', 'appthemes'), 'add_or_remove_items' =&gt; __( 'Add or remove Stores', 'appthemes'), 'separate_items_with_commas' =&gt; __( 'Separate Stores with commas', 'appthemes'), 'choose_from_most_used' =&gt; __( 'Choose from the most common Stores', 'appthemes'), 'new_item_name' =&gt; __( 'New Store Name', 'appthemes') ), 'show_ui' =&gt; true, 'query_var' =&gt; true, 'update_count_callback' =&gt; '_update_post_term_count', 'rewrite' =&gt; array( 'slug' =&gt; $store_tax_base_url, 'with_front' =&gt; false, 'hierarchical' =&gt; true ), ) ); register_taxonomy( APP_TAX_TYPE, array( APP_POST_TYPE ), array( 'hierarchical' =&gt; true, 'labels' =&gt; array( 'name' =&gt; __( 'Coupon Types', 'appthemes'), 'singular_name' =&gt; __( 'Coupon Type', 'appthemes'), 'search_items' =&gt; __( 'Search Coupon Types', 'appthemes'), 'all_items' =&gt; __( 'All Coupon Types', 'appthemes'), 'parent_item' =&gt; __( 'Parent Coupon Type', 'appthemes'), 'parent_item_colon' =&gt; __( 'Parent Coupon Type:', 'appthemes'), 'edit_item' =&gt; __( 'Edit Coupon Type', 'appthemes'), 'update_item' =&gt; __( 'Update Coupon Type', 'appthemes'), 'add_new_item' =&gt; __( 'Add New Coupon Type', 'appthemes'), 'new_item_name' =&gt; __( 'New Coupon Type Name', 'appthemes') ), 'show_ui' =&gt; true, 'query_var' =&gt; true, 'update_count_callback' =&gt; '_update_post_term_count', 'rewrite' =&gt; array( 'slug' =&gt; $type_tax_base_url, 'with_front' =&gt; false, 'hierarchical' =&gt; true ), ) ); // register taxonomy for printable coupon images register_taxonomy( APP_TAX_IMAGE, array( 'attachment' ), array( 'hierarchical' =&gt; false, 'labels' =&gt; array( 'name' =&gt; __( 'Coupon Images', 'appthemes'), 'singular_name' =&gt; __( 'Coupon Image', 'appthemes'), 'search_items' =&gt; __( 'Search Coupon Images', 'appthemes'), 'all_items' =&gt; __( 'All Coupon Images', 'appthemes'), 'parent_item' =&gt; __( 'Parent Coupon Image', 'appthemes'), 'parent_item_colon' =&gt; __( 'Parent Coupon Image:', 'appthemes'), 'edit_item' =&gt; __( 'Edit Coupon Image', 'appthemes'), 'update_item' =&gt; __( 'Update Coupon Image', 'appthemes'), 'add_new_item' =&gt; __( 'Add New Coupon Image', 'appthemes'), 'new_item_name' =&gt; __( 'New Coupon Image Name', 'appthemes') ), 'public' =&gt; false, 'show_ui' =&gt; false, 'query_var' =&gt; true, 'update_count_callback' =&gt; '_update_post_term_count', 'rewrite' =&gt; array( 'slug' =&gt; $image_tax_base_url, 'with_front' =&gt; false, 'hierarchical' =&gt; false ), ) ); $wpdb-&gt;storesmeta = $wpdb-&gt;clpr_storesmeta; // this needs to happen once after install script first runs if ( get_option( $app_abbr.'_rewrite_flush_flag' ) == 'true' ) { flush_rewrite_rules(); delete_option( $app_abbr.'_rewrite_flush_flag' ); } } </code></pre> <p>and this is my code in the same file.</p> <pre><code>// new code taxonomias function clrp_taxonomy_post(){ global $wpdb, $app_abbr; //need $wpdb!! if(get_option($app_abbr.'_coupon_store_tax_permalink')) $store_tax_base_url = get_option($app_abbr.'_coupon_store_tax_permalink'); else $store_tax_base_url = 'store'; register_taxonomy( APP_TAX_STORE, // taxonomy stores array( APP_POST_TYPE_POST ), // type POST array( 'hierarchical' =&gt; true, 'labels' =&gt; array( 'name' =&gt; __( 'Stores', 'appthemes'), 'singular_name' =&gt; __( 'Store', 'appthemes'), 'search_items' =&gt; __( 'Search Stores', 'appthemes'), 'all_items' =&gt; __( 'All Stores', 'appthemes'), 'edit_item' =&gt; __( 'Edit Store', 'appthemes'), 'update_item' =&gt; __( 'Update Store', 'appthemes'), 'add_new_item' =&gt; __( 'Add New Store', 'appthemes'), 'add_or_remove_items' =&gt; __( 'Add or remove Stores', 'appthemes'), 'separate_items_with_commas' =&gt; __( 'Separate Stores with commas', 'appthemes'), 'choose_from_most_used' =&gt; __( 'Choose from the most common Stores', 'appthemes'), 'new_item_name' =&gt; __( 'New Store Name', 'appthemes') ), 'show_ui' =&gt; true, 'query_var' =&gt; true, 'update_count_callback' =&gt; '_update_post_term_count', 'rewrite' =&gt; array( 'slug' =&gt; $store_tax_base_url, 'with_front' =&gt; false, 'hierarchical' =&gt; true ), ) ); } add_action('init', 'clrp_taxonomy_post', 0); </code></pre> <p>this last code just show in post but not in coupons, I need to this taxonomy show in post and coupons</p> <p>thanks for your attention.</p>
[ { "answer_id": 209980, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": false, "text": "<p>I honestly don't know what problem you are trying to solve. It is not clear what you are trying to accomplish with this code, but:</p>\n\n<blockquote>\n <p><code>echo count($the_query_partnerzy);</code></p>\n \n <p>really is counting elements in this query, but shows only 1 (weird).\n And having that, I'm not able to move further than this.</p>\n</blockquote>\n\n<p>No, its not. <code>WP_Query</code> returns an object and <a href=\"https://stackoverflow.com/q/1314745\"><code>count</code> doesn't work on Objects, mostly.</a></p>\n\n<p>The actual query results are in <code>$the_query_partnerzy-&gt;posts</code> so <code>count($the_query_partnerzy)</code> would give you what you want, but the <code>WP_Query</code> object already provides that data for you. Use <code>$the_query_partnerzy-&gt;found_posts</code> instead.</p>\n\n<p>I cleaned up your code a bit, and this does work using the 'post' post type (so I could run the code and test it):</p>\n\n<pre><code>$catArgs = array(\n 'type' =&gt; 'post',\n 'child_of' =&gt; 0,\n 'parent' =&gt; '',\n 'orderby' =&gt; 'name',\n 'order' =&gt; 'ASC',\n 'hide_empty' =&gt; 1,\n 'hierarchical' =&gt; 1,\n 'exclude' =&gt; '',\n 'include' =&gt; '',\n 'number' =&gt; '',\n 'taxonomy' =&gt; 'category',\n 'pad_counts' =&gt; false \n); \n\n$categoryList = get_categories( $catArgs );\n\necho 'Sum: '.count($categoryList);\n\n$i = 0;// debugging ?\nfor ($categoryList as $catl) {\n echo '&lt;br&gt;Number of loop: ' . $i; // debugging ?\n echo '&lt;br&gt;Category name: ' . $catl-&gt;name;\n $the_query_partnerzy = new WP_Query( \n array( \n 'post_type' =&gt;'post', \n 'category_name' =&gt; $catl-&gt;name \n ) \n );\n echo $the_query_partnerzy-&gt;found_posts; // debugging ?\n if ($the_query_partnerzy-&gt;have_posts()) {\n echo 'I got it!'; // debugging ?\n echo '&lt;div class=\"post-list container\"&gt;';\n echo '&lt;p class=\"post-title\"&gt;'. $catl-&gt;name .'&lt;/p&gt;';\n while ($the_query_partnerzy-&gt;have_posts()) {\n $the_query_partnerzy-&gt;the_post();\n echo the_post_thumbnail();\n } // while\n echo '&lt;/div&gt;';\n } // query partnerzy\n $i++; // debugging ?\n}\n</code></pre>\n\n<p>A few notes:</p>\n\n<ol>\n<li>The lines marked <code>// debugging ?</code> most certainly should be removed.</li>\n<li>The type of <code>for</code> loop you are using, while valid, is rarely\nnecessary in PHP. There is a much more convenient <code>foreach</code>, and\nthat <code>for</code> loop was causing some errors as (for reasons I have not\ninvestigated) the array given back by <code>get_categories()</code> started\nwith <code>1</code> and not <code>0</code>. With <code>foreach</code> you don't have to worry about\nthat.</li>\n<li><p>You were missing quotes in your query arguments. That is, this:</p>\n\n<pre><code> $the_query_partnerzy = new WP_Query( \n array( \n post_type =&gt; 'post', \n category_name =&gt; $catl-&gt;name \n ) \n );\n</code></pre>\n\n<p>Instead of this:</p>\n\n<pre><code> $the_query_partnerzy = new WP_Query( \n array( \n 'post_type' =&gt; 'post', \n 'category_name' =&gt; $catl-&gt;name \n ) \n );\n</code></pre>\n\n<p>While that should have worked it was spitting out warning like\ncrazy.</p></li>\n<li>You are pulling categories from the <code>post</code> post type, but later are\ntrying to pull posts from a different post type having those\ncategories. Are you sure that the categories are registered for both\npost types and that there are in fact posts that fit that logic?</li>\n</ol>\n\n<p>That said, the code is good and works for me. </p>\n" }, { "answer_id": 210005, "author": "Kacper Knapik", "author_id": 77857, "author_profile": "https://wordpress.stackexchange.com/users/77857", "pm_score": 0, "selected": false, "text": "<p>So thanks to you guys, I've figured out the answer.</p>\n\n<p>Here is my code:</p>\n\n<pre><code>foreach ($categoryList as $thisCategory) {\n\n $query = new WP_Query( array( 'post_type' =&gt; 'partnerzy' ) );\n\n if ($query-&gt;have_posts()) {\n\n echo '&lt;div class=\"post-list container\"&gt;';\n echo '&lt;p class=\"post-partners-title\"&gt;'. $thisCategory-&gt;name .'&lt;/p&gt;';\n echo '&lt;div class=\"row\"&gt;';\n\n while ($query-&gt;have_posts()) {\n\n if (in_category($thisCategory-&gt;slug, $query-&gt;the_post())) {\n\n echo '&lt;div class=\"col-lg-3 col-md-3 col-sm-6 col-xs-12 partner-item\"&gt;';\n echo '&lt;div class=\"col-lg-12 col-md-12 col-sm-12 col-xs-12\"&gt;';\n echo the_post_thumbnail();\n echo the_title('&lt;span&gt;', '&lt;/span&gt;');\n echo '&lt;/div&gt;&lt;/div&gt;';\n\n }\n\n } // while\n\n echo '&lt;/div&gt;&lt;/div&gt;';\n\n } else {\n\n echo '&lt;br&gt;nope&lt;br&gt;&lt;br&gt;';\n\n } // query partnerzy\n\n wp_reset_postdata();\n\n} // foreach\n</code></pre>\n\n<p>Thanks for your time. Cheers</p>\n" } ]
2015/11/26
[ "https://wordpress.stackexchange.com/questions/210008", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82358/" ]
I need help with this. I need repeat taxonomy in two places, are post, and coupones post, this code is in clipper theme. this code put taxonomy stores in coupon. ``` add_action('init', 'clpr_post_type', 0); // remove_action('init', 'create_builtin_taxonomies', 0); // in case we want to remove all default WP taxonomies // register all the custom taxonomies and custom post type function clpr_post_type() { global $wpdb, $app_abbr; //need $wpdb!! // get the slug value for the ad custom post type & taxonomies if(get_option($app_abbr.'_coupon_permalink')) $post_type_base_url = get_option($app_abbr.'_coupon_permalink'); else $post_type_base_url = 'coupon'; if(get_option($app_abbr.'_coupon_cat_tax_permalink')) $cat_tax_base_url = get_option($app_abbr.'_coupon_cat_tax_permalink'); else $cat_tax_base_url = 'coupon-category'; if(get_option($app_abbr.'_coupon_type_tax_permalink')) $type_tax_base_url = get_option($app_abbr.'_coupon_type_tax_permalink'); else $type_tax_base_url = 'coupon-type'; if(get_option($app_abbr.'_coupon_store_tax_permalink')) $store_tax_base_url = get_option($app_abbr.'_coupon_store_tax_permalink'); else $store_tax_base_url = 'store'; if(get_option($app_abbr.'_coupon_tag_tax_permalink')) $tag_tax_base_url = get_option($app_abbr.'_coupon_tag_tax_permalink'); else $tag_tax_base_url = 'coupon-tag'; if(get_option($app_abbr.'_coupon_image_tax_permalink')) $image_tax_base_url = get_option($app_abbr.'_coupon_image_tax_permalink'); else $image_tax_base_url = 'coupon-image'; register_post_type( APP_POST_TYPE, array( 'labels' => array( 'name' => __( 'Coupons', 'appthemes' ), 'singular_name' => __( 'Coupons', 'appthemes' ), 'add_new' => __( 'Add New', 'appthemes' ), 'add_new_item' => __( 'Add New Coupon', 'appthemes' ), 'edit' => __( 'Edit', 'appthemes' ), 'edit_item' => __( 'Edit Coupon', 'appthemes' ), 'new_item' => __( 'New Coupon', 'appthemes' ), 'view' => __( 'View Coupons', 'appthemes' ), 'view_item' => __( 'View Coupon', 'appthemes' ), 'search_items' => __( 'Search Coupons', 'appthemes' ), 'not_found' => __( 'No coupons found', 'appthemes' ), 'not_found_in_trash' => __( 'No coupons found in trash', 'appthemes' ), 'parent' => __( 'Parent Coupon', 'appthemes' ), ), 'description' => __( 'This is where you can create new coupon listings on your site.', 'appthemes' ), 'public' => true, 'show_ui' => true, 'capability_type' => 'post', 'publicly_queryable' => true, 'exclude_from_search' => false, 'menu_position' => 8, 'menu_icon' => get_template_directory_uri() . '/images/site_icon.png', 'hierarchical' => false, 'rewrite' => array( 'slug' => $post_type_base_url, 'with_front' => false ), /* Slug set so that permalinks work when just showing post name */ 'query_var' => true, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'sticky' ) ) ); // register post status for unreliable coupons register_post_status( 'unreliable', array( 'label' => __( 'Unreliable', 'appthemes' ), 'public' => true, '_builtin' => true, 'label_count' => _n_noop( 'Unreliable <span class="count">(%s)</span>', 'Unreliable <span class="count">(%s)</span>', 'appthemes' ), 'show_in_admin_all_list' => true, 'show_in_admin_status_list' => true, 'capability_type' => APP_POST_TYPE, ) ); // register the newcategory taxonomy register_taxonomy( APP_TAX_CAT, array( APP_POST_TYPE ), array( 'hierarchical' => true, 'labels' => array( 'name' => __( 'Categories', 'appthemes'), 'singular_name' => __( 'Coupon Category', 'appthemes'), 'search_items' => __( 'Search Coupon Categories', 'appthemes'), 'all_items' => __( 'All Coupon Categories', 'appthemes'), 'parent_item' => __( 'Parent Coupon Category', 'appthemes'), 'parent_item_colon' => __( 'Parent Coupon Category:', 'appthemes'), 'edit_item' => __( 'Edit Coupon Category', 'appthemes'), 'update_item' => __( 'Update Coupon Category', 'appthemes'), 'add_new_item' => __( 'Add New Coupon Category', 'appthemes'), 'new_item_name' => __( 'New Coupon Category Name', 'appthemes') ), 'show_ui' => true, 'query_var' => true, 'update_count_callback' => '_update_post_term_count', 'rewrite' => array( 'slug' => $cat_tax_base_url, 'with_front' => false, 'hierarchical' => true ), ) ); register_taxonomy( APP_TAX_TAG, array( APP_POST_TYPE ), array( 'hierarchical' => false, 'labels' => array( 'name' => __( 'Coupon Tags', 'appthemes'), 'singular_name' => __( 'Coupon Tag', 'appthemes'), 'search_items' => __( 'Search Coupon Tags', 'appthemes'), 'all_items' => __( 'All Coupon Tags', 'appthemes'), 'edit_item' => __( 'Edit Coupon Tag', 'appthemes'), 'update_item' => __( 'Update Coupon Tag', 'appthemes'), 'add_new_item' => __( 'Add New Coupon Tag', 'appthemes'), 'add_or_remove_items' => __( 'Add or remove Coupon Tags', 'appthemes'), 'separate_items_with_commas' => __( 'Separate Coupon Tags with commas', 'appthemes'), 'choose_from_most_used' => __( 'Choose from the most common Coupon Tags', 'appthemes'), 'new_item_name' => __( 'New Coupon Tag Name', 'appthemes') ), 'show_ui' => true, 'query_var' => true, 'update_count_callback' => '_update_post_term_count', 'rewrite' => array( 'slug' => $tag_tax_base_url, 'with_front' => false, 'hierarchical' => true ), ) ); register_taxonomy( APP_TAX_STORE, array( APP_POST_TYPE ), array( 'hierarchical' => true, 'labels' => array( 'name' => __( 'Stores', 'appthemes'), 'singular_name' => __( 'Store', 'appthemes'), 'search_items' => __( 'Search Stores', 'appthemes'), 'all_items' => __( 'All Stores', 'appthemes'), 'edit_item' => __( 'Edit Store', 'appthemes'), 'update_item' => __( 'Update Store', 'appthemes'), 'add_new_item' => __( 'Add New Store', 'appthemes'), 'add_or_remove_items' => __( 'Add or remove Stores', 'appthemes'), 'separate_items_with_commas' => __( 'Separate Stores with commas', 'appthemes'), 'choose_from_most_used' => __( 'Choose from the most common Stores', 'appthemes'), 'new_item_name' => __( 'New Store Name', 'appthemes') ), 'show_ui' => true, 'query_var' => true, 'update_count_callback' => '_update_post_term_count', 'rewrite' => array( 'slug' => $store_tax_base_url, 'with_front' => false, 'hierarchical' => true ), ) ); register_taxonomy( APP_TAX_TYPE, array( APP_POST_TYPE ), array( 'hierarchical' => true, 'labels' => array( 'name' => __( 'Coupon Types', 'appthemes'), 'singular_name' => __( 'Coupon Type', 'appthemes'), 'search_items' => __( 'Search Coupon Types', 'appthemes'), 'all_items' => __( 'All Coupon Types', 'appthemes'), 'parent_item' => __( 'Parent Coupon Type', 'appthemes'), 'parent_item_colon' => __( 'Parent Coupon Type:', 'appthemes'), 'edit_item' => __( 'Edit Coupon Type', 'appthemes'), 'update_item' => __( 'Update Coupon Type', 'appthemes'), 'add_new_item' => __( 'Add New Coupon Type', 'appthemes'), 'new_item_name' => __( 'New Coupon Type Name', 'appthemes') ), 'show_ui' => true, 'query_var' => true, 'update_count_callback' => '_update_post_term_count', 'rewrite' => array( 'slug' => $type_tax_base_url, 'with_front' => false, 'hierarchical' => true ), ) ); // register taxonomy for printable coupon images register_taxonomy( APP_TAX_IMAGE, array( 'attachment' ), array( 'hierarchical' => false, 'labels' => array( 'name' => __( 'Coupon Images', 'appthemes'), 'singular_name' => __( 'Coupon Image', 'appthemes'), 'search_items' => __( 'Search Coupon Images', 'appthemes'), 'all_items' => __( 'All Coupon Images', 'appthemes'), 'parent_item' => __( 'Parent Coupon Image', 'appthemes'), 'parent_item_colon' => __( 'Parent Coupon Image:', 'appthemes'), 'edit_item' => __( 'Edit Coupon Image', 'appthemes'), 'update_item' => __( 'Update Coupon Image', 'appthemes'), 'add_new_item' => __( 'Add New Coupon Image', 'appthemes'), 'new_item_name' => __( 'New Coupon Image Name', 'appthemes') ), 'public' => false, 'show_ui' => false, 'query_var' => true, 'update_count_callback' => '_update_post_term_count', 'rewrite' => array( 'slug' => $image_tax_base_url, 'with_front' => false, 'hierarchical' => false ), ) ); $wpdb->storesmeta = $wpdb->clpr_storesmeta; // this needs to happen once after install script first runs if ( get_option( $app_abbr.'_rewrite_flush_flag' ) == 'true' ) { flush_rewrite_rules(); delete_option( $app_abbr.'_rewrite_flush_flag' ); } } ``` and this is my code in the same file. ``` // new code taxonomias function clrp_taxonomy_post(){ global $wpdb, $app_abbr; //need $wpdb!! if(get_option($app_abbr.'_coupon_store_tax_permalink')) $store_tax_base_url = get_option($app_abbr.'_coupon_store_tax_permalink'); else $store_tax_base_url = 'store'; register_taxonomy( APP_TAX_STORE, // taxonomy stores array( APP_POST_TYPE_POST ), // type POST array( 'hierarchical' => true, 'labels' => array( 'name' => __( 'Stores', 'appthemes'), 'singular_name' => __( 'Store', 'appthemes'), 'search_items' => __( 'Search Stores', 'appthemes'), 'all_items' => __( 'All Stores', 'appthemes'), 'edit_item' => __( 'Edit Store', 'appthemes'), 'update_item' => __( 'Update Store', 'appthemes'), 'add_new_item' => __( 'Add New Store', 'appthemes'), 'add_or_remove_items' => __( 'Add or remove Stores', 'appthemes'), 'separate_items_with_commas' => __( 'Separate Stores with commas', 'appthemes'), 'choose_from_most_used' => __( 'Choose from the most common Stores', 'appthemes'), 'new_item_name' => __( 'New Store Name', 'appthemes') ), 'show_ui' => true, 'query_var' => true, 'update_count_callback' => '_update_post_term_count', 'rewrite' => array( 'slug' => $store_tax_base_url, 'with_front' => false, 'hierarchical' => true ), ) ); } add_action('init', 'clrp_taxonomy_post', 0); ``` this last code just show in post but not in coupons, I need to this taxonomy show in post and coupons thanks for your attention.
I honestly don't know what problem you are trying to solve. It is not clear what you are trying to accomplish with this code, but: > > `echo count($the_query_partnerzy);` > > > really is counting elements in this query, but shows only 1 (weird). > And having that, I'm not able to move further than this. > > > No, its not. `WP_Query` returns an object and [`count` doesn't work on Objects, mostly.](https://stackoverflow.com/q/1314745) The actual query results are in `$the_query_partnerzy->posts` so `count($the_query_partnerzy)` would give you what you want, but the `WP_Query` object already provides that data for you. Use `$the_query_partnerzy->found_posts` instead. I cleaned up your code a bit, and this does work using the 'post' post type (so I could run the code and test it): ``` $catArgs = array( 'type' => 'post', 'child_of' => 0, 'parent' => '', 'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => 1, 'hierarchical' => 1, 'exclude' => '', 'include' => '', 'number' => '', 'taxonomy' => 'category', 'pad_counts' => false ); $categoryList = get_categories( $catArgs ); echo 'Sum: '.count($categoryList); $i = 0;// debugging ? for ($categoryList as $catl) { echo '<br>Number of loop: ' . $i; // debugging ? echo '<br>Category name: ' . $catl->name; $the_query_partnerzy = new WP_Query( array( 'post_type' =>'post', 'category_name' => $catl->name ) ); echo $the_query_partnerzy->found_posts; // debugging ? if ($the_query_partnerzy->have_posts()) { echo 'I got it!'; // debugging ? echo '<div class="post-list container">'; echo '<p class="post-title">'. $catl->name .'</p>'; while ($the_query_partnerzy->have_posts()) { $the_query_partnerzy->the_post(); echo the_post_thumbnail(); } // while echo '</div>'; } // query partnerzy $i++; // debugging ? } ``` A few notes: 1. The lines marked `// debugging ?` most certainly should be removed. 2. The type of `for` loop you are using, while valid, is rarely necessary in PHP. There is a much more convenient `foreach`, and that `for` loop was causing some errors as (for reasons I have not investigated) the array given back by `get_categories()` started with `1` and not `0`. With `foreach` you don't have to worry about that. 3. You were missing quotes in your query arguments. That is, this: ``` $the_query_partnerzy = new WP_Query( array( post_type => 'post', category_name => $catl->name ) ); ``` Instead of this: ``` $the_query_partnerzy = new WP_Query( array( 'post_type' => 'post', 'category_name' => $catl->name ) ); ``` While that should have worked it was spitting out warning like crazy. 4. You are pulling categories from the `post` post type, but later are trying to pull posts from a different post type having those categories. Are you sure that the categories are registered for both post types and that there are in fact posts that fit that logic? That said, the code is good and works for me.
210,044
<p>I have created a way of choosing different layouts for posts(sidebar right, sidebar left, full width). This is done through a meta box that displays radio buttons with an image for each layout type. When I, for example, select the first layout image single.php file is loaded, when I chose the second image single-template-1.php file is loaded and when I chose the third image single-template-2.php is loaded.</p> <p>Now, this all works well, but I can't stop thinking that this might be a messy approach as the only difference between the 3 single templates is that single-template-1.php displays the sidebar on the left and single-template-2.php doesn't display sidebar at all. </p> <p>I am just wondering if this is the way to go about it or if there is a way to incorporate this functionality in just one single.php file which could be a cleaner solution.</p> <p><strong>meta box code which is responsible for loading the different single templates:</strong></p> <pre><code>&lt;?php function my_theme_add_meta_box_post_template_switcher() { add_meta_box( 'my_theme-post-layout', __( 'Post template', 'my_theme' ), 'my_theme_show_post_template_switcher', 'post', 'normal', 'high' ); } add_action( 'add_meta_boxes', 'my_theme_add_meta_box_post_template_switcher' ); function my_theme_show_post_template_switcher( $post ) { $template = get_post_meta( $post-&gt;ID, '_my_theme_post_template', true ); // Default template for new posts if( empty( $template ) ) { $template = 'default'; } wp_nonce_field( 'save_post_template', 'post_template' ); ?&gt; &lt;fieldset class="clearfix"&gt; &lt;div class="post-layout"&gt; &lt;label for="default-post" id="default-post-layout"&gt; &lt;input type="radio" id="default-post" name="_my_theme_post_template" value="default" &lt;?php checked( $template, 'default' ); ?&gt; /&gt; &lt;img width="150" height="100" src="&lt;?php echo get_template_directory_uri(); ?&gt;/admin/images/default.png" &gt; &lt;span&gt; &lt;?php _e( 'Default', 'my_theme' ); ?&gt; &lt;/span&gt; &lt;/label&gt; &lt;/div&gt; &lt;div class="post-layout"&gt; &lt;label for="sidebar-left-post"&gt; &lt;input type="radio" id="sidebar-left-post" name="_my_theme_post_template" value="template-1" &lt;?php checked( $template, 'template-1' ); ?&gt; /&gt; &lt;img width="150" height="100" src="&lt;?php echo get_template_directory_uri(); ?&gt;/admin/images/left-sidebar.png" &gt; &lt;span&gt; &lt;?php _e( 'Sidebar left', 'my_theme' ); ?&gt; &lt;/span&gt; &lt;/label&gt; &lt;/div&gt; &lt;div class="post-layout"&gt; &lt;label for="full-width-post"&gt; &lt;input type="radio" id="full-width-post" name="_my_theme_post_template" value="template-2" &lt;?php checked( $template, 'template-2' ); ?&gt; /&gt; &lt;img width="150" height="100" src="&lt;?php echo get_template_directory_uri(); ?&gt;/admin/images/full-width-layout.png" &gt; &lt;span&gt; &lt;?php _e( 'Full width', 'my_theme' ); ?&gt; &lt;/span&gt; &lt;/label&gt; &lt;/div&gt; &lt;/fieldset&gt; &lt;?php } function my_theme_save_post_template( $post_id ) { if( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) { return; } if( !isset( $_POST['post_template'] ) || !wp_verify_nonce( $_POST['post_template'], 'save_post_template' ) ) { return; } if( !current_user_can( 'edit_post' ) ) { return; } if( isset( $_POST['_my_theme_post_template'] ) ) { update_post_meta( $post_id, '_my_theme_post_template', esc_attr( strip_tags( $_POST['_my_theme_post_template'] ) ) ); } } add_action( 'save_post', 'my_theme_save_post_template' ); function my_theme_get_post_template_for_template_loader( $template ) { $post = get_queried_object(); if ( $post ) { $post_template = get_post_meta( $post-&gt;ID, '_my_theme_post_template', true ); if ( !empty( $post_template) &amp;&amp; $post_template != 'default' ) { $template = get_stylesheet_directory() . "/single-{$post_template}.php"; } } return $template; } </code></pre> <p><strong>My single.php file:</strong></p> <pre><code>&lt;?php get_header(); ?&gt; &lt;div class="main-content col-md-8" role="main"&gt; &lt;?php while (have_posts()) : the_post(); ?&gt; &lt;?php get_template_part( 'content', get_post_format() ); ?&gt; &lt;?php comments_template(); ?&gt; &lt;?php endwhile; ?&gt; &lt;/div&gt; &lt;!-- end .main-content --&gt; &lt;?php get_sidebar(); ?&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p><strong>My single-template-1.php, the sidebar left template:</strong></p> <pre><code>&lt;?php get_header(); ?&gt; &lt;?php get_sidebar(); ?&gt; &lt;div class="main-content col-md-8" role="main"&gt; &lt;?php while (have_posts()) : the_post(); ?&gt; &lt;?php get_template_part( 'content', get_post_format() ); ?&gt; &lt;?php comments_template(); ?&gt; &lt;?php endwhile; ?&gt; &lt;/div&gt; &lt;!-- end .main-content --&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p><strong>My single-template-2.php, full width template:</strong></p> <pre><code>&lt;?php get_header(); ?&gt; &lt;div class="main-content col-md-12" role="main"&gt; &lt;?php while (have_posts()) : the_post(); ?&gt; &lt;?php get_template_part( 'content', get_post_format() ); ?&gt; &lt;?php comments_template(); ?&gt; &lt;?php endwhile; ?&gt; &lt;/div&gt; &lt;!-- end .main-content --&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>I am just wondering if this is a good approach or if there is a better way.</p>
[ { "answer_id": 210051, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>The differences does not seem to be big enough to make it worth 3 different templates.</p>\n\n<p>You can probably just use the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/body_class\" rel=\"nofollow\">body_class</a> filter to add a class based on the meta and adjust the CSS to hide or show the sidebar at a specific location based on the class.</p>\n" }, { "answer_id": 304398, "author": "Abhik", "author_id": 26991, "author_profile": "https://wordpress.stackexchange.com/users/26991", "pm_score": 0, "selected": false, "text": "<p>You won't need three template files, just one will do. Save your meta value as class names. For example, default value as <code>col-md-8</code>, left sidebar as <code>col-md-8 pull-right</code> and full width as <code>col-xs-12</code>. </p>\n\n<p>Then a function to echo the classes to main content div. </p>\n\n<pre><code>function wpse_210044_layout_classes() {\n global $post;\n $template = get_post_meta( $post-&gt;ID, '_my_theme_post_template', true );\n\n esc_attr_e( $template );\n\n //Or you can just compare the existing values and echo relavant classes.\n //In that case, you don't need to save the meta value as class names.\n}\n</code></pre>\n\n<p>Then at single.php</p>\n\n<pre><code>&lt;?php get_header(); ?&gt;\n\n&lt;div class=\"main-content &lt;?php wpse_210044_layout_classes();?&gt;\" role=\"main\"&gt;\n\n &lt;?php while (have_posts()) : the_post(); ?&gt;\n\n &lt;?php get_template_part( 'content', get_post_format() ); ?&gt;\n\n &lt;?php comments_template(); ?&gt;\n &lt;?php endwhile; ?&gt;\n&lt;/div&gt; &lt;!-- end .main-content --&gt;\n\n\n&lt;?php get_sidebar(); ?&gt;\n&lt;?php get_footer(); ?&gt;\n</code></pre>\n" } ]
2015/11/27
[ "https://wordpress.stackexchange.com/questions/210044", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82982/" ]
I have created a way of choosing different layouts for posts(sidebar right, sidebar left, full width). This is done through a meta box that displays radio buttons with an image for each layout type. When I, for example, select the first layout image single.php file is loaded, when I chose the second image single-template-1.php file is loaded and when I chose the third image single-template-2.php is loaded. Now, this all works well, but I can't stop thinking that this might be a messy approach as the only difference between the 3 single templates is that single-template-1.php displays the sidebar on the left and single-template-2.php doesn't display sidebar at all. I am just wondering if this is the way to go about it or if there is a way to incorporate this functionality in just one single.php file which could be a cleaner solution. **meta box code which is responsible for loading the different single templates:** ``` <?php function my_theme_add_meta_box_post_template_switcher() { add_meta_box( 'my_theme-post-layout', __( 'Post template', 'my_theme' ), 'my_theme_show_post_template_switcher', 'post', 'normal', 'high' ); } add_action( 'add_meta_boxes', 'my_theme_add_meta_box_post_template_switcher' ); function my_theme_show_post_template_switcher( $post ) { $template = get_post_meta( $post->ID, '_my_theme_post_template', true ); // Default template for new posts if( empty( $template ) ) { $template = 'default'; } wp_nonce_field( 'save_post_template', 'post_template' ); ?> <fieldset class="clearfix"> <div class="post-layout"> <label for="default-post" id="default-post-layout"> <input type="radio" id="default-post" name="_my_theme_post_template" value="default" <?php checked( $template, 'default' ); ?> /> <img width="150" height="100" src="<?php echo get_template_directory_uri(); ?>/admin/images/default.png" > <span> <?php _e( 'Default', 'my_theme' ); ?> </span> </label> </div> <div class="post-layout"> <label for="sidebar-left-post"> <input type="radio" id="sidebar-left-post" name="_my_theme_post_template" value="template-1" <?php checked( $template, 'template-1' ); ?> /> <img width="150" height="100" src="<?php echo get_template_directory_uri(); ?>/admin/images/left-sidebar.png" > <span> <?php _e( 'Sidebar left', 'my_theme' ); ?> </span> </label> </div> <div class="post-layout"> <label for="full-width-post"> <input type="radio" id="full-width-post" name="_my_theme_post_template" value="template-2" <?php checked( $template, 'template-2' ); ?> /> <img width="150" height="100" src="<?php echo get_template_directory_uri(); ?>/admin/images/full-width-layout.png" > <span> <?php _e( 'Full width', 'my_theme' ); ?> </span> </label> </div> </fieldset> <?php } function my_theme_save_post_template( $post_id ) { if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } if( !isset( $_POST['post_template'] ) || !wp_verify_nonce( $_POST['post_template'], 'save_post_template' ) ) { return; } if( !current_user_can( 'edit_post' ) ) { return; } if( isset( $_POST['_my_theme_post_template'] ) ) { update_post_meta( $post_id, '_my_theme_post_template', esc_attr( strip_tags( $_POST['_my_theme_post_template'] ) ) ); } } add_action( 'save_post', 'my_theme_save_post_template' ); function my_theme_get_post_template_for_template_loader( $template ) { $post = get_queried_object(); if ( $post ) { $post_template = get_post_meta( $post->ID, '_my_theme_post_template', true ); if ( !empty( $post_template) && $post_template != 'default' ) { $template = get_stylesheet_directory() . "/single-{$post_template}.php"; } } return $template; } ``` **My single.php file:** ``` <?php get_header(); ?> <div class="main-content col-md-8" role="main"> <?php while (have_posts()) : the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> <?php comments_template(); ?> <?php endwhile; ?> </div> <!-- end .main-content --> <?php get_sidebar(); ?> <?php get_footer(); ?> ``` **My single-template-1.php, the sidebar left template:** ``` <?php get_header(); ?> <?php get_sidebar(); ?> <div class="main-content col-md-8" role="main"> <?php while (have_posts()) : the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> <?php comments_template(); ?> <?php endwhile; ?> </div> <!-- end .main-content --> <?php get_footer(); ?> ``` **My single-template-2.php, full width template:** ``` <?php get_header(); ?> <div class="main-content col-md-12" role="main"> <?php while (have_posts()) : the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> <?php comments_template(); ?> <?php endwhile; ?> </div> <!-- end .main-content --> <?php get_footer(); ?> ``` I am just wondering if this is a good approach or if there is a better way.
The differences does not seem to be big enough to make it worth 3 different templates. You can probably just use the [body\_class](https://codex.wordpress.org/Plugin_API/Filter_Reference/body_class) filter to add a class based on the meta and adjust the CSS to hide or show the sidebar at a specific location based on the class.
210,064
<p>I would like to hide this particular taxonomy box in the admin on the add new post page.</p> <p><a href="https://i.stack.imgur.com/YUsbG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YUsbG.jpg" alt="enter image description here"></a></p>
[ { "answer_id": 210068, "author": "jas", "author_id": 80247, "author_profile": "https://wordpress.stackexchange.com/users/80247", "pm_score": 0, "selected": false, "text": "<p>Hi I assume its your meta box while adding new post:</p>\n\n<p>Please go to <code>http://www.example.com/wp-admin/post-new.php</code> and there are screen options at top of new post form like screenshot where you can hide things according to available options. </p>\n\n<p><a href=\"https://i.stack.imgur.com/IjfSF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IjfSF.png\" alt=\"enter image description here\"></a></p>\n\n<p>You can uncheck things you don't want in post form.</p>\n\n<p>We can remove by codes as well, please follow this helpful post for details:</p>\n\n<p><a href=\"https://premium.wpmudev.org/blog/remove-wordpress-meta-boxes/\" rel=\"nofollow noreferrer\"><em>Remove Wordpress Meta Boxes</em> - WPMUDev.org</a></p>\n" }, { "answer_id": 210075, "author": "Andrew Welch", "author_id": 17862, "author_profile": "https://wordpress.stackexchange.com/users/17862", "pm_score": 2, "selected": true, "text": "<p>The following worked for me in functions.php</p>\n\n<pre><code>/**\n * [remove_meta_boxes remove the resource type standard meta box from the side sortables in the resource post edit screen\n * @return [type] [description]\n */\nfunction remove_meta_boxes(){\nremove_meta_box( 'resourcetypesdiv', 'resource','side' );\n}\nadd_action( 'admin_menu', __NAMESPACE__ . '\\\\remove_meta_boxes');\n</code></pre>\n" } ]
2015/11/27
[ "https://wordpress.stackexchange.com/questions/210064", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17862/" ]
I would like to hide this particular taxonomy box in the admin on the add new post page. [![enter image description here](https://i.stack.imgur.com/YUsbG.jpg)](https://i.stack.imgur.com/YUsbG.jpg)
The following worked for me in functions.php ``` /** * [remove_meta_boxes remove the resource type standard meta box from the side sortables in the resource post edit screen * @return [type] [description] */ function remove_meta_boxes(){ remove_meta_box( 'resourcetypesdiv', 'resource','side' ); } add_action( 'admin_menu', __NAMESPACE__ . '\\remove_meta_boxes'); ```
210,069
<p>For testing purposes I keep short time intervals for cron and when the functionality is working fine, I change it to the required time interval. Whenever I change the time intervals for ex: from 'three_days' to 'five_minutes' or from 'five_minutes' to 'fifteen_minutes', the cron is running with earlier frequency and not the updated one. I'm totally confused with this. Even after setting new intervals, cron function runs on previous time intervals only.</p> <p>What might be the reason for this, kindly help me out on this.</p> <p>This is my code:</p> <pre><code>add_filter('cron_schedules', 'filter_cron_schedules'); function filter_cron_schedules($schedules) { $schedules['fifteen_minutes'] = array( 'interval' =&gt; 900, // seconds 'display' =&gt; __('Every 15 minutes') ); $schedules['twenty_minutes'] = array( 'interval' =&gt; 1200, // seconds 'display' =&gt; __('Every 20 minutes') ); $schedules['three_days'] = array( 'interval' =&gt; 259200, // seconds 'display' =&gt; __('Every 3 days') ); $schedules['five_minutes'] = array( 'interval' =&gt; 300, // seconds 'display' =&gt; __('Every 5 minutes') ); return $schedules; } // Schedule the cron add_action('wp', 'bd_cron_activation'); function bd_cron_activation() { if (!wp_next_scheduled('bd_cron_cache')) { wp_schedule_event(time(), 'twenty_minutes', 'bd_cron_cache'); // hourly, daily, twicedaily } } // Firing the function add_action('bd_cron_cache', 'bd_data'); function bd_data() { // My Logic } </code></pre>
[ { "answer_id": 210074, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 2, "selected": true, "text": "<blockquote>\n<p>Whenever I change the time intervals for ex: from 'three_days' to 'five_minutes' or from 'five_minutes' to 'fifteen_minutes', the cron is running with earlier frequency and not the updated one.</p>\n</blockquote>\n<p>Because you only reschedule the event if it does not exist:</p>\n<pre><code>if ( ! wp_next_scheduled( 'bd_cron_cache' ) ) {\n // schedule\n}\n</code></pre>\n<p>...which will always be <code>false</code> once you initially schedule the event. Instead, check the stored task's schedule against the value you actually want it to be:</p>\n<pre><code>if ( wp_get_schedule( 'bd_cron_cache' ) !== 'twenty_minutes' ) {\n // Above statement will also be true if NO schedule exists, so here we check and unschedule if required\n if ( $time = wp_next_schedule( 'bd_cron_cache' ) ) {\n wp_unschedule_event( $time, 'bd_cron_cache' );\n }\n wp_schedule_event( time(), 'bd_cron_cache', 'twenty_minutes' );\n}\n</code></pre>\n" }, { "answer_id": 211247, "author": "immazharkhan", "author_id": 84378, "author_profile": "https://wordpress.stackexchange.com/users/84378", "pm_score": 0, "selected": false, "text": "<pre><code>// Custom Cron Schedules\nadd_filter('cron_schedules', 'filter_cron_schedules');\nfunction filter_cron_schedules($schedules) {\n $schedules['two_minutes'] = array(\n 'interval' =&gt; 120, // seconds\n 'display' =&gt; __('Every 2 minutes') \n );\n $schedules['twenty_minutes'] = array(\n 'interval' =&gt; 1200, // seconds\n 'display' =&gt; __('Every 20 minutes') \n );\n return $schedules;\n}\n\n// Schedule the cron\nadd_action('wp', 'bd_cron_activation');\nfunction bd_cron_activation() {\n if ( wp_get_schedule('bd_cron_cache') !== 'two_minutes' ) {\n // Above statement will also be true if NO schedule exists, so here we check and unschedule if required\n if ( $time = wp_next_scheduled('bd_cron_cache'))\n wp_unschedule_event($time, 'bd_cron_cache');\n\n wp_schedule_event(time(),'two_minutes','bd_cron_cache'); \n }\n}\n\n// Firing the function\nadd_action('bd_cron_cache', 'bd_data');\nfunction bd_data() {\n // My Logic\n}\n</code></pre>\n" } ]
2015/11/27
[ "https://wordpress.stackexchange.com/questions/210069", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84378/" ]
For testing purposes I keep short time intervals for cron and when the functionality is working fine, I change it to the required time interval. Whenever I change the time intervals for ex: from 'three\_days' to 'five\_minutes' or from 'five\_minutes' to 'fifteen\_minutes', the cron is running with earlier frequency and not the updated one. I'm totally confused with this. Even after setting new intervals, cron function runs on previous time intervals only. What might be the reason for this, kindly help me out on this. This is my code: ``` add_filter('cron_schedules', 'filter_cron_schedules'); function filter_cron_schedules($schedules) { $schedules['fifteen_minutes'] = array( 'interval' => 900, // seconds 'display' => __('Every 15 minutes') ); $schedules['twenty_minutes'] = array( 'interval' => 1200, // seconds 'display' => __('Every 20 minutes') ); $schedules['three_days'] = array( 'interval' => 259200, // seconds 'display' => __('Every 3 days') ); $schedules['five_minutes'] = array( 'interval' => 300, // seconds 'display' => __('Every 5 minutes') ); return $schedules; } // Schedule the cron add_action('wp', 'bd_cron_activation'); function bd_cron_activation() { if (!wp_next_scheduled('bd_cron_cache')) { wp_schedule_event(time(), 'twenty_minutes', 'bd_cron_cache'); // hourly, daily, twicedaily } } // Firing the function add_action('bd_cron_cache', 'bd_data'); function bd_data() { // My Logic } ```
> > Whenever I change the time intervals for ex: from 'three\_days' to 'five\_minutes' or from 'five\_minutes' to 'fifteen\_minutes', the cron is running with earlier frequency and not the updated one. > > > Because you only reschedule the event if it does not exist: ``` if ( ! wp_next_scheduled( 'bd_cron_cache' ) ) { // schedule } ``` ...which will always be `false` once you initially schedule the event. Instead, check the stored task's schedule against the value you actually want it to be: ``` if ( wp_get_schedule( 'bd_cron_cache' ) !== 'twenty_minutes' ) { // Above statement will also be true if NO schedule exists, so here we check and unschedule if required if ( $time = wp_next_schedule( 'bd_cron_cache' ) ) { wp_unschedule_event( $time, 'bd_cron_cache' ); } wp_schedule_event( time(), 'bd_cron_cache', 'twenty_minutes' ); } ```
210,071
<p>So basically I need to access the value of checked() in order to load diferent template parts in my single.php file.</p> <p>This is my meta box:</p> <pre><code>&lt;?php function my_theme_add_meta_box_post_template_switcher() { dd_meta_box( 'my_theme-post-layout', __( 'Post template', 'my_theme' ), 'my_theme_show_post_template_switcher', 'post', 'normal', 'high' ); } add_action( 'add_meta_boxes', 'my_theme_add_meta_box_post_template_switcher'); function my_theme_show_post_template_switcher( $post ) { $template = get_post_meta( $post-&gt;ID, '_my_theme_post_template', true ); // Default template for new posts if( empty( $template ) ) { $template = 'default'; } wp_nonce_field( 'save_post_template', 'post_template' ); ?&gt; &lt;fieldset class="clearfix"&gt; &lt;div class="post-layout"&gt; &lt;label for="sidebar-left-post"&gt; &lt;input type="radio" id="sidebar-left-post" name="_my_theme_post_template" value="template-1" &lt;?php checked( $template, 'template-1' ); ?&gt; /&gt; &lt;img width="150" height="100" src="&lt;?php echo get_template_directory_uri(); ?&gt;/admin/images/left-sidebar.png" &gt; &lt;span&gt; &lt;?php _e( 'Sidebar left', 'my_theme' ); ?&gt; &lt;/span&gt; &lt;/label&gt; &lt;/div&gt; &lt;div class="post-layout"&gt; &lt;label for="full-width-post"&gt; &lt;input type="radio" id="full-width-post" name="_my_theme_post_template" value="template-2" &lt;?php checked( $template, 'template-2' ); ?&gt; /&gt; &lt;img width="150" height="100" src="&lt;?php echo get_template_directory_uri(); ?&gt;/admin/images/full-width-layout.png" &gt; &lt;span&gt; &lt;?php _e( 'Full width', 'my_theme' ); ?&gt; &lt;/span&gt; &lt;/label&gt; &lt;/div&gt; &lt;/fieldset&gt; &lt;?php } function my_theme_save_post_template( $post_id ) { if( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) { return; } if( !isset( $_POST['post_template'] ) || !wp_verify_nonce( $_POST['post_template'], 'save_post_template' ) ) { return; } if( !current_user_can( 'edit_post' ) ) { return; } if( isset( $_POST['_my_theme_post_template'] ) ) { update_post_meta( $post_id, '_my_theme_post_template', esc_attr( strip_tags( $_POST['_my_theme_post_template'] ) ) ); } } add_action( 'save_post', 'my_theme_save_post_template' ); function my_theme_get_post_template_for_template_loader( $template ) { $post = get_queried_object(); if ( $post ) { $template = get_stylesheet_directory() . "/single.php"; } return $template; } </code></pre> <p>Now I need to access the checked() values so in my single.php I can load different parts according to the value checked() has, like so:</p> <pre><code> switch ( $checked ) { case checked( $template, 'template-1' ): get_template_part( 'inc/post-loops/template-1' ); break; case checked( $template, 'template-2' ) : get_template_part( 'inc/post-loops/template-2' ); default: get_template_part( 'inc/post-loops/template-1' ); break; } </code></pre>
[ { "answer_id": 210074, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 2, "selected": true, "text": "<blockquote>\n<p>Whenever I change the time intervals for ex: from 'three_days' to 'five_minutes' or from 'five_minutes' to 'fifteen_minutes', the cron is running with earlier frequency and not the updated one.</p>\n</blockquote>\n<p>Because you only reschedule the event if it does not exist:</p>\n<pre><code>if ( ! wp_next_scheduled( 'bd_cron_cache' ) ) {\n // schedule\n}\n</code></pre>\n<p>...which will always be <code>false</code> once you initially schedule the event. Instead, check the stored task's schedule against the value you actually want it to be:</p>\n<pre><code>if ( wp_get_schedule( 'bd_cron_cache' ) !== 'twenty_minutes' ) {\n // Above statement will also be true if NO schedule exists, so here we check and unschedule if required\n if ( $time = wp_next_schedule( 'bd_cron_cache' ) ) {\n wp_unschedule_event( $time, 'bd_cron_cache' );\n }\n wp_schedule_event( time(), 'bd_cron_cache', 'twenty_minutes' );\n}\n</code></pre>\n" }, { "answer_id": 211247, "author": "immazharkhan", "author_id": 84378, "author_profile": "https://wordpress.stackexchange.com/users/84378", "pm_score": 0, "selected": false, "text": "<pre><code>// Custom Cron Schedules\nadd_filter('cron_schedules', 'filter_cron_schedules');\nfunction filter_cron_schedules($schedules) {\n $schedules['two_minutes'] = array(\n 'interval' =&gt; 120, // seconds\n 'display' =&gt; __('Every 2 minutes') \n );\n $schedules['twenty_minutes'] = array(\n 'interval' =&gt; 1200, // seconds\n 'display' =&gt; __('Every 20 minutes') \n );\n return $schedules;\n}\n\n// Schedule the cron\nadd_action('wp', 'bd_cron_activation');\nfunction bd_cron_activation() {\n if ( wp_get_schedule('bd_cron_cache') !== 'two_minutes' ) {\n // Above statement will also be true if NO schedule exists, so here we check and unschedule if required\n if ( $time = wp_next_scheduled('bd_cron_cache'))\n wp_unschedule_event($time, 'bd_cron_cache');\n\n wp_schedule_event(time(),'two_minutes','bd_cron_cache'); \n }\n}\n\n// Firing the function\nadd_action('bd_cron_cache', 'bd_data');\nfunction bd_data() {\n // My Logic\n}\n</code></pre>\n" } ]
2015/11/27
[ "https://wordpress.stackexchange.com/questions/210071", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82982/" ]
So basically I need to access the value of checked() in order to load diferent template parts in my single.php file. This is my meta box: ``` <?php function my_theme_add_meta_box_post_template_switcher() { dd_meta_box( 'my_theme-post-layout', __( 'Post template', 'my_theme' ), 'my_theme_show_post_template_switcher', 'post', 'normal', 'high' ); } add_action( 'add_meta_boxes', 'my_theme_add_meta_box_post_template_switcher'); function my_theme_show_post_template_switcher( $post ) { $template = get_post_meta( $post->ID, '_my_theme_post_template', true ); // Default template for new posts if( empty( $template ) ) { $template = 'default'; } wp_nonce_field( 'save_post_template', 'post_template' ); ?> <fieldset class="clearfix"> <div class="post-layout"> <label for="sidebar-left-post"> <input type="radio" id="sidebar-left-post" name="_my_theme_post_template" value="template-1" <?php checked( $template, 'template-1' ); ?> /> <img width="150" height="100" src="<?php echo get_template_directory_uri(); ?>/admin/images/left-sidebar.png" > <span> <?php _e( 'Sidebar left', 'my_theme' ); ?> </span> </label> </div> <div class="post-layout"> <label for="full-width-post"> <input type="radio" id="full-width-post" name="_my_theme_post_template" value="template-2" <?php checked( $template, 'template-2' ); ?> /> <img width="150" height="100" src="<?php echo get_template_directory_uri(); ?>/admin/images/full-width-layout.png" > <span> <?php _e( 'Full width', 'my_theme' ); ?> </span> </label> </div> </fieldset> <?php } function my_theme_save_post_template( $post_id ) { if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } if( !isset( $_POST['post_template'] ) || !wp_verify_nonce( $_POST['post_template'], 'save_post_template' ) ) { return; } if( !current_user_can( 'edit_post' ) ) { return; } if( isset( $_POST['_my_theme_post_template'] ) ) { update_post_meta( $post_id, '_my_theme_post_template', esc_attr( strip_tags( $_POST['_my_theme_post_template'] ) ) ); } } add_action( 'save_post', 'my_theme_save_post_template' ); function my_theme_get_post_template_for_template_loader( $template ) { $post = get_queried_object(); if ( $post ) { $template = get_stylesheet_directory() . "/single.php"; } return $template; } ``` Now I need to access the checked() values so in my single.php I can load different parts according to the value checked() has, like so: ``` switch ( $checked ) { case checked( $template, 'template-1' ): get_template_part( 'inc/post-loops/template-1' ); break; case checked( $template, 'template-2' ) : get_template_part( 'inc/post-loops/template-2' ); default: get_template_part( 'inc/post-loops/template-1' ); break; } ```
> > Whenever I change the time intervals for ex: from 'three\_days' to 'five\_minutes' or from 'five\_minutes' to 'fifteen\_minutes', the cron is running with earlier frequency and not the updated one. > > > Because you only reschedule the event if it does not exist: ``` if ( ! wp_next_scheduled( 'bd_cron_cache' ) ) { // schedule } ``` ...which will always be `false` once you initially schedule the event. Instead, check the stored task's schedule against the value you actually want it to be: ``` if ( wp_get_schedule( 'bd_cron_cache' ) !== 'twenty_minutes' ) { // Above statement will also be true if NO schedule exists, so here we check and unschedule if required if ( $time = wp_next_schedule( 'bd_cron_cache' ) ) { wp_unschedule_event( $time, 'bd_cron_cache' ); } wp_schedule_event( time(), 'bd_cron_cache', 'twenty_minutes' ); } ```
210,097
<p>I'm looking for option to change language_attributes manually without hardcoding it like </p> <pre><code>html lang="en-US" </code></pre> <p>in html it self. The reason for this is I have three language site, using same WP engine and I want one and each of them run with specific lang attribute. Is this possible? It would be nice to have something like this to change it:</p> <pre><code>&lt;?php language_attributes('lang="en-US"'); ?&gt; </code></pre>
[ { "answer_id": 210101, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": false, "text": "<p>You can use a filter to modify the value before it is set</p>\n\n<pre><code>function __language_attributes($lang){\n\n // ignore the supplied argument\n $langs = array( 'en-US', 'KO', 'JA' );\n\n // change to whatever you want\n $my_language = $langs[0];\n\n // return the new attribute\n return 'lang=\"'.$my_language.'\"';\n}\n\nadd_filter('language_attributes', '__language_attributes');\n</code></pre>\n\n<p>Then just make sure your theme header has the correct php function</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html &lt;?php language_attributes(); ?&gt; class=\"no-js\"&gt;\n&lt;head&gt;\n</code></pre>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/language_attributes\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/language_attributes</a></li>\n</ul>\n\n<p>Another approach would be to set the language in a global variable before the filter is called.</p>\n\n<pre><code>// Make this variable global\nglobal $__language_attribute;\n\n// Set the language we want to use\n$__language_attribute = 'en-US'; \n\n// Listen for the language filter\nadd_filter('language_attributes', '__language_attributes_use_global');\n\nfunction __language_attributes_use_global($lang){\n global $__language_attribute;\n return \"lang=\\\"$__language_attribute\\\"\";\n}\n</code></pre>\n\n<p><strong>ALTERNATE</strong></p>\n\n<pre><code>// set your language here\n$my_lang = 'KO';\n\n// subscribe with closure to apply this value later\nadd_filter('language_attributes', function($lang) use ($my_lang) {\n return 'lang=\"' . $my_lang . '\"'; \n});\n</code></pre>\n" }, { "answer_id": 409993, "author": "mirazimi", "author_id": 226237, "author_profile": "https://wordpress.stackexchange.com/users/226237", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;html &lt;?php language_attributes(); ?&gt;&gt;\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/iDgrY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iDgrY.png\" alt=\"enter image description here\" /></a></p>\n" } ]
2015/11/27
[ "https://wordpress.stackexchange.com/questions/210097", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84388/" ]
I'm looking for option to change language\_attributes manually without hardcoding it like ``` html lang="en-US" ``` in html it self. The reason for this is I have three language site, using same WP engine and I want one and each of them run with specific lang attribute. Is this possible? It would be nice to have something like this to change it: ``` <?php language_attributes('lang="en-US"'); ?> ```
You can use a filter to modify the value before it is set ``` function __language_attributes($lang){ // ignore the supplied argument $langs = array( 'en-US', 'KO', 'JA' ); // change to whatever you want $my_language = $langs[0]; // return the new attribute return 'lang="'.$my_language.'"'; } add_filter('language_attributes', '__language_attributes'); ``` Then just make sure your theme header has the correct php function ``` <!DOCTYPE html> <html <?php language_attributes(); ?> class="no-js"> <head> ``` * <https://codex.wordpress.org/Function_Reference/language_attributes> Another approach would be to set the language in a global variable before the filter is called. ``` // Make this variable global global $__language_attribute; // Set the language we want to use $__language_attribute = 'en-US'; // Listen for the language filter add_filter('language_attributes', '__language_attributes_use_global'); function __language_attributes_use_global($lang){ global $__language_attribute; return "lang=\"$__language_attribute\""; } ``` **ALTERNATE** ``` // set your language here $my_lang = 'KO'; // subscribe with closure to apply this value later add_filter('language_attributes', function($lang) use ($my_lang) { return 'lang="' . $my_lang . '"'; }); ```
210,099
<p>I have a multilingual site setup: www.jeroenbrugman.com</p> <p>The main dutch version uses Fluxus. On the artwork page I output a link using this from Functions.php</p> <pre><code>function prefix_term_name($terms, $post_id, $taxonomy ) { foreach ($terms as &amp;$term) { $term-&gt;name = 'Terug naar '.$term-&gt;name; } } return $terms; </code></pre> <p>And on the page itself I show it using this:</p> <pre><code> &lt;h3 class="widget-title"&gt; &lt;?php add_filter( 'get_the_terms','prefix_term_name',10,3); the_terms($post-&gt;ID, 'fluxus-project-type'); remove_filter( 'get_the_terms','prefix_term_name',10,3); ?&gt; &lt;a href="../"&gt;&lt;?php the_terms($post-&gt;ID, 'fluxus-project-type'); ?&gt;&lt;/a&gt;&lt;/h3&gt; </code></pre> <p>But, on my English page. I need to output the 'Terug naar' from the main theme function.php as: 'Back To'. but when I copy the code from main functions.php to my child theme's functions.php and change Terug naar to Back to the whole english site goes blank.</p> <p>What am I doing wrong?</p> <p>Kind regards</p>
[ { "answer_id": 210102, "author": "Abhik", "author_id": 26991, "author_profile": "https://wordpress.stackexchange.com/users/26991", "pm_score": 2, "selected": true, "text": "<p>You need to make the function pluggable, that means, to support child themes, the functions in parent theme should use: </p>\n\n<pre><code>if ( !function_exists( 'function_name' )) {\n function function_name() {\n //Stuffs\n }\n} \n</code></pre>\n\n<p>You should have seen a PHP Error message if you have <a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"nofollow\">debugging enabled</a>. </p>\n\n<p><strong>EDIT:</strong> The below code snippet if to answer your other question in comment. </p>\n\n<pre><code>function modify_read_more_link() {\n global $post;\n\n return '&lt;a class=\"more-link\" href=\"' . get_permalink( $post-&gt;ID ) . '\"&gt;Your Read More Link Text&lt;/a&gt;';\n\n}\nadd_filter( 'the_content_more_link', 'modify_read_more_link' );\n</code></pre>\n" }, { "answer_id": 210110, "author": "ginobrugman", "author_id": 83929, "author_profile": "https://wordpress.stackexchange.com/users/83929", "pm_score": 0, "selected": false, "text": "<p>Issue Fixed!</p>\n\n<p>Had to wrap my function with </p>\n\n<pre><code>if ( !function_exists( 'function_name' )) {\n function function_name() {\n //Stuffs\n }\n} \n</code></pre>\n\n<p>Perfect!</p>\n" } ]
2015/11/27
[ "https://wordpress.stackexchange.com/questions/210099", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83929/" ]
I have a multilingual site setup: www.jeroenbrugman.com The main dutch version uses Fluxus. On the artwork page I output a link using this from Functions.php ``` function prefix_term_name($terms, $post_id, $taxonomy ) { foreach ($terms as &$term) { $term->name = 'Terug naar '.$term->name; } } return $terms; ``` And on the page itself I show it using this: ``` <h3 class="widget-title"> <?php add_filter( 'get_the_terms','prefix_term_name',10,3); the_terms($post->ID, 'fluxus-project-type'); remove_filter( 'get_the_terms','prefix_term_name',10,3); ?> <a href="../"><?php the_terms($post->ID, 'fluxus-project-type'); ?></a></h3> ``` But, on my English page. I need to output the 'Terug naar' from the main theme function.php as: 'Back To'. but when I copy the code from main functions.php to my child theme's functions.php and change Terug naar to Back to the whole english site goes blank. What am I doing wrong? Kind regards
You need to make the function pluggable, that means, to support child themes, the functions in parent theme should use: ``` if ( !function_exists( 'function_name' )) { function function_name() { //Stuffs } } ``` You should have seen a PHP Error message if you have [debugging enabled](https://codex.wordpress.org/Debugging_in_WordPress). **EDIT:** The below code snippet if to answer your other question in comment. ``` function modify_read_more_link() { global $post; return '<a class="more-link" href="' . get_permalink( $post->ID ) . '">Your Read More Link Text</a>'; } add_filter( 'the_content_more_link', 'modify_read_more_link' ); ```
210,109
<p>A 3rd party plugin that I use adds a shortcode that displays a list of adverts (CPT posts). The shortcode function includes (with an <code>include</code> statement) a template - the <code>list.php</code> file, that displays a search form and, in its turn, includes a second template - the <code>list-item.php</code> file, that displays the list of adverts itself. </p> <p>Each entry of this list includes only a post thumbnail, the post title, the post date, and the price of the advertised item. By changing the list-item.php code I added also the excerpt of the post. The problem is that excerpts are displayed properly when we browse the main adverts list page and not displayed when we browse a category page. </p> <p>How the adverts list is build when we browse a category page is partially influenced by a function applied to the <code>the_content()</code> filter. The question is: <em>Why excerpts are not displayed on category pages?</em></p> <p>This is the shortcode function that displays a list of adverts (and include the list.php template):</p> <pre><code>add_shortcode('adverts_list', 'shortcode_adverts_list'); /** * Generates HTML for [adverts_list] shortcode * * @param array $atts Shorcode attributes * @since 0.1 * @return string Fully formatted HTML for adverts list */ function shortcode_adverts_list( $atts ) { wp_enqueue_style( 'adverts-frontend' ); wp_enqueue_style( 'adverts-icons' ); wp_enqueue_script( 'adverts-frontend' ); extract(shortcode_atts(array( 'name' =&gt; 'default', 'category' =&gt; null, 'columns' =&gt; 2, 'paged' =&gt; adverts_request("pg", 1), 'posts_per_page' =&gt; 20, ), $atts)); $taxonomy = null; $meta = array(); $query = adverts_request("query"); $location = adverts_request("location"); if($location) { $meta[] = array('key'=&gt;'adverts_location', 'value'=&gt;$location, 'compare'=&gt;'LIKE'); } if($category) { $taxonomy = array( array( 'taxonomy' =&gt; 'advert_category', 'field' =&gt; 'term_id', 'terms' =&gt; $category, ), ); } $loop = new WP_Query( array( 'post_type' =&gt; 'advert', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; $posts_per_page, 'paged' =&gt; $paged, 's' =&gt; $query, 'meta_query' =&gt; $meta, 'tax_query' =&gt; $taxonomy ) ); $paginate_base = get_the_permalink() . '%_%'; $paginate_format = stripos( $paginate_base, '?' ) ? '&amp;pg=%#%' : '?pg=%#%'; // adverts/templates/list.php ob_start(); include_once ADVERTS_PATH . 'templates/list.php'; return ob_get_clean(); } </code></pre> <p>This is the code of the <code>list.php</code> that includes the <code>list-item.php</code> template:</p> <pre><code>&lt;div class="adverts-list"&gt; &lt;?php if( $loop-&gt;have_posts() ): ?&gt; &lt;?php while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt; &lt;?php include ADVERTS_PATH . 'templates/list-item.php' ?&gt; &lt;?php endwhile; ?&gt; &lt;?php else: ?&gt; &lt;div class="adverts-list-empty"&gt;&lt;em&gt;&lt;?php _e("There are no ads matching your search criteria.", "adverts") ?&gt;&lt;/em&gt;&lt;/div&gt; &lt;?php endif; ?&gt; &lt;?php wp_reset_query(); ?&gt; &lt;/div&gt; </code></pre> <p>This is the full code of customized <code>list-item.php</code>:</p> <pre><code>&lt;div class="advert-item advert-item-col-&lt;?php echo (int)$columns ?&gt;"&gt; &lt;?php $image = adverts_get_main_image( get_the_ID() ) ?&gt; &lt;div class="advert-img"&gt; &lt;?php if($image): ?&gt; &lt;img src="&lt;?php esc_attr_e($image) ?&gt;" alt="" class="advert-item-grow" /&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;div class="advert-post-title"&gt; &lt;span title="&lt;?php esc_attr_e( get_the_title() ) ?&gt;" class="advert-link"&gt;&lt;?php the_title() ?&gt;&lt;/span&gt; &lt;a href="&lt;?php the_permalink() ?&gt;" title="&lt;?php esc_attr_e( get_the_title() ) ?&gt;" class="advert-link-wrap"&gt;&lt;/a&gt; &lt;/div&gt; &lt;!-- THIS IS WHAT WAS CUSTOMIZED --&gt; &lt;div class="advert-post-excerpt"&gt; &lt;span class="advert-excerpt"&gt;&lt;?php echo get_the_excerpt(); ?&gt;&lt;/span&gt; &lt;/div&gt; &lt;!-- END OF CUSTOMIZATION --&gt; &lt;div class="advert-published "&gt; &lt;span class="advert-date"&gt;&lt;?php echo date_i18n( get_option( 'date_format' ), get_post_time( 'U', false, get_the_ID() ) ) ?&gt;&lt;/span&gt; &lt;?php $price = get_post_meta( get_the_ID(), "adverts_price", true ) ?&gt; &lt;?php if( $price ): ?&gt; &lt;div class="advert-price"&gt;&lt;?php esc_html_e( adverts_price( get_post_meta( get_the_ID(), "adverts_price", true ) ) ) ?&gt;&lt;/div&gt; &lt;?php endif; ?&gt; &lt;/div&gt;fun &lt;/div&gt; </code></pre> <p>This is the function applied to the <code>the_content()</code> filter when we browse single posts and also category pages (in this case again the first shortcode function is called):</p> <pre><code>add_filter('the_content', 'adverts_the_content'); function adverts_the_content($content) { global $wp_query; if (is_singular('advert') &amp;&amp; in_the_loop() ) { ob_start(); $post_id = get_the_ID(); include ADVERTS_PATH . 'templates/single.php'; $content = ob_get_clean(); } elseif( is_tax( 'advert_category' ) &amp;&amp; in_the_loop() ) { $content = shortcode_adverts_list(array( "category" =&gt; $wp_query-&gt;get_queried_object_id() )); } return $content; } </code></pre> <p><strong>UPDATE</strong></p> <p>This is the <code>adverts_request()</code> function, called by the <code>shortcode_adverts_list()</code> function:</p> <pre><code>function adverts_request($key, $default = null) { if(isset($_POST[$key])) { return $_POST[$key]; } elseif(isset($_GET[$key])) { return $_GET[$key]; } else { return $default; } } </code></pre>
[ { "answer_id": 210102, "author": "Abhik", "author_id": 26991, "author_profile": "https://wordpress.stackexchange.com/users/26991", "pm_score": 2, "selected": true, "text": "<p>You need to make the function pluggable, that means, to support child themes, the functions in parent theme should use: </p>\n\n<pre><code>if ( !function_exists( 'function_name' )) {\n function function_name() {\n //Stuffs\n }\n} \n</code></pre>\n\n<p>You should have seen a PHP Error message if you have <a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"nofollow\">debugging enabled</a>. </p>\n\n<p><strong>EDIT:</strong> The below code snippet if to answer your other question in comment. </p>\n\n<pre><code>function modify_read_more_link() {\n global $post;\n\n return '&lt;a class=\"more-link\" href=\"' . get_permalink( $post-&gt;ID ) . '\"&gt;Your Read More Link Text&lt;/a&gt;';\n\n}\nadd_filter( 'the_content_more_link', 'modify_read_more_link' );\n</code></pre>\n" }, { "answer_id": 210110, "author": "ginobrugman", "author_id": 83929, "author_profile": "https://wordpress.stackexchange.com/users/83929", "pm_score": 0, "selected": false, "text": "<p>Issue Fixed!</p>\n\n<p>Had to wrap my function with </p>\n\n<pre><code>if ( !function_exists( 'function_name' )) {\n function function_name() {\n //Stuffs\n }\n} \n</code></pre>\n\n<p>Perfect!</p>\n" } ]
2015/11/27
[ "https://wordpress.stackexchange.com/questions/210109", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25187/" ]
A 3rd party plugin that I use adds a shortcode that displays a list of adverts (CPT posts). The shortcode function includes (with an `include` statement) a template - the `list.php` file, that displays a search form and, in its turn, includes a second template - the `list-item.php` file, that displays the list of adverts itself. Each entry of this list includes only a post thumbnail, the post title, the post date, and the price of the advertised item. By changing the list-item.php code I added also the excerpt of the post. The problem is that excerpts are displayed properly when we browse the main adverts list page and not displayed when we browse a category page. How the adverts list is build when we browse a category page is partially influenced by a function applied to the `the_content()` filter. The question is: *Why excerpts are not displayed on category pages?* This is the shortcode function that displays a list of adverts (and include the list.php template): ``` add_shortcode('adverts_list', 'shortcode_adverts_list'); /** * Generates HTML for [adverts_list] shortcode * * @param array $atts Shorcode attributes * @since 0.1 * @return string Fully formatted HTML for adverts list */ function shortcode_adverts_list( $atts ) { wp_enqueue_style( 'adverts-frontend' ); wp_enqueue_style( 'adverts-icons' ); wp_enqueue_script( 'adverts-frontend' ); extract(shortcode_atts(array( 'name' => 'default', 'category' => null, 'columns' => 2, 'paged' => adverts_request("pg", 1), 'posts_per_page' => 20, ), $atts)); $taxonomy = null; $meta = array(); $query = adverts_request("query"); $location = adverts_request("location"); if($location) { $meta[] = array('key'=>'adverts_location', 'value'=>$location, 'compare'=>'LIKE'); } if($category) { $taxonomy = array( array( 'taxonomy' => 'advert_category', 'field' => 'term_id', 'terms' => $category, ), ); } $loop = new WP_Query( array( 'post_type' => 'advert', 'post_status' => 'publish', 'posts_per_page' => $posts_per_page, 'paged' => $paged, 's' => $query, 'meta_query' => $meta, 'tax_query' => $taxonomy ) ); $paginate_base = get_the_permalink() . '%_%'; $paginate_format = stripos( $paginate_base, '?' ) ? '&pg=%#%' : '?pg=%#%'; // adverts/templates/list.php ob_start(); include_once ADVERTS_PATH . 'templates/list.php'; return ob_get_clean(); } ``` This is the code of the `list.php` that includes the `list-item.php` template: ``` <div class="adverts-list"> <?php if( $loop->have_posts() ): ?> <?php while ( $loop->have_posts() ) : $loop->the_post(); ?> <?php include ADVERTS_PATH . 'templates/list-item.php' ?> <?php endwhile; ?> <?php else: ?> <div class="adverts-list-empty"><em><?php _e("There are no ads matching your search criteria.", "adverts") ?></em></div> <?php endif; ?> <?php wp_reset_query(); ?> </div> ``` This is the full code of customized `list-item.php`: ``` <div class="advert-item advert-item-col-<?php echo (int)$columns ?>"> <?php $image = adverts_get_main_image( get_the_ID() ) ?> <div class="advert-img"> <?php if($image): ?> <img src="<?php esc_attr_e($image) ?>" alt="" class="advert-item-grow" /> <?php endif; ?> </div> <div class="advert-post-title"> <span title="<?php esc_attr_e( get_the_title() ) ?>" class="advert-link"><?php the_title() ?></span> <a href="<?php the_permalink() ?>" title="<?php esc_attr_e( get_the_title() ) ?>" class="advert-link-wrap"></a> </div> <!-- THIS IS WHAT WAS CUSTOMIZED --> <div class="advert-post-excerpt"> <span class="advert-excerpt"><?php echo get_the_excerpt(); ?></span> </div> <!-- END OF CUSTOMIZATION --> <div class="advert-published "> <span class="advert-date"><?php echo date_i18n( get_option( 'date_format' ), get_post_time( 'U', false, get_the_ID() ) ) ?></span> <?php $price = get_post_meta( get_the_ID(), "adverts_price", true ) ?> <?php if( $price ): ?> <div class="advert-price"><?php esc_html_e( adverts_price( get_post_meta( get_the_ID(), "adverts_price", true ) ) ) ?></div> <?php endif; ?> </div>fun </div> ``` This is the function applied to the `the_content()` filter when we browse single posts and also category pages (in this case again the first shortcode function is called): ``` add_filter('the_content', 'adverts_the_content'); function adverts_the_content($content) { global $wp_query; if (is_singular('advert') && in_the_loop() ) { ob_start(); $post_id = get_the_ID(); include ADVERTS_PATH . 'templates/single.php'; $content = ob_get_clean(); } elseif( is_tax( 'advert_category' ) && in_the_loop() ) { $content = shortcode_adverts_list(array( "category" => $wp_query->get_queried_object_id() )); } return $content; } ``` **UPDATE** This is the `adverts_request()` function, called by the `shortcode_adverts_list()` function: ``` function adverts_request($key, $default = null) { if(isset($_POST[$key])) { return $_POST[$key]; } elseif(isset($_GET[$key])) { return $_GET[$key]; } else { return $default; } } ```
You need to make the function pluggable, that means, to support child themes, the functions in parent theme should use: ``` if ( !function_exists( 'function_name' )) { function function_name() { //Stuffs } } ``` You should have seen a PHP Error message if you have [debugging enabled](https://codex.wordpress.org/Debugging_in_WordPress). **EDIT:** The below code snippet if to answer your other question in comment. ``` function modify_read_more_link() { global $post; return '<a class="more-link" href="' . get_permalink( $post->ID ) . '">Your Read More Link Text</a>'; } add_filter( 'the_content_more_link', 'modify_read_more_link' ); ```
210,116
<p>This is what I have:</p> <pre><code>global $wpdb, $month; $months = $wpdb-&gt;get_results( "SELECT * FROM $wpdb-&gt;posts WHERE post_type = 'post' AND post_status = 'publish' AND DATE_FORMAT( post_date_gmt, '%Y' ) = $y GROUP BY DATE_FORMAT( post_date_gmt, '%Y-%m' ) ORDER BY post_date_gmt DESC "); </code></pre> <p>The problem is, this returns all posts from that time, but I want only posts that are in category 11.</p> <p>Is there an easy way to achieve this?</p>
[ { "answer_id": 210118, "author": "Gyanendra Giri", "author_id": 47270, "author_profile": "https://wordpress.stackexchange.com/users/47270", "pm_score": 0, "selected": false, "text": "<p>To show all posts from a category ID 11. Use following loop. It will show all posts from category ID 11.</p>\n\n<p><pre>\n// WP_Query arguments for category Id 11\n $args = array (\n 'cat' => '11',\n );</p>\n\n<p>// The Query\n $query = new WP_Query( $args );\n// The Loop\n if ( $query->have_posts() ) {\n while ( $query->have_posts() ) {\n $query->the_post();\n // rest of loop code\n }\n } else {\n // no posts found\n }</p>\n\n<p>// Restore post data loop\n wp_reset_postdata();\n </pre></p>\n" }, { "answer_id": 210270, "author": "Toskan", "author_id": 48130, "author_profile": "https://wordpress.stackexchange.com/users/48130", "pm_score": 3, "selected": true, "text": "<p>it's quite easy:</p>\n\n<pre><code>$months = $wpdb-&gt;get_col(\"SELECT DATE_FORMAT(post_date_gmt, '%m')\n FROM $wpdb-&gt;posts\n LEFT JOIN $wpdb-&gt;term_relationships as t\n ON ID = t.object_id\n WHERE post_type = 'post' AND post_status = 'publish' AND t.term_taxonomy_id = 11\n AND DATE_FORMAT(post_date_gmt, '%Y') = $y\n GROUP BY DATE_FORMAT(post_date_gmt, '%Y-%m')\n ORDER BY post_date_gmt DESC\");\n</code></pre>\n\n<p>term_taxonomy_id is the category. And I join on the object ID</p>\n" }, { "answer_id": 276264, "author": "Aaron Lynch", "author_id": 125397, "author_profile": "https://wordpress.stackexchange.com/users/125397", "pm_score": 1, "selected": false, "text": "<p>The best way to get all posts from a specific category within WordPress is to use the native class <code>WP_Query</code>, and not the <code>$wpdb</code> method.</p>\n\n<p>Here is a query example using WP_Query:</p>\n\n<pre><code>&lt;?php\n\n $args = array(\n // Arguments for your query.\n );\n\n // Custom query.\n $query = new WP_Query( $args );\n\n // Check that we have query results.\n if ( $query-&gt;have_posts() ) {\n\n // Start looping over the query results.\n while ( $query-&gt;have_posts() ) {\n\n $query-&gt;the_post();\n\n // Contents of the queried post results go here.\n\n }\n\n }\n\n // Restore original post data.\n wp_reset_postdata();\n\n?&gt;\n</code></pre>\n\n<p>In your scenario all we need to do now is specify in the query arguments the category parameter <code>cat</code> and your desired category's <code>ID</code>, like so:</p>\n\n<pre><code>$args = array(\n 'cat' =&gt; '11',\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish'\n);\n</code></pre>\n\n<p>There are <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">many more parameters and values</a> you can feed to the query's argument.</p>\n\n<p>Hope this helps!</p>\n" } ]
2015/11/27
[ "https://wordpress.stackexchange.com/questions/210116", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48130/" ]
This is what I have: ``` global $wpdb, $month; $months = $wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' AND DATE_FORMAT( post_date_gmt, '%Y' ) = $y GROUP BY DATE_FORMAT( post_date_gmt, '%Y-%m' ) ORDER BY post_date_gmt DESC "); ``` The problem is, this returns all posts from that time, but I want only posts that are in category 11. Is there an easy way to achieve this?
it's quite easy: ``` $months = $wpdb->get_col("SELECT DATE_FORMAT(post_date_gmt, '%m') FROM $wpdb->posts LEFT JOIN $wpdb->term_relationships as t ON ID = t.object_id WHERE post_type = 'post' AND post_status = 'publish' AND t.term_taxonomy_id = 11 AND DATE_FORMAT(post_date_gmt, '%Y') = $y GROUP BY DATE_FORMAT(post_date_gmt, '%Y-%m') ORDER BY post_date_gmt DESC"); ``` term\_taxonomy\_id is the category. And I join on the object ID
210,126
<p>I am writing a plugin that instantiates a custom post type (among other things). It is a multisite plugin and lives in the directory <strong>mu-plugins</strong>.</p> <p>What is the best practice for handling <strong>flush_rewrite_rules()</strong> in this situation? For a 'normal' plugin you'd do this in an activation hook -- which is not going to be possible for a must-use plugin since those hooks are not available.</p> <p>Since this is supposed to be a "one time" event after registering the custom post type, would it make sense to do something like this in my class that registers the CPT:</p> <pre><code>private function check_flush_my_CPT() { global $wp_rewrite; if ( !get_option('my_plugin_firstrun') ) { $wp_rewrite-&gt;init(); $wp_rewrite-&gt;flush_rules(true); update_option('my_plugin_firstrun', 'yes'); } } public function register_my_CPT() { // do all the CPT setup steps for the $args array... register_post_type('my_CPT', $args); $this-&gt;check_flush_my_CPT(); } add_action( 'init', array(&amp;$this, 'register_my_CPT' ) ); </code></pre> <p>So, the CPT registration happens on every 'init' action -- but if I have this right, the rewrite rules flush only happens once. <strong>Ever</strong>.</p> <p>Am I on the right track?</p> <p>(edit): I just tried it; my CPT is giving a 404 not found error, so the rewrites rules are not working :-(</p> <p>(edit #2): I did try the solution for accessing the global variable as shown in this question: <a href="https://wordpress.stackexchange.com/questions/187750/how-to-reliably-flush-rewrite-rules-on-multisite">How to reliably flush rewrite rules on multisite?</a> - I will update my code example above to show this. Unfortunately I am still getting 404 error when trying to load a CPT. I see that the rewrite rules are being stored in the database, it just seems like they are not being used. I'm lost.</p>
[ { "answer_id": 216647, "author": "Leon Francis Shelhamer", "author_id": 25927, "author_profile": "https://wordpress.stackexchange.com/users/25927", "pm_score": 0, "selected": false, "text": "<p>If your mu-plugin has options I would put the flush right after updating them:</p>\n\n<pre><code>update_option( 'my_options', $values );\n// Flush rules after install\nflush_rewrite_rules();\n</code></pre>\n" }, { "answer_id": 233914, "author": "Andrei", "author_id": 26395, "author_profile": "https://wordpress.stackexchange.com/users/26395", "pm_score": 2, "selected": false, "text": "<p>The <code>flush_rewrite_rules</code> function is reliable in some contexts like a theme or a plugin based on hooks but I'm not sure if it works for a <code>mu-plugin</code></p>\n\n<p>My statement is based on the fact that WordPress is initialized in this way:</p>\n\n<ul>\n<li>call the <code>wp-settings.php</code> file</li>\n<li>call the <code>do_action( 'muplugins_loaded' );</code> hook, here your plugin is initialized</li>\n<li>call <code>$GLOBALS['wp_rewrite'] = new WP_Rewrite();</code> here the method <code>flush_rules</code> is initialized and available from now on</li>\n<li><code>do_action( 'setup_theme' );</code> is called and I bet all my money that on this hook the <code>flush_rewrite_rules</code> will work</li>\n</ul>\n\n<p><strong>Solution?</strong></p>\n\n<p>Personally, I find reliable the deletion of the rewrite_rules option.</p>\n\n<pre><code>delete_option('rewrite_rules');\n</code></pre>\n\n<p>or</p>\n\n<pre><code>update_option('rewrite_rules', '' );\n</code></pre>\n\n<p>Whenever WordPress will lack the <code>rewrite_rules</code> it will build them back, this is also what the <code>flush_rules</code> method does.</p>\n\n<p>There are points in WordPress execution flow where functions like this aren't available. even in the core of WordPress I found this statement</p>\n\n<pre><code>// Rewrite rules can't be flushed during switch to blog.\ndelete_option( 'rewrite_rules' );\n</code></pre>\n\n<p>The only problem would be the performance, don't do this on every request because it is a hard process to build them back.\nAs I can see you want to flush them only at the first call and this is a good thing.</p>\n\n<p>P.S: I'm not such a self-promo fan but I've also written an <a href=\"http://andrei-lupu.com/wordpress/dont-forget-to-flush-your-rewrite-rules/\" rel=\"nofollow\">article</a> about this long time ago and I think it still stands up for this</p>\n" }, { "answer_id": 367012, "author": "svandragt", "author_id": 103106, "author_profile": "https://wordpress.stackexchange.com/users/103106", "pm_score": 1, "selected": false, "text": "<p>MU-Plugins are considered to be always activated, so the <code>register_activation_hook</code> and <code>register_deactivation_hook</code> hooks are never called.</p>\n\n<p>Instead add a plugin version, which must be updated whenever any changes affecting the rewrite rules are made:</p>\n\n<pre><code>namespace My\\Namespace;\n\ndefine( 'MY_CPTS_REWRITES', '2020-05-19.1' );\n\nfunction maybe_flush_rewrite_rules() {\n if ( update_option('MY_CPTS_REWRITES', MY_CPTS_REWRITES) ) {\n flush_rewrite_rules(false);\n }\n}\n\nadd_action( 'init', __NAMESPACE__ . '\\\\maybe_flush_rewrite_rules', 11 );\n</code></pre>\n\n<p>The hook priority is set to 11 to ensure it's ran after the post type is registered, (in case the default priority 10 is used). </p>\n\n<p>Note that by testing for <code>update_option()</code> we avoid a race condition that exists on high traffic sites where between a <code>get_option()</code> call and an <code>update_option()</code> call the value is changed on another request, causing eternal flushes. <code>update_option()</code> includes a check for the old value of the option and only returns true if the option is changed.</p>\n\n<p>To test this works, update the custom post type’s rewrite slug to anything else, then view one of the items in the front end and it should contain the updated slug. If it updates without updating the version number, something else is updating the permalinks which should be investigated.</p>\n" }, { "answer_id": 383168, "author": "OzzyCzech", "author_id": 12545, "author_profile": "https://wordpress.stackexchange.com/users/12545", "pm_score": 0, "selected": false, "text": "<p>I am using follow code. It's check if current file has changed, then flush rewrite rules.</p>\n<pre><code>add_action('init', function() {\n $md5 = md5_file(__FILE__);\n if (get_option(__FILE__) !== $md5) {\n update_option(__FILE__, $md5);\n flush_rewrite_rules();\n }\n});\n</code></pre>\n" } ]
2015/11/28
[ "https://wordpress.stackexchange.com/questions/210126", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83299/" ]
I am writing a plugin that instantiates a custom post type (among other things). It is a multisite plugin and lives in the directory **mu-plugins**. What is the best practice for handling **flush\_rewrite\_rules()** in this situation? For a 'normal' plugin you'd do this in an activation hook -- which is not going to be possible for a must-use plugin since those hooks are not available. Since this is supposed to be a "one time" event after registering the custom post type, would it make sense to do something like this in my class that registers the CPT: ``` private function check_flush_my_CPT() { global $wp_rewrite; if ( !get_option('my_plugin_firstrun') ) { $wp_rewrite->init(); $wp_rewrite->flush_rules(true); update_option('my_plugin_firstrun', 'yes'); } } public function register_my_CPT() { // do all the CPT setup steps for the $args array... register_post_type('my_CPT', $args); $this->check_flush_my_CPT(); } add_action( 'init', array(&$this, 'register_my_CPT' ) ); ``` So, the CPT registration happens on every 'init' action -- but if I have this right, the rewrite rules flush only happens once. **Ever**. Am I on the right track? (edit): I just tried it; my CPT is giving a 404 not found error, so the rewrites rules are not working :-( (edit #2): I did try the solution for accessing the global variable as shown in this question: [How to reliably flush rewrite rules on multisite?](https://wordpress.stackexchange.com/questions/187750/how-to-reliably-flush-rewrite-rules-on-multisite) - I will update my code example above to show this. Unfortunately I am still getting 404 error when trying to load a CPT. I see that the rewrite rules are being stored in the database, it just seems like they are not being used. I'm lost.
The `flush_rewrite_rules` function is reliable in some contexts like a theme or a plugin based on hooks but I'm not sure if it works for a `mu-plugin` My statement is based on the fact that WordPress is initialized in this way: * call the `wp-settings.php` file * call the `do_action( 'muplugins_loaded' );` hook, here your plugin is initialized * call `$GLOBALS['wp_rewrite'] = new WP_Rewrite();` here the method `flush_rules` is initialized and available from now on * `do_action( 'setup_theme' );` is called and I bet all my money that on this hook the `flush_rewrite_rules` will work **Solution?** Personally, I find reliable the deletion of the rewrite\_rules option. ``` delete_option('rewrite_rules'); ``` or ``` update_option('rewrite_rules', '' ); ``` Whenever WordPress will lack the `rewrite_rules` it will build them back, this is also what the `flush_rules` method does. There are points in WordPress execution flow where functions like this aren't available. even in the core of WordPress I found this statement ``` // Rewrite rules can't be flushed during switch to blog. delete_option( 'rewrite_rules' ); ``` The only problem would be the performance, don't do this on every request because it is a hard process to build them back. As I can see you want to flush them only at the first call and this is a good thing. P.S: I'm not such a self-promo fan but I've also written an [article](http://andrei-lupu.com/wordpress/dont-forget-to-flush-your-rewrite-rules/) about this long time ago and I think it still stands up for this
210,127
<p>I am trying to built fancybox plugins.I added all js and css file to my php file and add one image to it ,but I found this error.</p> <blockquote> <p>The plugins generated 3265 characters of unexpected output during activation.</p> <p>If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugins.</p> </blockquote>
[ { "answer_id": 216647, "author": "Leon Francis Shelhamer", "author_id": 25927, "author_profile": "https://wordpress.stackexchange.com/users/25927", "pm_score": 0, "selected": false, "text": "<p>If your mu-plugin has options I would put the flush right after updating them:</p>\n\n<pre><code>update_option( 'my_options', $values );\n// Flush rules after install\nflush_rewrite_rules();\n</code></pre>\n" }, { "answer_id": 233914, "author": "Andrei", "author_id": 26395, "author_profile": "https://wordpress.stackexchange.com/users/26395", "pm_score": 2, "selected": false, "text": "<p>The <code>flush_rewrite_rules</code> function is reliable in some contexts like a theme or a plugin based on hooks but I'm not sure if it works for a <code>mu-plugin</code></p>\n\n<p>My statement is based on the fact that WordPress is initialized in this way:</p>\n\n<ul>\n<li>call the <code>wp-settings.php</code> file</li>\n<li>call the <code>do_action( 'muplugins_loaded' );</code> hook, here your plugin is initialized</li>\n<li>call <code>$GLOBALS['wp_rewrite'] = new WP_Rewrite();</code> here the method <code>flush_rules</code> is initialized and available from now on</li>\n<li><code>do_action( 'setup_theme' );</code> is called and I bet all my money that on this hook the <code>flush_rewrite_rules</code> will work</li>\n</ul>\n\n<p><strong>Solution?</strong></p>\n\n<p>Personally, I find reliable the deletion of the rewrite_rules option.</p>\n\n<pre><code>delete_option('rewrite_rules');\n</code></pre>\n\n<p>or</p>\n\n<pre><code>update_option('rewrite_rules', '' );\n</code></pre>\n\n<p>Whenever WordPress will lack the <code>rewrite_rules</code> it will build them back, this is also what the <code>flush_rules</code> method does.</p>\n\n<p>There are points in WordPress execution flow where functions like this aren't available. even in the core of WordPress I found this statement</p>\n\n<pre><code>// Rewrite rules can't be flushed during switch to blog.\ndelete_option( 'rewrite_rules' );\n</code></pre>\n\n<p>The only problem would be the performance, don't do this on every request because it is a hard process to build them back.\nAs I can see you want to flush them only at the first call and this is a good thing.</p>\n\n<p>P.S: I'm not such a self-promo fan but I've also written an <a href=\"http://andrei-lupu.com/wordpress/dont-forget-to-flush-your-rewrite-rules/\" rel=\"nofollow\">article</a> about this long time ago and I think it still stands up for this</p>\n" }, { "answer_id": 367012, "author": "svandragt", "author_id": 103106, "author_profile": "https://wordpress.stackexchange.com/users/103106", "pm_score": 1, "selected": false, "text": "<p>MU-Plugins are considered to be always activated, so the <code>register_activation_hook</code> and <code>register_deactivation_hook</code> hooks are never called.</p>\n\n<p>Instead add a plugin version, which must be updated whenever any changes affecting the rewrite rules are made:</p>\n\n<pre><code>namespace My\\Namespace;\n\ndefine( 'MY_CPTS_REWRITES', '2020-05-19.1' );\n\nfunction maybe_flush_rewrite_rules() {\n if ( update_option('MY_CPTS_REWRITES', MY_CPTS_REWRITES) ) {\n flush_rewrite_rules(false);\n }\n}\n\nadd_action( 'init', __NAMESPACE__ . '\\\\maybe_flush_rewrite_rules', 11 );\n</code></pre>\n\n<p>The hook priority is set to 11 to ensure it's ran after the post type is registered, (in case the default priority 10 is used). </p>\n\n<p>Note that by testing for <code>update_option()</code> we avoid a race condition that exists on high traffic sites where between a <code>get_option()</code> call and an <code>update_option()</code> call the value is changed on another request, causing eternal flushes. <code>update_option()</code> includes a check for the old value of the option and only returns true if the option is changed.</p>\n\n<p>To test this works, update the custom post type’s rewrite slug to anything else, then view one of the items in the front end and it should contain the updated slug. If it updates without updating the version number, something else is updating the permalinks which should be investigated.</p>\n" }, { "answer_id": 383168, "author": "OzzyCzech", "author_id": 12545, "author_profile": "https://wordpress.stackexchange.com/users/12545", "pm_score": 0, "selected": false, "text": "<p>I am using follow code. It's check if current file has changed, then flush rewrite rules.</p>\n<pre><code>add_action('init', function() {\n $md5 = md5_file(__FILE__);\n if (get_option(__FILE__) !== $md5) {\n update_option(__FILE__, $md5);\n flush_rewrite_rules();\n }\n});\n</code></pre>\n" } ]
2015/11/28
[ "https://wordpress.stackexchange.com/questions/210127", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84167/" ]
I am trying to built fancybox plugins.I added all js and css file to my php file and add one image to it ,but I found this error. > > The plugins generated 3265 characters of unexpected output during activation. > > > If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugins. > > >
The `flush_rewrite_rules` function is reliable in some contexts like a theme or a plugin based on hooks but I'm not sure if it works for a `mu-plugin` My statement is based on the fact that WordPress is initialized in this way: * call the `wp-settings.php` file * call the `do_action( 'muplugins_loaded' );` hook, here your plugin is initialized * call `$GLOBALS['wp_rewrite'] = new WP_Rewrite();` here the method `flush_rules` is initialized and available from now on * `do_action( 'setup_theme' );` is called and I bet all my money that on this hook the `flush_rewrite_rules` will work **Solution?** Personally, I find reliable the deletion of the rewrite\_rules option. ``` delete_option('rewrite_rules'); ``` or ``` update_option('rewrite_rules', '' ); ``` Whenever WordPress will lack the `rewrite_rules` it will build them back, this is also what the `flush_rules` method does. There are points in WordPress execution flow where functions like this aren't available. even in the core of WordPress I found this statement ``` // Rewrite rules can't be flushed during switch to blog. delete_option( 'rewrite_rules' ); ``` The only problem would be the performance, don't do this on every request because it is a hard process to build them back. As I can see you want to flush them only at the first call and this is a good thing. P.S: I'm not such a self-promo fan but I've also written an [article](http://andrei-lupu.com/wordpress/dont-forget-to-flush-your-rewrite-rules/) about this long time ago and I think it still stands up for this
210,169
<p>I would like to get relative path from a php file without knowing the absolute path. I have succeeded to do it but for a reason which I don't know, on some servers (in rare case) it doesn't work when I enqueue css/js. Slashes are missing...</p> <p>Here the code:</p> <pre><code>define('PATH', trailingslashit(str_replace('\\', '/', dirname(__FILE__)))); define('URI', site_url(str_replace(trailingslashit(str_replace('\\', '/',ABSPATH)), '', PATH))) </code></pre> <p>What did I miss? Does it come from the server or the code itself?</p>
[ { "answer_id": 210170, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>Just don't do it, you can never know if the plugins directory is even \"below\" ABSPATH, and you can not know the URL out of the directory path <a href=\"https://codex.wordpress.org/Determining_Plugin_and_Content_Directories\" rel=\"nofollow\">https://codex.wordpress.org/Determining_Plugin_and_Content_Directories</a>.</p>\n\n<p>Just use the core api of plugins_utl etc, don't reinvent the wheel.</p>\n" }, { "answer_id": 210171, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 0, "selected": false, "text": "<pre><code>function get_url_from_path ($path) {\n\n // clean paths\n $dir_path = str_replace( '\\\\', '/', $path ) ); // file or directory\n $site_dir = trailingslashit( str_replace( '\\\\', '/', ABSPATH ) ); // path set in wp-config\n\n // remove server directory from path\n $file_rel = str_replace( $site_dir, '', $dir_path );\n\n // convert relative url to absolute url\n $dir_rel_url = site_url ($file_rel, 'http' );\n\n // return\n return $dir_rel_url; \n}\n\n// __FILE__ and __DIR__ are referencing the php calling these functions\n\necho get_url_from_path (__FILE__);\n\necho trailingslashit( get_url_from_path (__DIR__) );\n</code></pre>\n" } ]
2015/11/28
[ "https://wordpress.stackexchange.com/questions/210169", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/35097/" ]
I would like to get relative path from a php file without knowing the absolute path. I have succeeded to do it but for a reason which I don't know, on some servers (in rare case) it doesn't work when I enqueue css/js. Slashes are missing... Here the code: ``` define('PATH', trailingslashit(str_replace('\\', '/', dirname(__FILE__)))); define('URI', site_url(str_replace(trailingslashit(str_replace('\\', '/',ABSPATH)), '', PATH))) ``` What did I miss? Does it come from the server or the code itself?
Just don't do it, you can never know if the plugins directory is even "below" ABSPATH, and you can not know the URL out of the directory path <https://codex.wordpress.org/Determining_Plugin_and_Content_Directories>. Just use the core api of plugins\_utl etc, don't reinvent the wheel.
210,199
<p>The error I'm seeing is that the way I currently have my category page set up, if a post on that page has more than 1 category, the loop won't load the posts that follow the one with multiple categories. </p> <p>Currently I have about 10 posts in my test installation of WordPress. 9 of them have the same category, lets call it "Surprised". 1 of them has 3 categories. When I go to the category for page "Surprised, instead of seeing 10 posts on that page, including the one with 3 different categories, the page stops loading the category posts that follow it. </p> <p>Here is an example of one of the loops that ate on the category page (there are 4 loops total and all of them behave the same presently).</p> <pre><code>&lt;? get_header(); ?&gt; &lt;? $cat_array = get_the_category(); $cat_name = esc_html($cat_array[0]-&gt;name); ?&gt; &lt;? $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'category_name' =&gt; $cat_name, 'paged' =&gt; $paged, 'posts_per_page' =&gt; 2 ); $wp_query = new WP_Query($args); while($wp_query-&gt;have_posts()) : $wp_query-&gt;the_post(); ?&gt; &lt;div class="post-box pane"&gt; &lt;a href="&lt;? the_permalink(); ?&gt;" class="article"&gt; &lt;h3 class="title"&gt;&lt;? echo get_the_title(); ?&gt;&lt;/h3&gt; &lt;? echo the_post_thumbnail('smaller-general-thumb', array('class' =&gt; 'thumb')) ?&gt; &lt;/a&gt; &lt;/div&gt; &lt;? endwhile; wp_reset_postdata(); ?&gt; </code></pre> <p>The reason I'm doing 4 sections with different loops is because each section has a specific number of posts in it. I have to limit the number of posts that show for a section, so I create a new loop and I limit the posts for that loop by paging them and limiting posts per page.</p>
[ { "answer_id": 210200, "author": "Hans Spieß", "author_id": 27933, "author_profile": "https://wordpress.stackexchange.com/users/27933", "pm_score": 2, "selected": true, "text": "<h3>Multiple Loops</h3>\n\n<p>Outside the loop you can get available terms of the core taxonomy <em>category</em> with <a href=\"https://codex.wordpress.org/Function_Reference/get_terms\" rel=\"nofollow\"><code>get_terms( 'taxonomy_name' )</code></a>. The resulting array contains objects like</p>\n\n<pre><code>object(stdClass)#141 (9) {\n [\"term_id\"] =&gt; string(1) \"3\"\n [\"name\"] =&gt; string(9) \"The Name of your Category\"\n [\"slug\"] =&gt; string(9) \"name-of-tax-term\"\n [\"term_group\"] =&gt; string(1) \"0\"\n [\"term_taxonomy_id\"] =&gt; string(1) \"3\"\n [\"taxonomy\"] =&gt; string(11) \"slug_of_tax\"\n [\"description\"] =&gt; string(41) \"Description of Term.\"\n [\"parent\"] =&gt; string(1) \"0\"\n [\"count\"] =&gt; string(1) \"3\"\n}\n</code></pre>\n\n<p>So you would want to get the category slug, not its name:</p>\n\n<pre><code>$cats = get_terms( 'category' );\n</code></pre>\n\n<p>You could then loop the categories like </p>\n\n<pre><code>foreach ( $cats as $cat ) {\n $args = array(\n 'category_name' =&gt; $cat-&gt;slug,\n 'paged' =&gt; $paged,\n 'posts_per_page' =&gt; 2\n );\n // the loop\n wp_reset_postdata();\n}\n</code></pre>\n\n<h3>One Loop</h3>\n\n<p>If your loop runs on the unchanged main query, the current category is already present in the query. </p>\n\n<p>Just change</p>\n\n<pre><code>$args = array(\n 'category_name' =&gt; $cat_name,\n 'paged' =&gt; $paged,\n 'posts_per_page' =&gt; 2\n);\n</code></pre>\n\n<p>to</p>\n\n<pre><code>$args = array(\n 'paged' =&gt; $paged,\n 'posts_per_page' =&gt; 2\n);\n</code></pre>\n\n<p>in your code.</p>\n\n<p>Besides, when not using <a href=\"https://developer.wordpress.org/reference/functions/get_the_category/\" rel=\"nofollow\"><code>get_the_category()</code></a> inside the loop, you have to pass a post ID as argument.</p>\n" }, { "answer_id": 210262, "author": "ninja08", "author_id": 35549, "author_profile": "https://wordpress.stackexchange.com/users/35549", "pm_score": -1, "selected": false, "text": "<p>This is the solution I found to be the most elegant and appropriate for my situation:</p>\n\n<pre><code>&lt;? global $wp_query; ?&gt;\n\n$args = array_merge( $wp_query-&gt;query_vars, array( 'posts_per_page' =&gt; 2));\n$the_query = new WP_Query($args);\nwhile($the_query-&gt;have_posts()) : $the_query-&gt;the_post(); ?&gt;\n\n/// The loop\n\n&lt;? endwhile; rewind_posts(); ?&gt; \n</code></pre>\n\n<p>I specifically decided to use array_merge in order to merge the global query with the loop I'm writing in order to limit the number of posts for that loop. Now I don't need to specify the category since that's already in the global query. No need to update dat bish myself. </p>\n\n<p>Thank you everyone for your help! </p>\n" } ]
2015/11/29
[ "https://wordpress.stackexchange.com/questions/210199", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/35549/" ]
The error I'm seeing is that the way I currently have my category page set up, if a post on that page has more than 1 category, the loop won't load the posts that follow the one with multiple categories. Currently I have about 10 posts in my test installation of WordPress. 9 of them have the same category, lets call it "Surprised". 1 of them has 3 categories. When I go to the category for page "Surprised, instead of seeing 10 posts on that page, including the one with 3 different categories, the page stops loading the category posts that follow it. Here is an example of one of the loops that ate on the category page (there are 4 loops total and all of them behave the same presently). ``` <? get_header(); ?> <? $cat_array = get_the_category(); $cat_name = esc_html($cat_array[0]->name); ?> <? $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'category_name' => $cat_name, 'paged' => $paged, 'posts_per_page' => 2 ); $wp_query = new WP_Query($args); while($wp_query->have_posts()) : $wp_query->the_post(); ?> <div class="post-box pane"> <a href="<? the_permalink(); ?>" class="article"> <h3 class="title"><? echo get_the_title(); ?></h3> <? echo the_post_thumbnail('smaller-general-thumb', array('class' => 'thumb')) ?> </a> </div> <? endwhile; wp_reset_postdata(); ?> ``` The reason I'm doing 4 sections with different loops is because each section has a specific number of posts in it. I have to limit the number of posts that show for a section, so I create a new loop and I limit the posts for that loop by paging them and limiting posts per page.
### Multiple Loops Outside the loop you can get available terms of the core taxonomy *category* with [`get_terms( 'taxonomy_name' )`](https://codex.wordpress.org/Function_Reference/get_terms). The resulting array contains objects like ``` object(stdClass)#141 (9) { ["term_id"] => string(1) "3" ["name"] => string(9) "The Name of your Category" ["slug"] => string(9) "name-of-tax-term" ["term_group"] => string(1) "0" ["term_taxonomy_id"] => string(1) "3" ["taxonomy"] => string(11) "slug_of_tax" ["description"] => string(41) "Description of Term." ["parent"] => string(1) "0" ["count"] => string(1) "3" } ``` So you would want to get the category slug, not its name: ``` $cats = get_terms( 'category' ); ``` You could then loop the categories like ``` foreach ( $cats as $cat ) { $args = array( 'category_name' => $cat->slug, 'paged' => $paged, 'posts_per_page' => 2 ); // the loop wp_reset_postdata(); } ``` ### One Loop If your loop runs on the unchanged main query, the current category is already present in the query. Just change ``` $args = array( 'category_name' => $cat_name, 'paged' => $paged, 'posts_per_page' => 2 ); ``` to ``` $args = array( 'paged' => $paged, 'posts_per_page' => 2 ); ``` in your code. Besides, when not using [`get_the_category()`](https://developer.wordpress.org/reference/functions/get_the_category/) inside the loop, you have to pass a post ID as argument.
210,218
<p>I am trying to make a site with two languages. I was looking for a solution and didn't find a simple how-to answer. Also, I prefer not to use plugins when it is possible.</p> <p>What I'm trying to do:</p> <p>1) To have a <code>domain.com/en</code> and <code>domain.com/ru</code> while default redirect is at <code>domain.com/en</code>. </p> <p>2) One WP engine install, same admin panel with same language - English.</p> <p>3) Free way of styling things(this include html too, not only css). This is the most problematic part of course. </p> <p>I can't figure out how to make this. I know there is a way to call different headers and footers, but I don't know how to manage this effectively with two languages site. I can use for example different categories for different languages, but is this good practice and is this going to work properly?</p>
[ { "answer_id": 210200, "author": "Hans Spieß", "author_id": 27933, "author_profile": "https://wordpress.stackexchange.com/users/27933", "pm_score": 2, "selected": true, "text": "<h3>Multiple Loops</h3>\n\n<p>Outside the loop you can get available terms of the core taxonomy <em>category</em> with <a href=\"https://codex.wordpress.org/Function_Reference/get_terms\" rel=\"nofollow\"><code>get_terms( 'taxonomy_name' )</code></a>. The resulting array contains objects like</p>\n\n<pre><code>object(stdClass)#141 (9) {\n [\"term_id\"] =&gt; string(1) \"3\"\n [\"name\"] =&gt; string(9) \"The Name of your Category\"\n [\"slug\"] =&gt; string(9) \"name-of-tax-term\"\n [\"term_group\"] =&gt; string(1) \"0\"\n [\"term_taxonomy_id\"] =&gt; string(1) \"3\"\n [\"taxonomy\"] =&gt; string(11) \"slug_of_tax\"\n [\"description\"] =&gt; string(41) \"Description of Term.\"\n [\"parent\"] =&gt; string(1) \"0\"\n [\"count\"] =&gt; string(1) \"3\"\n}\n</code></pre>\n\n<p>So you would want to get the category slug, not its name:</p>\n\n<pre><code>$cats = get_terms( 'category' );\n</code></pre>\n\n<p>You could then loop the categories like </p>\n\n<pre><code>foreach ( $cats as $cat ) {\n $args = array(\n 'category_name' =&gt; $cat-&gt;slug,\n 'paged' =&gt; $paged,\n 'posts_per_page' =&gt; 2\n );\n // the loop\n wp_reset_postdata();\n}\n</code></pre>\n\n<h3>One Loop</h3>\n\n<p>If your loop runs on the unchanged main query, the current category is already present in the query. </p>\n\n<p>Just change</p>\n\n<pre><code>$args = array(\n 'category_name' =&gt; $cat_name,\n 'paged' =&gt; $paged,\n 'posts_per_page' =&gt; 2\n);\n</code></pre>\n\n<p>to</p>\n\n<pre><code>$args = array(\n 'paged' =&gt; $paged,\n 'posts_per_page' =&gt; 2\n);\n</code></pre>\n\n<p>in your code.</p>\n\n<p>Besides, when not using <a href=\"https://developer.wordpress.org/reference/functions/get_the_category/\" rel=\"nofollow\"><code>get_the_category()</code></a> inside the loop, you have to pass a post ID as argument.</p>\n" }, { "answer_id": 210262, "author": "ninja08", "author_id": 35549, "author_profile": "https://wordpress.stackexchange.com/users/35549", "pm_score": -1, "selected": false, "text": "<p>This is the solution I found to be the most elegant and appropriate for my situation:</p>\n\n<pre><code>&lt;? global $wp_query; ?&gt;\n\n$args = array_merge( $wp_query-&gt;query_vars, array( 'posts_per_page' =&gt; 2));\n$the_query = new WP_Query($args);\nwhile($the_query-&gt;have_posts()) : $the_query-&gt;the_post(); ?&gt;\n\n/// The loop\n\n&lt;? endwhile; rewind_posts(); ?&gt; \n</code></pre>\n\n<p>I specifically decided to use array_merge in order to merge the global query with the loop I'm writing in order to limit the number of posts for that loop. Now I don't need to specify the category since that's already in the global query. No need to update dat bish myself. </p>\n\n<p>Thank you everyone for your help! </p>\n" } ]
2015/11/29
[ "https://wordpress.stackexchange.com/questions/210218", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84453/" ]
I am trying to make a site with two languages. I was looking for a solution and didn't find a simple how-to answer. Also, I prefer not to use plugins when it is possible. What I'm trying to do: 1) To have a `domain.com/en` and `domain.com/ru` while default redirect is at `domain.com/en`. 2) One WP engine install, same admin panel with same language - English. 3) Free way of styling things(this include html too, not only css). This is the most problematic part of course. I can't figure out how to make this. I know there is a way to call different headers and footers, but I don't know how to manage this effectively with two languages site. I can use for example different categories for different languages, but is this good practice and is this going to work properly?
### Multiple Loops Outside the loop you can get available terms of the core taxonomy *category* with [`get_terms( 'taxonomy_name' )`](https://codex.wordpress.org/Function_Reference/get_terms). The resulting array contains objects like ``` object(stdClass)#141 (9) { ["term_id"] => string(1) "3" ["name"] => string(9) "The Name of your Category" ["slug"] => string(9) "name-of-tax-term" ["term_group"] => string(1) "0" ["term_taxonomy_id"] => string(1) "3" ["taxonomy"] => string(11) "slug_of_tax" ["description"] => string(41) "Description of Term." ["parent"] => string(1) "0" ["count"] => string(1) "3" } ``` So you would want to get the category slug, not its name: ``` $cats = get_terms( 'category' ); ``` You could then loop the categories like ``` foreach ( $cats as $cat ) { $args = array( 'category_name' => $cat->slug, 'paged' => $paged, 'posts_per_page' => 2 ); // the loop wp_reset_postdata(); } ``` ### One Loop If your loop runs on the unchanged main query, the current category is already present in the query. Just change ``` $args = array( 'category_name' => $cat_name, 'paged' => $paged, 'posts_per_page' => 2 ); ``` to ``` $args = array( 'paged' => $paged, 'posts_per_page' => 2 ); ``` in your code. Besides, when not using [`get_the_category()`](https://developer.wordpress.org/reference/functions/get_the_category/) inside the loop, you have to pass a post ID as argument.
210,222
<p>Why does Woocommerce use hooks rather than including template parts?</p> <p>I'm in the process of creating my first Woocommerce theme, and it seems that deactivating the current hooks and then readding them to change the order of a section real overkill. To me, it makes more sense that you just include each of the template parts using <code>get_template_part()</code>.</p> <p>What am I missing / what's the benefit of doing it their way?!</p>
[ { "answer_id": 210225, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>I'm not familiar with Woocommerce, but in short, <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow\"><code>get_template_part()</code></a> only look for template parts in parent and child themes, not in plugins.</p>\n\n<p>If you look at the source code, <code>get_template_part()</code> uses <a href=\"https://developer.wordpress.org/reference/functions/locate_template/\" rel=\"nofollow\"><code>locate_template</code></a> which have the following source code (<em>which is where the actual template part is searched for</em>)</p>\n\n<pre><code>function locate_template($template_names, $load = false, $require_once = true ) {\n $located = '';\n foreach ( (array) $template_names as $template_name ) {\n if ( !$template_name )\n continue;\n if ( file_exists(STYLESHEETPATH . '/' . $template_name)) {\n $located = STYLESHEETPATH . '/' . $template_name;\n break;\n } elseif ( file_exists(TEMPLATEPATH . '/' . $template_name) ) {\n $located = TEMPLATEPATH . '/' . $template_name;\n break;\n }\n }\n\n if ( $load &amp;&amp; '' != $located )\n load_template( $located, $require_once );\n\n return $located;\n}\n</code></pre>\n\n<p>As you can see, <code>locate_template</code> only look for templates in parent and child themes</p>\n\n<p>That is why you cannot use <code>get_template_part()</code> in a plugin or use it to call template parts into a theme from a plugin.</p>\n\n<h2>EDIT from comments from @MarkKaplun</h2>\n\n<p>Apart from just the general way in which <code>get_template_part()</code> works in retrieving template parts, Mark has also pointed out a valid point in comments about the use of Woocommerce</p>\n\n<blockquote>\n <p>I would say it differently - since WC is a plugin it can not have any assumptions about which themes are using it and what parts do they have without limiting its adoption, and WC is meant to work with any theme.</p>\n</blockquote>\n" }, { "answer_id": 210231, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 0, "selected": false, "text": "<pre><code>/**\n * @since 1.2.0\n *\n */\nfunction add_action(...) {\n /* ... */\n}\n</code></pre>\n\n<p>.</p>\n\n<pre><code>/**\n * @since 3.0.0\n *\n */\nfunction get_template_part(...) {\n /* ... */\n}\n</code></pre>\n\n<p>WooCommerce was launched in September 2011. However, it wasn't coded in a day, they must have started a few months earlier. </p>\n\n<p>At the time, WP was just post 3.0 (huge update, btw) and nothing about updating WP, themes or plugins was working as smooth as now.</p>\n\n<p>Besides, <code>add_action()</code> and <code>add_filter()</code> are the foundation behind WP concept. You can be sure they will never become obsolete. It's the way to go when you code something as large as WooCommerce.</p>\n\n<p>As you probably know, WC provides a <a href=\"https://docs.woothemes.com/document/template-structure/\" rel=\"nofollow\">templating system</a>.</p>\n" } ]
2015/11/29
[ "https://wordpress.stackexchange.com/questions/210222", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/27866/" ]
Why does Woocommerce use hooks rather than including template parts? I'm in the process of creating my first Woocommerce theme, and it seems that deactivating the current hooks and then readding them to change the order of a section real overkill. To me, it makes more sense that you just include each of the template parts using `get_template_part()`. What am I missing / what's the benefit of doing it their way?!
I'm not familiar with Woocommerce, but in short, [`get_template_part()`](https://developer.wordpress.org/reference/functions/get_template_part/) only look for template parts in parent and child themes, not in plugins. If you look at the source code, `get_template_part()` uses [`locate_template`](https://developer.wordpress.org/reference/functions/locate_template/) which have the following source code (*which is where the actual template part is searched for*) ``` function locate_template($template_names, $load = false, $require_once = true ) { $located = ''; foreach ( (array) $template_names as $template_name ) { if ( !$template_name ) continue; if ( file_exists(STYLESHEETPATH . '/' . $template_name)) { $located = STYLESHEETPATH . '/' . $template_name; break; } elseif ( file_exists(TEMPLATEPATH . '/' . $template_name) ) { $located = TEMPLATEPATH . '/' . $template_name; break; } } if ( $load && '' != $located ) load_template( $located, $require_once ); return $located; } ``` As you can see, `locate_template` only look for templates in parent and child themes That is why you cannot use `get_template_part()` in a plugin or use it to call template parts into a theme from a plugin. EDIT from comments from @MarkKaplun ----------------------------------- Apart from just the general way in which `get_template_part()` works in retrieving template parts, Mark has also pointed out a valid point in comments about the use of Woocommerce > > I would say it differently - since WC is a plugin it can not have any assumptions about which themes are using it and what parts do they have without limiting its adoption, and WC is meant to work with any theme. > > >
210,229
<p>I am using wp_insert_post and all the fields are working except tax_input is working. Is there something wrong with my code?</p> <pre><code>$customtax = array( 'product_link' =&gt; $link, 'product_price' =&gt; $price, 'product_description' =&gt; $desc ); $my_post = array( 'post_title' =&gt; $title, 'post_content' =&gt; $content, 'post_type' =&gt; 'products', 'tax_input' =&gt; $customtax ); </code></pre> <p>Thank you in advance</p>
[ { "answer_id": 210233, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 5, "selected": false, "text": "<p>The most common reason is that you run this code without user context (cron, etc). Within <code>wp_insert_post()</code> context WP will check if user has permissions to a taxonomy. No user equals no permissions equals no terms being assigned.</p>\n\n<p>The workaround is to create post first, then assign terms to it. When terms are assigned explicitly via API method (such as <code>wp_set_object_terms()</code>) the permissions check is not performed.</p>\n" }, { "answer_id": 241756, "author": "user1180105", "author_id": 14630, "author_profile": "https://wordpress.stackexchange.com/users/14630", "pm_score": 1, "selected": false, "text": "<p>When using tax_input for post insertion, be sure to use term taxonomy id, since slugs or names seem to be thrown away</p>\n\n<pre><code>$my_post = array(\n'post_title' =&gt; $title,\n'post_content' =&gt; $content,\n'post_type' =&gt; 'products',\n'tax_input' =&gt; array('myTax', array(4,458,11478)),\n);\n</code></pre>\n" }, { "answer_id": 287029, "author": "Eduardo Marcolino", "author_id": 124309, "author_profile": "https://wordpress.stackexchange.com/users/124309", "pm_score": 3, "selected": false, "text": "<p>It turns out that <code>tax_input</code> does not work if a user does not have the capabilities to work with a custom taxonomy:</p>\n\n<p>wp-includes/post.php (wp_insert_post):\n<a href=\"https://i.stack.imgur.com/IWJYd.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/IWJYd.png\" alt=\"enter image description here\"></a></p>\n\n<p>So either add the correct caps or use <code>wp_set_object_terms()</code></p>\n" }, { "answer_id": 332292, "author": "Tuhin A.", "author_id": 162773, "author_profile": "https://wordpress.stackexchange.com/users/162773", "pm_score": 2, "selected": false, "text": "<p>As you said in comment that plugin will do the filters and don't have hook, I think plugin must have wp_insert_post hook anyway. Otherwise how do you insert the post ?\nI am answering this after so long time cause I faced the same issue and found the only one way.</p>\n\n<p><Pre>\n$new_id = wp_insert_post($post_arr, true);\n$status = wp_set_object_terms($new_id, $term_id, 'location');\n</pre></p>\n\n<p>here location is the term slug. Someday someone will get this helpful..</p>\n" }, { "answer_id": 341001, "author": "giannisrig", "author_id": 149933, "author_profile": "https://wordpress.stackexchange.com/users/149933", "pm_score": 0, "selected": false, "text": "<p>As @Rarst said WordPress checks during the <a href=\"https://developer.wordpress.org/reference/functions/wp_insert_post/\" rel=\"nofollow noreferrer\">wp_insert_post()</a> if a current user has permission to add taxonomy terms. You also see from the <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/post.php#L3352\" rel=\"nofollow noreferrer\">post.php Line:3352</a></p>\n\n<pre><code> if ( current_user_can( $taxonomy_obj-&gt;cap-&gt;assign_terms ) ) {\n wp_set_post_terms( $post_ID, $tags, $taxonomy );\n }\n</code></pre>\n\n<p>If you are running the wp_insert_post code without having a logged in user you can set a current user by using the <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_current_user\" rel=\"nofollow noreferrer\">wp_set_current_user()</a> method.</p>\n\n<pre><code> $user = get_user_by('ID', $user_id);\n\n if( $user ){\n\n wp_set_current_user( $user_id, $user-&gt;user_login );\n\n }\n</code></pre>\n" }, { "answer_id": 365064, "author": "Gagan", "author_id": 174613, "author_profile": "https://wordpress.stackexchange.com/users/174613", "pm_score": 1, "selected": false, "text": "<p>The question is old, still I spent quite some time to figure out that insert post (wp_insert_post) show this behaviour when used inside the cron action.</p>\n\n<p>Insert post and then wp_set_object_terms is a good workaround, however, setting the current user before inserting post also worked for me</p>\n\n<pre><code>$user_id = 1;\n$user = get_user_by( 'id', $user_id );\nwp_set_current_user( $user_id, $user-&gt;user_login);\n\n$new_id = wp_insert_post($my_post);\n</code></pre>\n" } ]
2015/11/29
[ "https://wordpress.stackexchange.com/questions/210229", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84458/" ]
I am using wp\_insert\_post and all the fields are working except tax\_input is working. Is there something wrong with my code? ``` $customtax = array( 'product_link' => $link, 'product_price' => $price, 'product_description' => $desc ); $my_post = array( 'post_title' => $title, 'post_content' => $content, 'post_type' => 'products', 'tax_input' => $customtax ); ``` Thank you in advance
The most common reason is that you run this code without user context (cron, etc). Within `wp_insert_post()` context WP will check if user has permissions to a taxonomy. No user equals no permissions equals no terms being assigned. The workaround is to create post first, then assign terms to it. When terms are assigned explicitly via API method (such as `wp_set_object_terms()`) the permissions check is not performed.
210,285
<p>I am trying to figure out how to use another single.php for a custom plugin I'm making. It's for a custom post type.</p> <p>Because if people install this plugin, they won't have the custom single-product.php in their theme folder. That's why I want it to be in the plugin folder.</p> <p>Is there a way to change the path of this custom post type's single.php or a way to automatically generate the file in the theme folder after installing this plugin?</p> <p>Thanks in advance</p>
[ { "answer_id": 210286, "author": "flomei", "author_id": 65455, "author_profile": "https://wordpress.stackexchange.com/users/65455", "pm_score": 4, "selected": true, "text": "<p>I think a hook into <code>template_include</code> like <a href=\"https://wordpress.stackexchange.com/questions/55763/is-it-possible-to-define-a-template-for-a-custom-post-type-within-a-plugin-indep\">described here</a> could be a proper way to do this.</p>\n\n<p>Code could be like this:</p>\n\n<pre><code>add_filter('template_include', 'my_plugin_templates');\nfunction my_plugin_templates( $template ) {\n $post_types = array('post');\n\n if (is_singular($post_types)) {\n $template = 'path/to/singular/template/in/plugin/folder.php';\n }\n\n return $template;\n}\n</code></pre>\n" }, { "answer_id": 210289, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>Plugins should never* have any visual effect which is not a widget or a shortcode. If you feel the need to manipulate the theme files then you are most likely doing it wrong.</p>\n\n<p>*there are always exceptions as targeting a specific theme or doing something which is so theme agnostic (like popup/lightbox) that there is very little chance of breaking the theme or getting an ugly result.</p>\n\n<h2>EDIT from COMMENTS</h2>\n\n<p>This is a border line issue without any white/black type of answer. From what you describe you should have done a theme and not a plugin, but I get you were given the assignment. The right way is like with woocommerce - shortcodes and widgets that display the content managed as CPT otherwise you are more likely not to play nice with all the themes</p>\n" }, { "answer_id": 238483, "author": "kamleshpal", "author_id": 94178, "author_profile": "https://wordpress.stackexchange.com/users/94178", "pm_score": 1, "selected": false, "text": "<p>Where <code>get_custom_post_type_template</code> is the function WordPress should call when the content is being retrieved. Note that the filter function the plugin defines must return the a full path to a template file or the resulting page will be blank. The template file should have the same entries as the <code>single.php</code> file has in the theme. <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/single_template\" rel=\"nofollow\">For more information visit the site.</a></p>\n\n<pre><code> &lt;?php\n function get_custom_post_type_template($single_template) {\n global $post;\n\n if ($post-&gt;post_type == 'my_post_type') {\n $single_template = dirname( __FILE__ ) . '/post-type-template.php';\n }\n return $single_template;\n }\n add_filter( 'single_template', 'get_custom_post_type_template' );\n?&gt;\n</code></pre>\n" } ]
2015/11/30
[ "https://wordpress.stackexchange.com/questions/210285", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67623/" ]
I am trying to figure out how to use another single.php for a custom plugin I'm making. It's for a custom post type. Because if people install this plugin, they won't have the custom single-product.php in their theme folder. That's why I want it to be in the plugin folder. Is there a way to change the path of this custom post type's single.php or a way to automatically generate the file in the theme folder after installing this plugin? Thanks in advance
I think a hook into `template_include` like [described here](https://wordpress.stackexchange.com/questions/55763/is-it-possible-to-define-a-template-for-a-custom-post-type-within-a-plugin-indep) could be a proper way to do this. Code could be like this: ``` add_filter('template_include', 'my_plugin_templates'); function my_plugin_templates( $template ) { $post_types = array('post'); if (is_singular($post_types)) { $template = 'path/to/singular/template/in/plugin/folder.php'; } return $template; } ```
210,304
<p>Is it possible to add a page that is totally blank and doesn't use any components of the site's theme? Or is the best way to do that to upload it separately to the web server outside of WordPress?</p>
[ { "answer_id": 210306, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": 4, "selected": true, "text": "<p><strong>Edit:</strong> Updated with the added context from your comment.</p>\n\n<p>You could do this with a custom Page template. In your theme, create a new file. In this example, my theme will be \"mytheme2015,\" my new file is \"template-holiday-card.php\":</p>\n\n<p>in wp-content/themes/mytheme2015/template-holiday-card.php</p>\n\n<pre><code>&lt;?php\n/**\n* Template Name: Holiday Card\n*/\n</code></pre>\n\n<p>Now, once you have that template file created with a header like that, you can use it in the WordPress admin when you create a new Page type. The commented out \"Template Name:\" part tells WordPress what to call the template in the backend.</p>\n\n<p><a href=\"https://i.stack.imgur.com/foj3f.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/foj3f.png\" alt=\"enter image description here\"></a></p>\n\n<p>Note: if you don't see the Page Attributes box, look in the Screen Options pulldown menu at the top of the page.</p>\n\n<p>Now, you can put whatever code you want in template-holiday-card.php which (since it's blank) won't display <strong>anything</strong> by default.</p>\n\n<p>If you want to allow your designer to input the HTML/CSS directly in WordPress through the admin, you could just have a call to <code>the_content()</code> in your template and allow them to edit the page's content in HTML mode. Your resulting template would look something like:</p>\n\n<pre><code>&lt;?php\n/**\n* Template Name: Holiday Card\n*/\n\nthe_content();\n</code></pre>\n" }, { "answer_id": 210321, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 0, "selected": false, "text": "<p>After understanding your desired outcome, from the comments, here is my suggestion:</p>\n\n<p>If you want to send a link to your customers with a nice card, you should probably use an image placed on your server (this way you are 100% the fonts are displayed exactly how the designer wants them, on every device) and link it directly. You could also place a stand-alone <code>.html</code> or <code>.php</code> file and link those directly, as well. </p>\n\n<p>If, however, you want your existing content to be ornated for holidays, you should use a function in your <code>functions.php</code> to filter the result of header, menu and/or/maybe footer inside a simple date conditional, replacing the normal ones with the changed ones for the desired period of time.</p>\n" } ]
2015/11/30
[ "https://wordpress.stackexchange.com/questions/210304", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81877/" ]
Is it possible to add a page that is totally blank and doesn't use any components of the site's theme? Or is the best way to do that to upload it separately to the web server outside of WordPress?
**Edit:** Updated with the added context from your comment. You could do this with a custom Page template. In your theme, create a new file. In this example, my theme will be "mytheme2015," my new file is "template-holiday-card.php": in wp-content/themes/mytheme2015/template-holiday-card.php ``` <?php /** * Template Name: Holiday Card */ ``` Now, once you have that template file created with a header like that, you can use it in the WordPress admin when you create a new Page type. The commented out "Template Name:" part tells WordPress what to call the template in the backend. [![enter image description here](https://i.stack.imgur.com/foj3f.png)](https://i.stack.imgur.com/foj3f.png) Note: if you don't see the Page Attributes box, look in the Screen Options pulldown menu at the top of the page. Now, you can put whatever code you want in template-holiday-card.php which (since it's blank) won't display **anything** by default. If you want to allow your designer to input the HTML/CSS directly in WordPress through the admin, you could just have a call to `the_content()` in your template and allow them to edit the page's content in HTML mode. Your resulting template would look something like: ``` <?php /** * Template Name: Holiday Card */ the_content(); ```
210,305
<p>Using underscores, I made a lot of small, simple custome themes. I was more interested in CSS and simple layout modifications, but I'm not used to vanilla PHP. What I need I think is a simple code, but I can't wrap my head around it and I've been trying for hours. I'm trying to have a different layout for my front page, which is a static page. It works only under certain circumstances. Here's what I did and it sort of works, only I get a blank screen when trying to use <code>elseif</code>.</p> <p>My content-page.php looks like this:</p> <pre><code>&lt;?php /** * Template part for displaying page content in page.php. * * @link https://codex.wordpress.org/Template_Hierarchy * * @package mythemename */ ?&gt; &lt;article id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class(); ?&gt;&gt; &lt;header class="entry-header"&gt; &lt;?php the_title( '&lt;h1 class="entry-title"&gt;', '&lt;/h1&gt;' ); ?&gt; &lt;/header&gt;&lt;!-- .entry-header --&gt; &lt;div class="entry-content"&gt; &lt;?php the_content(); ?&gt; &lt;?php wp_link_pages( array( 'before' =&gt; '&lt;div class="page-links"&gt;' . esc_html__( 'Pages:', 'phoebelovegood' ), 'after' =&gt; '&lt;/div&gt;', ) ); ?&gt; &lt;/div&gt;&lt;!-- .entry-content --&gt; &lt;footer class="entry-footer"&gt; &lt;?php edit_post_link( sprintf( /* translators: %s: Name of current post */ esc_html__( 'Edit %s', 'phoebelovegood' ), the_title( '&lt;span class="screen-reader-text"&gt;"', '"&lt;/span&gt;', false ) ), '&lt;span class="edit-link"&gt;', '&lt;/span&gt;' ); ?&gt; &lt;/footer&gt;&lt;!-- .entry-footer --&gt; &lt;/article&gt;&lt;!-- #post-## --&gt; </code></pre> <p>Using conditionals for my page ID, I'm trying to do this:</p> <pre><code>&lt;?php if(is_page("18")): ?&gt; &lt;p&gt;This is front page&lt;/p&gt; &lt;?php elseif: ?&gt; &lt;article id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class(); ?&gt;&gt; &lt;header class="entry-header"&gt; &lt;?php the_title( '&lt;h1 class="entry-title"&gt;', '&lt;/h1&gt;' ); ?&gt; &lt;/header&gt;&lt;!-- .entry-header --&gt; &lt;div class="entry-content"&gt; &lt;?php the_content(); ?&gt; &lt;?php wp_link_pages( array( 'before' =&gt; '&lt;div class="page-links"&gt;' . esc_html__( 'Pages:', 'phoebelovegood' ), 'after' =&gt; '&lt;/div&gt;', ) ); ?&gt; &lt;/div&gt;&lt;!-- .entry-content --&gt; &lt;footer class="entry-footer"&gt; &lt;?php edit_post_link( sprintf( /* translators: %s: Name of current post */ esc_html__( 'Edit %s', 'phoebelovegood' ), the_title( '&lt;span class="screen-reader-text"&gt;"', '"&lt;/span&gt;', false ) ), '&lt;span class="edit-link"&gt;', '&lt;/span&gt;' ); ?&gt; &lt;/footer&gt;&lt;!-- .entry-footer --&gt; &lt;/article&gt;&lt;!-- #post-## --&gt; &lt;?php endif; ?&gt; </code></pre> <p>Instead, I get a blank page. What do I do wrong? Code is working if used in page.php for example, when I want to add something in-between, not using elseif.</p> <p>Any thoughts? Thanks in advance!</p>
[ { "answer_id": 210307, "author": "designarti", "author_id": 84495, "author_profile": "https://wordpress.stackexchange.com/users/84495", "pm_score": 0, "selected": false, "text": "<p>Oh, boy. I did manage to fix that and I will answer my first question here on WPSE.\nIt shouldn't work with elseif, only with else.\nWorks with:</p>\n\n<pre><code>&lt;?php if (is_page('18')) { ?&gt;\n&lt;p&gt;This is front page&lt;/p&gt;\n&lt;?php } else { ?&gt;\n&lt;article id=\"post-&lt;?php the_ID(); ?&gt;\" &lt;?php post_class(); ?&gt;&gt;\n &lt;header class=\"entry-header\"&gt;\n &lt;?php the_title( '&lt;h1 class=\"entry-title\"&gt;', '&lt;/h1&gt;' ); ?&gt;\n &lt;/header&gt;&lt;!-- .entry-header --&gt;\n\n &lt;div class=\"entry-content\"&gt;\n &lt;?php the_content(); ?&gt;\n &lt;?php\n wp_link_pages( array(\n 'before' =&gt; '&lt;div class=\"page-links\"&gt;' . esc_html__( 'Pages:', 'phoebelovegood' ),\n 'after' =&gt; '&lt;/div&gt;',\n ) );\n ?&gt;\n &lt;/div&gt;&lt;!-- .entry-content --&gt;\n\n &lt;footer class=\"entry-footer\"&gt;\n &lt;?php\n edit_post_link(\n sprintf(\n /* translators: %s: Name of current post */\n esc_html__( 'Edit %s', 'phoebelovegood' ),\n the_title( '&lt;span class=\"screen-reader-text\"&gt;\"', '\"&lt;/span&gt;', false )\n ),\n '&lt;span class=\"edit-link\"&gt;',\n '&lt;/span&gt;'\n );\n ?&gt;\n &lt;/footer&gt;&lt;!-- .entry-footer --&gt;\n&lt;/article&gt;&lt;!-- #post-## --&gt;\n&lt;?php } ?&gt;\n</code></pre>\n\n<p>Different approach...</p>\n" }, { "answer_id": 210308, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": 2, "selected": true, "text": "<p>Your first code sample didn't work because the <code>elseif</code> had no condition. <code>elseif</code> is a concatenation of <code>else</code> and <code>if</code>:</p>\n\n<pre><code>if ( something ) {\n\n} elseif ( something else ) {\n\n} else {\n\n}\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>&lt;?php if ( something ): ?&gt;\n\n&lt;?php elseif ( something else ): ?&gt;\n\n&lt;?php else: ?&gt;\n\n&lt;?php endif; ?&gt;\n</code></pre>\n\n<p>Also, if you want a front page that's different from your other pages, look at the <code>front-page.php</code> template.</p>\n" } ]
2015/11/30
[ "https://wordpress.stackexchange.com/questions/210305", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84495/" ]
Using underscores, I made a lot of small, simple custome themes. I was more interested in CSS and simple layout modifications, but I'm not used to vanilla PHP. What I need I think is a simple code, but I can't wrap my head around it and I've been trying for hours. I'm trying to have a different layout for my front page, which is a static page. It works only under certain circumstances. Here's what I did and it sort of works, only I get a blank screen when trying to use `elseif`. My content-page.php looks like this: ``` <?php /** * Template part for displaying page content in page.php. * * @link https://codex.wordpress.org/Template_Hierarchy * * @package mythemename */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?> </header><!-- .entry-header --> <div class="entry-content"> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'phoebelovegood' ), 'after' => '</div>', ) ); ?> </div><!-- .entry-content --> <footer class="entry-footer"> <?php edit_post_link( sprintf( /* translators: %s: Name of current post */ esc_html__( 'Edit %s', 'phoebelovegood' ), the_title( '<span class="screen-reader-text">"', '"</span>', false ) ), '<span class="edit-link">', '</span>' ); ?> </footer><!-- .entry-footer --> </article><!-- #post-## --> ``` Using conditionals for my page ID, I'm trying to do this: ``` <?php if(is_page("18")): ?> <p>This is front page</p> <?php elseif: ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?> </header><!-- .entry-header --> <div class="entry-content"> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'phoebelovegood' ), 'after' => '</div>', ) ); ?> </div><!-- .entry-content --> <footer class="entry-footer"> <?php edit_post_link( sprintf( /* translators: %s: Name of current post */ esc_html__( 'Edit %s', 'phoebelovegood' ), the_title( '<span class="screen-reader-text">"', '"</span>', false ) ), '<span class="edit-link">', '</span>' ); ?> </footer><!-- .entry-footer --> </article><!-- #post-## --> <?php endif; ?> ``` Instead, I get a blank page. What do I do wrong? Code is working if used in page.php for example, when I want to add something in-between, not using elseif. Any thoughts? Thanks in advance!
Your first code sample didn't work because the `elseif` had no condition. `elseif` is a concatenation of `else` and `if`: ``` if ( something ) { } elseif ( something else ) { } else { } ``` Or ``` <?php if ( something ): ?> <?php elseif ( something else ): ?> <?php else: ?> <?php endif; ?> ``` Also, if you want a front page that's different from your other pages, look at the `front-page.php` template.
210,320
<p>The basic challenge: I have a 'normal' custom query, e.g. of news posts from a certain category and want to add in several elements (CTAs, generally speaking) at every nth position, while the loop of cta_elements (see below) is being repeated when more news posts exist than cta_elements could fill up. HTML example below, with a CTA element after every fourth (news) post:</p> <pre><code>&lt;div class="news_list"&gt; &lt;div class="news_item"&gt;&lt;/div&gt; &lt;div class="news_item"&gt;&lt;/div&gt; &lt;div class="news_item"&gt;&lt;/div&gt; &lt;div class="news_item"&gt;&lt;/div&gt; &lt;div class="cta_element" id="cta_1"&gt;Some different content&lt;/div&gt; &lt;div class="news_item"&gt;&lt;/div&gt; &lt;div class="news_item"&gt;&lt;/div&gt; &lt;div class="news_item"&gt;&lt;/div&gt; &lt;div class="news_item"&gt;&lt;/div&gt; &lt;div class="cta_element" id="cta_2"&gt;Some different content&lt;/div&gt; &lt;div class="news_item"&gt;&lt;/div&gt; &lt;div class="news_item"&gt;&lt;/div&gt; &lt;div class="news_item"&gt;&lt;/div&gt; &lt;div class="news_item"&gt;&lt;/div&gt; &lt;div class="cta_element" id="cta_3"&gt;Some different content&lt;/div&gt; &lt;div class="news_item"&gt;&lt;/div&gt; &lt;div class="news_item"&gt;&lt;/div&gt; &lt;div class="news_item"&gt;&lt;/div&gt; &lt;div class="news_item"&gt;&lt;/div&gt; &lt;!-- 1st CTA again, since there are only 3 CTAs, but more posts in news query. --&gt; &lt;div class="cta_element" id="cta_1"&gt;Some different content&lt;/div&gt; ... &lt;/div&gt; </code></pre> <p>This means in fact that a query would have to be 'paused' in order to insert single elements of another type/loop (generally speaking), which themselves repeat once there are not enough cta_elements elements that could fill in at every further nth position (see example above). </p> <p>Ideally, the cta_elements would be widgets from a custom widget area, so the user can add a) add different kinds of predefined 'widgets' to the list of cta_elements to be inserted and b) order them according to their wishes with a simple drag'n'drop and c) could have different widget areas for different loops, e.g. front page CTAs, archive page CTAs, author archive page CTAs.</p> <p>Alternatively, one could possibly go with letting out the complications widgets possibly introduce and use a custom post type (and use categories in order to have different loops on different archive pages).</p> <p>Is there any way of solving this in a simple way? Pardon me if the question itself is too complex and should be subdivided into several questions. I still want to find the most user-friendly and efficient way to solve this.</p>
[ { "answer_id": 210324, "author": "Michelle", "author_id": 16, "author_profile": "https://wordpress.stackexchange.com/users/16", "pm_score": 0, "selected": false, "text": "<p>I'd go the custom post type / custom taxonomy route. Then you can set up your archives with a for/each loop to count off the number of posts and insert the CTAs from the relevant CPT/taxonomy query.</p>\n\n<p>I've found the plugin <a href=\"https://wordpress.org/plugins/intuitive-custom-post-order/\" rel=\"nofollow\">Intuitive Custom Post Order</a> works well for this kind of thing; you can tell your users to filter the CTAs by the CTA-group taxonomy they want to organize, then drag-and-drop the CTAs into the order they want. Just make sure your CPT query is ordered by menu_order and voila.</p>\n" }, { "answer_id": 210335, "author": "Carlos Faria", "author_id": 39047, "author_profile": "https://wordpress.stackexchange.com/users/39047", "pm_score": 0, "selected": false, "text": "<p>What about sth like this?</p>\n\n<pre><code>&lt;?php $max_posts = get_option('posts_per_page '); ?&gt;\n\n&lt;?php global $paged; ?&gt;\n//Get $paged to have a good pagination index\n&lt;?php \n if ( get_query_var('paged') ) { $paged = get_query_var('paged'); }\n elseif ( get_query_var('page') ) { $paged = get_query_var('page'); }\n else { $paged = 1; } \n?&gt;\n\n//Max news per block\n&lt;?php $num_news = 4; ?&gt;\n\n//First 4 news\n&lt;section class=\"news\"&gt;\n &lt;?php $args = array('posts_per_page' =&gt; $max_posts,\n 'paged' =&gt; $paged ); ?&gt;\n &lt;?php $cont = 0; ?&gt;\n &lt;?php $query = new WP_Query( $args ); ?&gt; \n &lt;?php if ( $query-&gt;have_posts() ) : ?&gt; \n &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; \n &lt;article class=\"news_item\"&gt;\n Your code here\n &lt;/article&gt;\n &lt;?php if($cont++ &gt;= $num_news) break; //Only 4 posts/news in this block ?&gt;\n &lt;?php endwhile ?&gt; \n &lt;?php endif; ?&gt; \n&lt;/section&gt;\n\n//After break I show the first widget area \n&lt;div class=\"cta_element\" id=\"cta_1\"&gt;Your widget area 1&lt;/div&gt;\n\n//Second loop, another 4 items...\n&lt;?php if ( $query-&gt;have_posts() ) : ?&gt; \n &lt;?php $cont = 0; ?&gt;\n &lt;section class=\"news\"&gt; \n &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt;\n &lt;article class=\"news_item\"&gt;\n Your code here\n &lt;/article&gt;\n &lt;?php if($cont++ &gt;= $num_news) break; //Only 4 posts/news in this block ?&gt;\n &lt;?php endwhile ?&gt; \n &lt;/section&gt; \n&lt;?php endif; ?&gt;\n\n//Second widget area\n&lt;div class=\"cta_element\" id=\"cta_1\"&gt;Your widget area 1&lt;/div&gt;\n</code></pre>\n\n<p>Edit: To get a specific widget in a sidebar. Not too clean but I think it should work.</p>\n\n<pre><code>&lt;?php\nfunction get_widget_from_sidebar($sidebar,$widget_index){\n ob_start();\n $widgets = dynamic_sidebar($sidebar);\n if($widgets){\n $html = ob_get_contents();\n $widgets_array = explode(\"&lt;li\",$html);\n ob_end_clean();\n return $widgets_array[$widget_index];\n }\n return \"\";\n}\n\n//Call the function like this\necho get_widget_from_sidebar('id_of_sidebar', $cont);\n</code></pre>\n" }, { "answer_id": 210341, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": false, "text": "<p>If you can get an index of your post then utilize <code>%</code> for CTA breaks.</p>\n\n<pre><code>&lt;?php\n\n// Your CTA Content\n\n$cta_array = array(\n \"Some different content 1\",\n \"Some different content ABC\",\n \"Some different content XYZ\",\n);\n$cta_inx = 0; // index\n$cta_len = count($cta_array); // max\n$cta_interval = 5; // breaks every x posts\n\n// Query\n\n$args = array(\n 'posts_per_page' =&gt; 25, \n 'post_type' =&gt; 'post', \n 'post_status' =&gt; 'publish',\n 'suppress_filters' =&gt; true \n);\n\n$posts_array = get_posts( $args );\n\n// LOOP\n\n?&gt;&lt;div class=\"news_list\"&gt;&lt;?php // news_list START\n\nforeach ($posts_array as $inx =&gt; $post ){\n\n // News Item\n ?&gt;&lt;div class=\"news_item\"&gt;&lt;?php echo $post-&gt;post_title; ?&gt;&lt;/div&gt;&lt;?php\n\n // CTA\n if( $inx &amp;&amp; ! ( $inx % $cta_interval )) {\n\n if( $cta_inx == $cta_len) $cta_inx = 0; // reset the index\n\n ?&gt;&lt;div class=\"cta_element\" id=\"cta_&lt;?php echo $cta_inx; ?&gt;\"&gt;&lt;?php echo $cta_array[$cta_inx]; ?&gt;&lt;/div&gt;&lt;?php\n\n $cta_inx ++; // advance the cta\n }\n } \n?&gt;&lt;/div&gt;&lt;?php // news_list END\n</code></pre>\n\n<p>That should output:</p>\n\n<pre><code>&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\nSome different content 1\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\nSome different content ABC\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\nSome different content XYZ\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\nSome different content 1\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\nSome different content ABC\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\nSome different content XYZ\n</code></pre>\n" }, { "answer_id": 213922, "author": "physalis", "author_id": 25245, "author_profile": "https://wordpress.stackexchange.com/users/25245", "pm_score": 1, "selected": true, "text": "<p>For anyone interested in something similar, this is what a fellow pro did come up with, it’s 1. registering a specific sidebar for my widget insertion, 2. getting the DOM node from the sidebar as HTML string and 3. putting it together while looping through the available widgets. </p>\n\n<p>Put this into your <strong>functions.php</strong>:</p>\n\n<pre><code>// Register sidebar for repeated widgets\nfunction register_custom_sidebar() {\n\n register_sidebar(array(\n 'name' =&gt; \"CTAs — Home\",\n 'id' =&gt; 'widgets_home',\n 'description' =&gt; \"Widgets will be displayed after every 3rd post\",\n 'before_widget' =&gt; '&lt;li id=\"%1$s\" class=\"widget %2$s\"&gt;',\n 'after_widget' =&gt; '&lt;/li&gt;',\n 'before_title' =&gt; '&lt;h2 class=\"widgettitle\"&gt;',\n 'after_title' =&gt; '&lt;/h2&gt;',\n ));\n}\nadd_action('widgets_init', 'register_custom_sidebar');\n\n// Return dom node from other document as html string\nfunction return_dom_node_as_html($element) {\n\n $newdoc = new DOMDocument();\n $newdoc-&gt;appendChild($newdoc-&gt;importNode($element, TRUE));\n\n return $newdoc-&gt;saveHTML();\n}\n</code></pre>\n\n<p>And then create or adapt a template (e.g. page template like in this example, whatever works for you) with the following:</p>\n\n<pre><code>&lt;?php \n/* Template Name: My CTA loop page\n *\n */\nget_header();\n?&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 while (have_posts()) : the_post(); ?&gt;\n\n &lt;?php\n // Your custom query\n $args = [\n \"post_type\" =&gt; \"post\",\n \"posts_per_page\" =&gt; \"-1\"\n ];\n $custom_posts = new WP_Query($args);\n\n\n\n // Catch output of sidebar in string\n ob_start();\n dynamic_sidebar(\"widgets_home\");\n $sidebar_output = ob_get_clean();\n\n // Create DOMDocument with string (and set encoding to utf-8)\n $dom = new DOMDocument;\n $dom-&gt;loadHTML('&lt;?xml encoding=\"utf-8\" ?&gt;' . $sidebar_output);\n\n // Get IDs of the elements in your sidebar, e.g. \"text-2\"\n global $_wp_sidebars_widgets;\n $sidebar_element_ids = $_wp_sidebars_widgets[\"widgets_home\"]; // Use ID of your sidebar\n // Save single widgets as html string in array\n $sidebar_elements = [];\n\n foreach ($sidebar_element_ids as $sidebar_element_id):\n\n // Get widget by ID\n $element = $dom-&gt;getElementById($sidebar_element_id);\n // Convert it to string (function return_dom_node_as_html() must be in functions.php)\n $sidebar_elements[] = return_dom_node_as_html($element);\n\n endforeach;\n\n $widget_intervall = 3; // After how many post a widget appears\n $post_count = 0;\n $element_count = 0;\n\n while ($custom_posts-&gt;have_posts()): $custom_posts-&gt;the_post();\n\n echo \"&lt;p&gt;\" . the_title() . \"&lt;/p&gt;\"; // Whatever you want to display from your news posts (= main loop)\n\n $post_count++;\n\n if (!empty($sidebar_elements) &amp;&amp; $post_count % $widget_intervall === 0):\n\n // Echo the widget\n echo $sidebar_elements[$element_count];\n $element_count++;\n // Restart after the last widget\n if ($element_count == count($sidebar_elements)):\n $element_count = 0;\n endif;\n\n endif;\n\n endwhile;\n\n wp_reset_postdata();\n ?&gt;\n\n &lt;?php\n // If comments are open or we have at least one comment, load up the comment template\n if (comments_open() || get_comments_number()) :\n comments_template();\n endif;\n ?&gt;\n\n &lt;?php endwhile; // end of the loop. ?&gt;\n\n &lt;/main&gt;&lt;!-- #main --&gt;\n&lt;/div&gt;&lt;!-- #primary --&gt;\n&lt;?php get_sidebar(); ?&gt;\n&lt;?php get_footer(); ?&gt;\n</code></pre>\n\n<p>I had some minor trouble with the RSS widget when I insert it without data, but apart from that it seems to work fine. </p>\n" } ]
2015/11/30
[ "https://wordpress.stackexchange.com/questions/210320", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25245/" ]
The basic challenge: I have a 'normal' custom query, e.g. of news posts from a certain category and want to add in several elements (CTAs, generally speaking) at every nth position, while the loop of cta\_elements (see below) is being repeated when more news posts exist than cta\_elements could fill up. HTML example below, with a CTA element after every fourth (news) post: ``` <div class="news_list"> <div class="news_item"></div> <div class="news_item"></div> <div class="news_item"></div> <div class="news_item"></div> <div class="cta_element" id="cta_1">Some different content</div> <div class="news_item"></div> <div class="news_item"></div> <div class="news_item"></div> <div class="news_item"></div> <div class="cta_element" id="cta_2">Some different content</div> <div class="news_item"></div> <div class="news_item"></div> <div class="news_item"></div> <div class="news_item"></div> <div class="cta_element" id="cta_3">Some different content</div> <div class="news_item"></div> <div class="news_item"></div> <div class="news_item"></div> <div class="news_item"></div> <!-- 1st CTA again, since there are only 3 CTAs, but more posts in news query. --> <div class="cta_element" id="cta_1">Some different content</div> ... </div> ``` This means in fact that a query would have to be 'paused' in order to insert single elements of another type/loop (generally speaking), which themselves repeat once there are not enough cta\_elements elements that could fill in at every further nth position (see example above). Ideally, the cta\_elements would be widgets from a custom widget area, so the user can add a) add different kinds of predefined 'widgets' to the list of cta\_elements to be inserted and b) order them according to their wishes with a simple drag'n'drop and c) could have different widget areas for different loops, e.g. front page CTAs, archive page CTAs, author archive page CTAs. Alternatively, one could possibly go with letting out the complications widgets possibly introduce and use a custom post type (and use categories in order to have different loops on different archive pages). Is there any way of solving this in a simple way? Pardon me if the question itself is too complex and should be subdivided into several questions. I still want to find the most user-friendly and efficient way to solve this.
For anyone interested in something similar, this is what a fellow pro did come up with, it’s 1. registering a specific sidebar for my widget insertion, 2. getting the DOM node from the sidebar as HTML string and 3. putting it together while looping through the available widgets. Put this into your **functions.php**: ``` // Register sidebar for repeated widgets function register_custom_sidebar() { register_sidebar(array( 'name' => "CTAs — Home", 'id' => 'widgets_home', 'description' => "Widgets will be displayed after every 3rd post", 'before_widget' => '<li id="%1$s" class="widget %2$s">', 'after_widget' => '</li>', 'before_title' => '<h2 class="widgettitle">', 'after_title' => '</h2>', )); } add_action('widgets_init', 'register_custom_sidebar'); // Return dom node from other document as html string function return_dom_node_as_html($element) { $newdoc = new DOMDocument(); $newdoc->appendChild($newdoc->importNode($element, TRUE)); return $newdoc->saveHTML(); } ``` And then create or adapt a template (e.g. page template like in this example, whatever works for you) with the following: ``` <?php /* Template Name: My CTA loop page * */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php while (have_posts()) : the_post(); ?> <?php // Your custom query $args = [ "post_type" => "post", "posts_per_page" => "-1" ]; $custom_posts = new WP_Query($args); // Catch output of sidebar in string ob_start(); dynamic_sidebar("widgets_home"); $sidebar_output = ob_get_clean(); // Create DOMDocument with string (and set encoding to utf-8) $dom = new DOMDocument; $dom->loadHTML('<?xml encoding="utf-8" ?>' . $sidebar_output); // Get IDs of the elements in your sidebar, e.g. "text-2" global $_wp_sidebars_widgets; $sidebar_element_ids = $_wp_sidebars_widgets["widgets_home"]; // Use ID of your sidebar // Save single widgets as html string in array $sidebar_elements = []; foreach ($sidebar_element_ids as $sidebar_element_id): // Get widget by ID $element = $dom->getElementById($sidebar_element_id); // Convert it to string (function return_dom_node_as_html() must be in functions.php) $sidebar_elements[] = return_dom_node_as_html($element); endforeach; $widget_intervall = 3; // After how many post a widget appears $post_count = 0; $element_count = 0; while ($custom_posts->have_posts()): $custom_posts->the_post(); echo "<p>" . the_title() . "</p>"; // Whatever you want to display from your news posts (= main loop) $post_count++; if (!empty($sidebar_elements) && $post_count % $widget_intervall === 0): // Echo the widget echo $sidebar_elements[$element_count]; $element_count++; // Restart after the last widget if ($element_count == count($sidebar_elements)): $element_count = 0; endif; endif; endwhile; wp_reset_postdata(); ?> <?php // If comments are open or we have at least one comment, load up the comment template if (comments_open() || get_comments_number()) : comments_template(); endif; ?> <?php endwhile; // end of the loop. ?> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?> ``` I had some minor trouble with the RSS widget when I insert it without data, but apart from that it seems to work fine.
210,322
<p>I'm setting up some transactionals emails on my site and I'd like to send one 3 days after a user signed up if he didn't post. Here is what I have:</p> <pre><code>function set_mail_html_content_type() { return 'text/html'; } add_action( 'user_help_signup', 10 ,2 ); function user_help_signup( $ID, //DURATION SINCE SIGN UP ) { if ( //DURATION SINCE SIGN UP &gt; 3days || count_user_posts( $post-&gt;post_author ) &gt; 1 ) return; $to = get_user_by( 'id', $post-&gt;post_author )-&gt;user_email; $subject = 'Need help ?'; $headers = array('Content-Type: text/html'); $message = '&lt;h3&gt;Hi {display_name}! &lt;/h3&gt; &lt;p&gt; You signed up 3 days ago on mysite.com and we wanted to know if we could help you to get started '; wp_mail( $to, $subject, $message, 'Content-Type: text/html' ); } </code></pre> <p>However, I can't find any info on how to retrieve the duration since sign up. How can I achieve this?</p>
[ { "answer_id": 210324, "author": "Michelle", "author_id": 16, "author_profile": "https://wordpress.stackexchange.com/users/16", "pm_score": 0, "selected": false, "text": "<p>I'd go the custom post type / custom taxonomy route. Then you can set up your archives with a for/each loop to count off the number of posts and insert the CTAs from the relevant CPT/taxonomy query.</p>\n\n<p>I've found the plugin <a href=\"https://wordpress.org/plugins/intuitive-custom-post-order/\" rel=\"nofollow\">Intuitive Custom Post Order</a> works well for this kind of thing; you can tell your users to filter the CTAs by the CTA-group taxonomy they want to organize, then drag-and-drop the CTAs into the order they want. Just make sure your CPT query is ordered by menu_order and voila.</p>\n" }, { "answer_id": 210335, "author": "Carlos Faria", "author_id": 39047, "author_profile": "https://wordpress.stackexchange.com/users/39047", "pm_score": 0, "selected": false, "text": "<p>What about sth like this?</p>\n\n<pre><code>&lt;?php $max_posts = get_option('posts_per_page '); ?&gt;\n\n&lt;?php global $paged; ?&gt;\n//Get $paged to have a good pagination index\n&lt;?php \n if ( get_query_var('paged') ) { $paged = get_query_var('paged'); }\n elseif ( get_query_var('page') ) { $paged = get_query_var('page'); }\n else { $paged = 1; } \n?&gt;\n\n//Max news per block\n&lt;?php $num_news = 4; ?&gt;\n\n//First 4 news\n&lt;section class=\"news\"&gt;\n &lt;?php $args = array('posts_per_page' =&gt; $max_posts,\n 'paged' =&gt; $paged ); ?&gt;\n &lt;?php $cont = 0; ?&gt;\n &lt;?php $query = new WP_Query( $args ); ?&gt; \n &lt;?php if ( $query-&gt;have_posts() ) : ?&gt; \n &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; \n &lt;article class=\"news_item\"&gt;\n Your code here\n &lt;/article&gt;\n &lt;?php if($cont++ &gt;= $num_news) break; //Only 4 posts/news in this block ?&gt;\n &lt;?php endwhile ?&gt; \n &lt;?php endif; ?&gt; \n&lt;/section&gt;\n\n//After break I show the first widget area \n&lt;div class=\"cta_element\" id=\"cta_1\"&gt;Your widget area 1&lt;/div&gt;\n\n//Second loop, another 4 items...\n&lt;?php if ( $query-&gt;have_posts() ) : ?&gt; \n &lt;?php $cont = 0; ?&gt;\n &lt;section class=\"news\"&gt; \n &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt;\n &lt;article class=\"news_item\"&gt;\n Your code here\n &lt;/article&gt;\n &lt;?php if($cont++ &gt;= $num_news) break; //Only 4 posts/news in this block ?&gt;\n &lt;?php endwhile ?&gt; \n &lt;/section&gt; \n&lt;?php endif; ?&gt;\n\n//Second widget area\n&lt;div class=\"cta_element\" id=\"cta_1\"&gt;Your widget area 1&lt;/div&gt;\n</code></pre>\n\n<p>Edit: To get a specific widget in a sidebar. Not too clean but I think it should work.</p>\n\n<pre><code>&lt;?php\nfunction get_widget_from_sidebar($sidebar,$widget_index){\n ob_start();\n $widgets = dynamic_sidebar($sidebar);\n if($widgets){\n $html = ob_get_contents();\n $widgets_array = explode(\"&lt;li\",$html);\n ob_end_clean();\n return $widgets_array[$widget_index];\n }\n return \"\";\n}\n\n//Call the function like this\necho get_widget_from_sidebar('id_of_sidebar', $cont);\n</code></pre>\n" }, { "answer_id": 210341, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": false, "text": "<p>If you can get an index of your post then utilize <code>%</code> for CTA breaks.</p>\n\n<pre><code>&lt;?php\n\n// Your CTA Content\n\n$cta_array = array(\n \"Some different content 1\",\n \"Some different content ABC\",\n \"Some different content XYZ\",\n);\n$cta_inx = 0; // index\n$cta_len = count($cta_array); // max\n$cta_interval = 5; // breaks every x posts\n\n// Query\n\n$args = array(\n 'posts_per_page' =&gt; 25, \n 'post_type' =&gt; 'post', \n 'post_status' =&gt; 'publish',\n 'suppress_filters' =&gt; true \n);\n\n$posts_array = get_posts( $args );\n\n// LOOP\n\n?&gt;&lt;div class=\"news_list\"&gt;&lt;?php // news_list START\n\nforeach ($posts_array as $inx =&gt; $post ){\n\n // News Item\n ?&gt;&lt;div class=\"news_item\"&gt;&lt;?php echo $post-&gt;post_title; ?&gt;&lt;/div&gt;&lt;?php\n\n // CTA\n if( $inx &amp;&amp; ! ( $inx % $cta_interval )) {\n\n if( $cta_inx == $cta_len) $cta_inx = 0; // reset the index\n\n ?&gt;&lt;div class=\"cta_element\" id=\"cta_&lt;?php echo $cta_inx; ?&gt;\"&gt;&lt;?php echo $cta_array[$cta_inx]; ?&gt;&lt;/div&gt;&lt;?php\n\n $cta_inx ++; // advance the cta\n }\n } \n?&gt;&lt;/div&gt;&lt;?php // news_list END\n</code></pre>\n\n<p>That should output:</p>\n\n<pre><code>&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\nSome different content 1\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\nSome different content ABC\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\nSome different content XYZ\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\nSome different content 1\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\nSome different content ABC\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\nSome different content XYZ\n</code></pre>\n" }, { "answer_id": 213922, "author": "physalis", "author_id": 25245, "author_profile": "https://wordpress.stackexchange.com/users/25245", "pm_score": 1, "selected": true, "text": "<p>For anyone interested in something similar, this is what a fellow pro did come up with, it’s 1. registering a specific sidebar for my widget insertion, 2. getting the DOM node from the sidebar as HTML string and 3. putting it together while looping through the available widgets. </p>\n\n<p>Put this into your <strong>functions.php</strong>:</p>\n\n<pre><code>// Register sidebar for repeated widgets\nfunction register_custom_sidebar() {\n\n register_sidebar(array(\n 'name' =&gt; \"CTAs — Home\",\n 'id' =&gt; 'widgets_home',\n 'description' =&gt; \"Widgets will be displayed after every 3rd post\",\n 'before_widget' =&gt; '&lt;li id=\"%1$s\" class=\"widget %2$s\"&gt;',\n 'after_widget' =&gt; '&lt;/li&gt;',\n 'before_title' =&gt; '&lt;h2 class=\"widgettitle\"&gt;',\n 'after_title' =&gt; '&lt;/h2&gt;',\n ));\n}\nadd_action('widgets_init', 'register_custom_sidebar');\n\n// Return dom node from other document as html string\nfunction return_dom_node_as_html($element) {\n\n $newdoc = new DOMDocument();\n $newdoc-&gt;appendChild($newdoc-&gt;importNode($element, TRUE));\n\n return $newdoc-&gt;saveHTML();\n}\n</code></pre>\n\n<p>And then create or adapt a template (e.g. page template like in this example, whatever works for you) with the following:</p>\n\n<pre><code>&lt;?php \n/* Template Name: My CTA loop page\n *\n */\nget_header();\n?&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 while (have_posts()) : the_post(); ?&gt;\n\n &lt;?php\n // Your custom query\n $args = [\n \"post_type\" =&gt; \"post\",\n \"posts_per_page\" =&gt; \"-1\"\n ];\n $custom_posts = new WP_Query($args);\n\n\n\n // Catch output of sidebar in string\n ob_start();\n dynamic_sidebar(\"widgets_home\");\n $sidebar_output = ob_get_clean();\n\n // Create DOMDocument with string (and set encoding to utf-8)\n $dom = new DOMDocument;\n $dom-&gt;loadHTML('&lt;?xml encoding=\"utf-8\" ?&gt;' . $sidebar_output);\n\n // Get IDs of the elements in your sidebar, e.g. \"text-2\"\n global $_wp_sidebars_widgets;\n $sidebar_element_ids = $_wp_sidebars_widgets[\"widgets_home\"]; // Use ID of your sidebar\n // Save single widgets as html string in array\n $sidebar_elements = [];\n\n foreach ($sidebar_element_ids as $sidebar_element_id):\n\n // Get widget by ID\n $element = $dom-&gt;getElementById($sidebar_element_id);\n // Convert it to string (function return_dom_node_as_html() must be in functions.php)\n $sidebar_elements[] = return_dom_node_as_html($element);\n\n endforeach;\n\n $widget_intervall = 3; // After how many post a widget appears\n $post_count = 0;\n $element_count = 0;\n\n while ($custom_posts-&gt;have_posts()): $custom_posts-&gt;the_post();\n\n echo \"&lt;p&gt;\" . the_title() . \"&lt;/p&gt;\"; // Whatever you want to display from your news posts (= main loop)\n\n $post_count++;\n\n if (!empty($sidebar_elements) &amp;&amp; $post_count % $widget_intervall === 0):\n\n // Echo the widget\n echo $sidebar_elements[$element_count];\n $element_count++;\n // Restart after the last widget\n if ($element_count == count($sidebar_elements)):\n $element_count = 0;\n endif;\n\n endif;\n\n endwhile;\n\n wp_reset_postdata();\n ?&gt;\n\n &lt;?php\n // If comments are open or we have at least one comment, load up the comment template\n if (comments_open() || get_comments_number()) :\n comments_template();\n endif;\n ?&gt;\n\n &lt;?php endwhile; // end of the loop. ?&gt;\n\n &lt;/main&gt;&lt;!-- #main --&gt;\n&lt;/div&gt;&lt;!-- #primary --&gt;\n&lt;?php get_sidebar(); ?&gt;\n&lt;?php get_footer(); ?&gt;\n</code></pre>\n\n<p>I had some minor trouble with the RSS widget when I insert it without data, but apart from that it seems to work fine. </p>\n" } ]
2015/11/30
[ "https://wordpress.stackexchange.com/questions/210322", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68671/" ]
I'm setting up some transactionals emails on my site and I'd like to send one 3 days after a user signed up if he didn't post. Here is what I have: ``` function set_mail_html_content_type() { return 'text/html'; } add_action( 'user_help_signup', 10 ,2 ); function user_help_signup( $ID, //DURATION SINCE SIGN UP ) { if ( //DURATION SINCE SIGN UP > 3days || count_user_posts( $post->post_author ) > 1 ) return; $to = get_user_by( 'id', $post->post_author )->user_email; $subject = 'Need help ?'; $headers = array('Content-Type: text/html'); $message = '<h3>Hi {display_name}! </h3> <p> You signed up 3 days ago on mysite.com and we wanted to know if we could help you to get started '; wp_mail( $to, $subject, $message, 'Content-Type: text/html' ); } ``` However, I can't find any info on how to retrieve the duration since sign up. How can I achieve this?
For anyone interested in something similar, this is what a fellow pro did come up with, it’s 1. registering a specific sidebar for my widget insertion, 2. getting the DOM node from the sidebar as HTML string and 3. putting it together while looping through the available widgets. Put this into your **functions.php**: ``` // Register sidebar for repeated widgets function register_custom_sidebar() { register_sidebar(array( 'name' => "CTAs — Home", 'id' => 'widgets_home', 'description' => "Widgets will be displayed after every 3rd post", 'before_widget' => '<li id="%1$s" class="widget %2$s">', 'after_widget' => '</li>', 'before_title' => '<h2 class="widgettitle">', 'after_title' => '</h2>', )); } add_action('widgets_init', 'register_custom_sidebar'); // Return dom node from other document as html string function return_dom_node_as_html($element) { $newdoc = new DOMDocument(); $newdoc->appendChild($newdoc->importNode($element, TRUE)); return $newdoc->saveHTML(); } ``` And then create or adapt a template (e.g. page template like in this example, whatever works for you) with the following: ``` <?php /* Template Name: My CTA loop page * */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php while (have_posts()) : the_post(); ?> <?php // Your custom query $args = [ "post_type" => "post", "posts_per_page" => "-1" ]; $custom_posts = new WP_Query($args); // Catch output of sidebar in string ob_start(); dynamic_sidebar("widgets_home"); $sidebar_output = ob_get_clean(); // Create DOMDocument with string (and set encoding to utf-8) $dom = new DOMDocument; $dom->loadHTML('<?xml encoding="utf-8" ?>' . $sidebar_output); // Get IDs of the elements in your sidebar, e.g. "text-2" global $_wp_sidebars_widgets; $sidebar_element_ids = $_wp_sidebars_widgets["widgets_home"]; // Use ID of your sidebar // Save single widgets as html string in array $sidebar_elements = []; foreach ($sidebar_element_ids as $sidebar_element_id): // Get widget by ID $element = $dom->getElementById($sidebar_element_id); // Convert it to string (function return_dom_node_as_html() must be in functions.php) $sidebar_elements[] = return_dom_node_as_html($element); endforeach; $widget_intervall = 3; // After how many post a widget appears $post_count = 0; $element_count = 0; while ($custom_posts->have_posts()): $custom_posts->the_post(); echo "<p>" . the_title() . "</p>"; // Whatever you want to display from your news posts (= main loop) $post_count++; if (!empty($sidebar_elements) && $post_count % $widget_intervall === 0): // Echo the widget echo $sidebar_elements[$element_count]; $element_count++; // Restart after the last widget if ($element_count == count($sidebar_elements)): $element_count = 0; endif; endif; endwhile; wp_reset_postdata(); ?> <?php // If comments are open or we have at least one comment, load up the comment template if (comments_open() || get_comments_number()) : comments_template(); endif; ?> <?php endwhile; // end of the loop. ?> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?> ``` I had some minor trouble with the RSS widget when I insert it without data, but apart from that it seems to work fine.
210,330
<p>How do I change specific section background image in wordpress?</p> <p>I have a background image set via CSS:</p> <pre><code>.section3 { background: url(bg.jpg) no repeat; } </code></pre> <p>Say I want to change this image later via the WordPress dashboard. How would I do this? I want to add functionality so that user can change the image in future.</p> <p>The default background function only enables the user to change the background color on the page. I want to target this specific section.</p>
[ { "answer_id": 210324, "author": "Michelle", "author_id": 16, "author_profile": "https://wordpress.stackexchange.com/users/16", "pm_score": 0, "selected": false, "text": "<p>I'd go the custom post type / custom taxonomy route. Then you can set up your archives with a for/each loop to count off the number of posts and insert the CTAs from the relevant CPT/taxonomy query.</p>\n\n<p>I've found the plugin <a href=\"https://wordpress.org/plugins/intuitive-custom-post-order/\" rel=\"nofollow\">Intuitive Custom Post Order</a> works well for this kind of thing; you can tell your users to filter the CTAs by the CTA-group taxonomy they want to organize, then drag-and-drop the CTAs into the order they want. Just make sure your CPT query is ordered by menu_order and voila.</p>\n" }, { "answer_id": 210335, "author": "Carlos Faria", "author_id": 39047, "author_profile": "https://wordpress.stackexchange.com/users/39047", "pm_score": 0, "selected": false, "text": "<p>What about sth like this?</p>\n\n<pre><code>&lt;?php $max_posts = get_option('posts_per_page '); ?&gt;\n\n&lt;?php global $paged; ?&gt;\n//Get $paged to have a good pagination index\n&lt;?php \n if ( get_query_var('paged') ) { $paged = get_query_var('paged'); }\n elseif ( get_query_var('page') ) { $paged = get_query_var('page'); }\n else { $paged = 1; } \n?&gt;\n\n//Max news per block\n&lt;?php $num_news = 4; ?&gt;\n\n//First 4 news\n&lt;section class=\"news\"&gt;\n &lt;?php $args = array('posts_per_page' =&gt; $max_posts,\n 'paged' =&gt; $paged ); ?&gt;\n &lt;?php $cont = 0; ?&gt;\n &lt;?php $query = new WP_Query( $args ); ?&gt; \n &lt;?php if ( $query-&gt;have_posts() ) : ?&gt; \n &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; \n &lt;article class=\"news_item\"&gt;\n Your code here\n &lt;/article&gt;\n &lt;?php if($cont++ &gt;= $num_news) break; //Only 4 posts/news in this block ?&gt;\n &lt;?php endwhile ?&gt; \n &lt;?php endif; ?&gt; \n&lt;/section&gt;\n\n//After break I show the first widget area \n&lt;div class=\"cta_element\" id=\"cta_1\"&gt;Your widget area 1&lt;/div&gt;\n\n//Second loop, another 4 items...\n&lt;?php if ( $query-&gt;have_posts() ) : ?&gt; \n &lt;?php $cont = 0; ?&gt;\n &lt;section class=\"news\"&gt; \n &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt;\n &lt;article class=\"news_item\"&gt;\n Your code here\n &lt;/article&gt;\n &lt;?php if($cont++ &gt;= $num_news) break; //Only 4 posts/news in this block ?&gt;\n &lt;?php endwhile ?&gt; \n &lt;/section&gt; \n&lt;?php endif; ?&gt;\n\n//Second widget area\n&lt;div class=\"cta_element\" id=\"cta_1\"&gt;Your widget area 1&lt;/div&gt;\n</code></pre>\n\n<p>Edit: To get a specific widget in a sidebar. Not too clean but I think it should work.</p>\n\n<pre><code>&lt;?php\nfunction get_widget_from_sidebar($sidebar,$widget_index){\n ob_start();\n $widgets = dynamic_sidebar($sidebar);\n if($widgets){\n $html = ob_get_contents();\n $widgets_array = explode(\"&lt;li\",$html);\n ob_end_clean();\n return $widgets_array[$widget_index];\n }\n return \"\";\n}\n\n//Call the function like this\necho get_widget_from_sidebar('id_of_sidebar', $cont);\n</code></pre>\n" }, { "answer_id": 210341, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": false, "text": "<p>If you can get an index of your post then utilize <code>%</code> for CTA breaks.</p>\n\n<pre><code>&lt;?php\n\n// Your CTA Content\n\n$cta_array = array(\n \"Some different content 1\",\n \"Some different content ABC\",\n \"Some different content XYZ\",\n);\n$cta_inx = 0; // index\n$cta_len = count($cta_array); // max\n$cta_interval = 5; // breaks every x posts\n\n// Query\n\n$args = array(\n 'posts_per_page' =&gt; 25, \n 'post_type' =&gt; 'post', \n 'post_status' =&gt; 'publish',\n 'suppress_filters' =&gt; true \n);\n\n$posts_array = get_posts( $args );\n\n// LOOP\n\n?&gt;&lt;div class=\"news_list\"&gt;&lt;?php // news_list START\n\nforeach ($posts_array as $inx =&gt; $post ){\n\n // News Item\n ?&gt;&lt;div class=\"news_item\"&gt;&lt;?php echo $post-&gt;post_title; ?&gt;&lt;/div&gt;&lt;?php\n\n // CTA\n if( $inx &amp;&amp; ! ( $inx % $cta_interval )) {\n\n if( $cta_inx == $cta_len) $cta_inx = 0; // reset the index\n\n ?&gt;&lt;div class=\"cta_element\" id=\"cta_&lt;?php echo $cta_inx; ?&gt;\"&gt;&lt;?php echo $cta_array[$cta_inx]; ?&gt;&lt;/div&gt;&lt;?php\n\n $cta_inx ++; // advance the cta\n }\n } \n?&gt;&lt;/div&gt;&lt;?php // news_list END\n</code></pre>\n\n<p>That should output:</p>\n\n<pre><code>&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\nSome different content 1\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\nSome different content ABC\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\nSome different content XYZ\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\nSome different content 1\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\nSome different content ABC\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\n&gt; Post Title\nSome different content XYZ\n</code></pre>\n" }, { "answer_id": 213922, "author": "physalis", "author_id": 25245, "author_profile": "https://wordpress.stackexchange.com/users/25245", "pm_score": 1, "selected": true, "text": "<p>For anyone interested in something similar, this is what a fellow pro did come up with, it’s 1. registering a specific sidebar for my widget insertion, 2. getting the DOM node from the sidebar as HTML string and 3. putting it together while looping through the available widgets. </p>\n\n<p>Put this into your <strong>functions.php</strong>:</p>\n\n<pre><code>// Register sidebar for repeated widgets\nfunction register_custom_sidebar() {\n\n register_sidebar(array(\n 'name' =&gt; \"CTAs — Home\",\n 'id' =&gt; 'widgets_home',\n 'description' =&gt; \"Widgets will be displayed after every 3rd post\",\n 'before_widget' =&gt; '&lt;li id=\"%1$s\" class=\"widget %2$s\"&gt;',\n 'after_widget' =&gt; '&lt;/li&gt;',\n 'before_title' =&gt; '&lt;h2 class=\"widgettitle\"&gt;',\n 'after_title' =&gt; '&lt;/h2&gt;',\n ));\n}\nadd_action('widgets_init', 'register_custom_sidebar');\n\n// Return dom node from other document as html string\nfunction return_dom_node_as_html($element) {\n\n $newdoc = new DOMDocument();\n $newdoc-&gt;appendChild($newdoc-&gt;importNode($element, TRUE));\n\n return $newdoc-&gt;saveHTML();\n}\n</code></pre>\n\n<p>And then create or adapt a template (e.g. page template like in this example, whatever works for you) with the following:</p>\n\n<pre><code>&lt;?php \n/* Template Name: My CTA loop page\n *\n */\nget_header();\n?&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 while (have_posts()) : the_post(); ?&gt;\n\n &lt;?php\n // Your custom query\n $args = [\n \"post_type\" =&gt; \"post\",\n \"posts_per_page\" =&gt; \"-1\"\n ];\n $custom_posts = new WP_Query($args);\n\n\n\n // Catch output of sidebar in string\n ob_start();\n dynamic_sidebar(\"widgets_home\");\n $sidebar_output = ob_get_clean();\n\n // Create DOMDocument with string (and set encoding to utf-8)\n $dom = new DOMDocument;\n $dom-&gt;loadHTML('&lt;?xml encoding=\"utf-8\" ?&gt;' . $sidebar_output);\n\n // Get IDs of the elements in your sidebar, e.g. \"text-2\"\n global $_wp_sidebars_widgets;\n $sidebar_element_ids = $_wp_sidebars_widgets[\"widgets_home\"]; // Use ID of your sidebar\n // Save single widgets as html string in array\n $sidebar_elements = [];\n\n foreach ($sidebar_element_ids as $sidebar_element_id):\n\n // Get widget by ID\n $element = $dom-&gt;getElementById($sidebar_element_id);\n // Convert it to string (function return_dom_node_as_html() must be in functions.php)\n $sidebar_elements[] = return_dom_node_as_html($element);\n\n endforeach;\n\n $widget_intervall = 3; // After how many post a widget appears\n $post_count = 0;\n $element_count = 0;\n\n while ($custom_posts-&gt;have_posts()): $custom_posts-&gt;the_post();\n\n echo \"&lt;p&gt;\" . the_title() . \"&lt;/p&gt;\"; // Whatever you want to display from your news posts (= main loop)\n\n $post_count++;\n\n if (!empty($sidebar_elements) &amp;&amp; $post_count % $widget_intervall === 0):\n\n // Echo the widget\n echo $sidebar_elements[$element_count];\n $element_count++;\n // Restart after the last widget\n if ($element_count == count($sidebar_elements)):\n $element_count = 0;\n endif;\n\n endif;\n\n endwhile;\n\n wp_reset_postdata();\n ?&gt;\n\n &lt;?php\n // If comments are open or we have at least one comment, load up the comment template\n if (comments_open() || get_comments_number()) :\n comments_template();\n endif;\n ?&gt;\n\n &lt;?php endwhile; // end of the loop. ?&gt;\n\n &lt;/main&gt;&lt;!-- #main --&gt;\n&lt;/div&gt;&lt;!-- #primary --&gt;\n&lt;?php get_sidebar(); ?&gt;\n&lt;?php get_footer(); ?&gt;\n</code></pre>\n\n<p>I had some minor trouble with the RSS widget when I insert it without data, but apart from that it seems to work fine. </p>\n" } ]
2015/11/30
[ "https://wordpress.stackexchange.com/questions/210330", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84503/" ]
How do I change specific section background image in wordpress? I have a background image set via CSS: ``` .section3 { background: url(bg.jpg) no repeat; } ``` Say I want to change this image later via the WordPress dashboard. How would I do this? I want to add functionality so that user can change the image in future. The default background function only enables the user to change the background color on the page. I want to target this specific section.
For anyone interested in something similar, this is what a fellow pro did come up with, it’s 1. registering a specific sidebar for my widget insertion, 2. getting the DOM node from the sidebar as HTML string and 3. putting it together while looping through the available widgets. Put this into your **functions.php**: ``` // Register sidebar for repeated widgets function register_custom_sidebar() { register_sidebar(array( 'name' => "CTAs — Home", 'id' => 'widgets_home', 'description' => "Widgets will be displayed after every 3rd post", 'before_widget' => '<li id="%1$s" class="widget %2$s">', 'after_widget' => '</li>', 'before_title' => '<h2 class="widgettitle">', 'after_title' => '</h2>', )); } add_action('widgets_init', 'register_custom_sidebar'); // Return dom node from other document as html string function return_dom_node_as_html($element) { $newdoc = new DOMDocument(); $newdoc->appendChild($newdoc->importNode($element, TRUE)); return $newdoc->saveHTML(); } ``` And then create or adapt a template (e.g. page template like in this example, whatever works for you) with the following: ``` <?php /* Template Name: My CTA loop page * */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php while (have_posts()) : the_post(); ?> <?php // Your custom query $args = [ "post_type" => "post", "posts_per_page" => "-1" ]; $custom_posts = new WP_Query($args); // Catch output of sidebar in string ob_start(); dynamic_sidebar("widgets_home"); $sidebar_output = ob_get_clean(); // Create DOMDocument with string (and set encoding to utf-8) $dom = new DOMDocument; $dom->loadHTML('<?xml encoding="utf-8" ?>' . $sidebar_output); // Get IDs of the elements in your sidebar, e.g. "text-2" global $_wp_sidebars_widgets; $sidebar_element_ids = $_wp_sidebars_widgets["widgets_home"]; // Use ID of your sidebar // Save single widgets as html string in array $sidebar_elements = []; foreach ($sidebar_element_ids as $sidebar_element_id): // Get widget by ID $element = $dom->getElementById($sidebar_element_id); // Convert it to string (function return_dom_node_as_html() must be in functions.php) $sidebar_elements[] = return_dom_node_as_html($element); endforeach; $widget_intervall = 3; // After how many post a widget appears $post_count = 0; $element_count = 0; while ($custom_posts->have_posts()): $custom_posts->the_post(); echo "<p>" . the_title() . "</p>"; // Whatever you want to display from your news posts (= main loop) $post_count++; if (!empty($sidebar_elements) && $post_count % $widget_intervall === 0): // Echo the widget echo $sidebar_elements[$element_count]; $element_count++; // Restart after the last widget if ($element_count == count($sidebar_elements)): $element_count = 0; endif; endif; endwhile; wp_reset_postdata(); ?> <?php // If comments are open or we have at least one comment, load up the comment template if (comments_open() || get_comments_number()) : comments_template(); endif; ?> <?php endwhile; // end of the loop. ?> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?> ``` I had some minor trouble with the RSS widget when I insert it without data, but apart from that it seems to work fine.
210,358
<p>I've tried searching for this using various terminology, but I always end up at questions pertaining to the php template files. That's not what I'm looking for, so I'm asking a new question. I apologize if this is a duplicate.</p> <p>Basically, I'm looking for a way to create template posts. I'm using ACF Pro on a custom "Job" post type, and I've got a Repeater Field set up for "Job Steps."</p> <p>To give an example, a "Make a Pizza" Job would have the following steps:</p> <ol> <li>Ordered</li> <li>Prep</li> <li>Bake</li> <li>Box</li> <li>Deliver</li> </ol> <p>The way things are currently set up, users will need to manually define these steps each and every time, so what I would like to do is create a "Pizza Template" post that users can use to define the steps once, and then adding a new "Make a Pizza" job will automatically define the steps but allows users to fill in the specific details like toppings, crust, delivery address, etc.</p> <p>One of the things I thought about doing was adding a new "Job Template" post type that uses the same custom field definition as the "Job" type. Then, when users create a new Job, they would be prompted to pick a "Job Template".</p> <p>If they chose "Pizza Template", it would copy the Repeater Field values from the Job Template post and set them in the editor for the new Job. I suspect that would be a very convoluted process, so I'm hoping that someone knows a more efficient way somewhere in the core.</p> <h2>Edit</h2> <p>Based on comments, I see that one aspect of this question wasn't as clear as I thought, so to give more info:</p> <p>I'm trying to create a generic Tracker plugin that can be customized by users at runtime to fit a variety of workflows. The Repeater Field gives me that flexibility, but efficient use depends on templates. Users define their workflow once as a template and then use that template when creating new Jobs.</p> <p>This approach also allows users to define multiple workflows without the need for multiple field groups or multiple post types.</p> <p>I'm working on a few possible solutions myself (and will post answers when I get there), but I'm really hoping there's something in the core that I can leverage to make this easier.</p>
[ { "answer_id": 210363, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p>It's possible you may have to define your own <a href=\"http://www.advancedcustomfields.com/resources/creating-a-new-field-type/\" rel=\"nofollow\">ACF Custom Field Type</a> which holds your templates. And after a template is selected then you would programmatically copy the fields to a <a href=\"http://www.advancedcustomfields.com/resources/repeater/\" rel=\"nofollow\">repeater</a>. <a href=\"https://github.com/navidkashani/awesome-acf\" rel=\"nofollow\">Awesome ACF</a> has quite a few examples, WordPress has quite a few <a href=\"https://wordpress.org/plugins/search.php?q=Advanced+Custom+Fields\" rel=\"nofollow\">plugins</a> and there is a <a href=\"http://support.advancedcustomfields.com/forums/forum/add-ons/user-submitted/\" rel=\"nofollow\">User Submitted Add-Ons</a> support forum.</p>\n" }, { "answer_id": 211299, "author": "Mike", "author_id": 45704, "author_profile": "https://wordpress.stackexchange.com/users/45704", "pm_score": 0, "selected": false, "text": "<p>I was able to pull this off with a second post type and a little bit of JavaScript.</p>\n\n<h2>Step 1: Assign the ACF Field Group</h2>\n\n<p>I already had the <strong>Job Steps</strong> field group defined, so I modified the setup a bit and assigned it to both Jobs and Job Archetypes:</p>\n\n<pre><code>// [...] This is a snip from the full custom field setup\n'location' =&gt; array (\n array (\n array (\n 'param' =&gt; 'post_type',\n 'operator' =&gt; '==',\n 'value' =&gt; 'my-job',\n ),\n ),\n\n array (\n array (\n 'param' =&gt; 'post_type',\n 'operator' =&gt; '==',\n 'value' =&gt; 'my-job-archetype',\n ),\n ),\n),\n</code></pre>\n\n<p>Now I can access Job Steps in the same way for poth content types.</p>\n\n<hr>\n\n<h2>Step 2: Register a Custom Query Var</h2>\n\n<p>The next thing I did was add a custom query variable for the Archetype post ID:</p>\n\n<pre><code>function my_registerArchetypeQueryVar($vars) {\n $vars[] = 'archetypeId;\n return $vars;\n}\nadd_filter('query_vars', 'my_registerArchetypeQueryVar');\n</code></pre>\n\n<hr>\n\n<h2>Step 3: Front End Form - Edit Archetype</h2>\n\n<p>Next, I created an Edit Archetype page with the following:</p>\n\n<pre><code>if(get_query_var('archetypeId')) {\n $id = get_query_var('archetypeId');\n\n $jobArchetype = get_post($id);\n\n if ($jobArchetype) {\n acf_form(array(\n \"id\" =&gt; \"editJobForm\",\n \"post_id\" =&gt; $id,\n \"post_title\" =&gt; true,\n 'field_groups' =&gt; array('my_jobStepFields'),\n \"return\" =&gt; \"%post_url%\",\n \"submit_value\" =&gt; __(\"Update Archetype\", 'acf'),\n ));\n } else {\n acf_form(array(\n \"id\" =&gt; \"addJobForm\",\n \"post_id\" =&gt; 'new_post',\n 'new_post' =&gt; array(\n 'post_type' =&gt; 'my-job-archetype',\n 'post_status' =&gt; 'publish'\n ),\n \"post_title\" =&gt; true,\n 'field_groups' =&gt; array('my_jobStepFields'),\n \"return\" =&gt; \"%post_url%\",\n \"submit_value\" =&gt; __(\"Add Archetype\", 'acf'),\n ));\n }\n}\n</code></pre>\n\n<p>On the this page, I grab the <code>archetypeId</code> query var and use that to pull up an ACF form for the specified post. (And if no <code>archetypeId</code> is provided, I render a New Archetype form instead.</p>\n\n<hr>\n\n<h2>Step 4: Front End Form - New Job</h2>\n\n<p>Next, I created a New Job page with the following:</p>\n\n<pre><code>$id = get_query_var('archetypeId');\n$jobArchetype = get_post($id);\n\n\nif ($jobArchetype) { ?&gt;\n &lt;script&gt;\n $(document).ready(function() {\n my_loadJobArchetype();\n });\n\n function my_loadJobArchetype() {\n $('&lt;div&gt;').load(\"&lt;?php echo get_page_by_path('edit-archetype') \n . \"?archetypeId=\" . $jobArchetype-&gt;ID; ?&gt;\" \n + ' ' + \"[data-name='wf_job_steps']\", function() {\n\n $(\"[data-name='wf_job_steps']\").replaceWith(\n $(this).children(\"[data-name='wf_job_steps']\")\n );\n });\n }\n &lt;/script&gt;\n&lt;?php }\n</code></pre>\n\n<p>When the New Job page receives an archetype ID, it loads a custom script that essentially replaces the blank Job Steps section of the New Job form with a <em>copy</em> of the Job Steps section from the Edit Archetype form.</p>\n\n<hr>\n\n<h2>The Script</h2>\n\n<p>When the page is rendered in the client's browser, it will look something like this:</p>\n\n<pre><code>&lt;script&gt;\n $(document).ready(function() {\n my_loadJobArchetype();\n });\n\n function my_loadJobArchetype() {\n $('&lt;div&gt;').load(\"mysite.com/edit-archetype/?archetypeId=123\" \n + ' ' + \"[data-name='my_job_steps']\", function() {\n\n $(\"[data-name='my_job_steps']\").replaceWith(\n $(this).children(\"[data-name='my_job_steps']\")\n );\n });\n }\n&lt;/script&gt;\n</code></pre>\n\n<p>And here's a breakdown of what's happening:</p>\n\n<p><code>$(ducument).ready()</code> calls <code>my_loadJobArchetype()</code> as soon as the page is loaded.</p>\n\n<p>Next, we load a <strong>portion</strong> of the Edit Archetype page into a new <code>&lt;div&gt;</code> element with:</p>\n\n<pre><code>$('&lt;div&gt;').load(\"mysite.com/edit-archetype/?archetypeId=123\" \n + ' ' + \"[data-name='my_job_steps']\" // ...\n);\n</code></pre>\n\n<p>We're actually passing something <em>similar</em> to two arguments here. The <code>url</code> argument of jQuery's <code>load()</code> function can also contain a jQuery selector string (separated by a space) which will load only a fragment of the target page rather than the entire document.</p>\n\n<p>I inspected the source of my Edit Archetype and New Job pages, and found that the Job Step field group was contained in a <code>&lt;div&gt;</code> tag with the attribute: <code>data-name=\"my-job-steps\"</code> (the value of this attribute happens to be the KEY I defined for the custom field group).</p>\n\n<p>Knowing that, I built a jQuery selector based on that attribute: <code>[data-name='my_job_steps']</code> which I passed in with the <code>url</code> argument of the <code>load()</code> call.</p>\n\n<p>Then, in the callback function, I grab the existing Job Steps section of the page, and replace it with the section I loaded from the Edit Template page.</p>\n\n<pre><code>function() {\n $(\"[data-name='my_job_steps']\").replaceWith(\n $(this).children(\"[data-name='my_job_steps']\")\n );\n}\n</code></pre>\n\n<p>The <code>$(this)</code> element in this case is the new <code>&lt;div&gt;</code> element we created to store the response from <code>load()</code>.</p>\n\n<p>The end result is a functional templating feature. I'm not exactly happy with the fact that I'm now relying on JavaScript for this to work, but it's a start. </p>\n\n<p>When I figure out how to achieve this without JS, I'll be sure to share.</p>\n" }, { "answer_id": 214026, "author": "Mike", "author_id": 45704, "author_profile": "https://wordpress.stackexchange.com/users/45704", "pm_score": 1, "selected": true, "text": "<p>I know I posted an answer to this already, but I've found a better solution, so I wanted to take the time to share that.</p>\n\n<p>As it turns out, there is one small hiccup with the JS solution in my previous answer that didn't surface until I had a friend test my in progress application.</p>\n\n<h2>The Problem</h2>\n\n<p>Previously, I defined Job Steps as a <strong>Repeater Field</strong> with two sub-fields: Title and Details. The Details sub-field is a WYSIWYG field to give users some control over formatting.</p>\n\n<p>The problem is, tinyMCE uses JavaScript that wraps plain <code>textarea</code> inputs in the user-friendly WYSIWYG <code>textarea</code> after a page has loaded. This caused problems, because my JS solution:</p>\n\n<pre><code>function my_loadJobArchetype() {\n $('&lt;div&gt;').load(\"mysite.com/edit-archetype/?archetypeId=123\" \n + ' ' + \"[data-name='my_job_steps']\", function() {\n\n $(\"[data-name='my_job_steps']\").replaceWith(\n $(this).children(\"[data-name='my_job_steps']\")\n );\n });\n}\n</code></pre>\n\n<p>Didn't execute scripts during the <code>load()</code> call. When I replaced the blank Job content with the content loaded from the archetype, my users were getting a plain text box rather than a WYSIWYG editor.</p>\n\n<p>So, instead of seeing things like <strong>Quantity</strong>, they saw:</p>\n\n<pre><code>&lt;p&gt;&lt;strong&gt;Quantity&lt;/strong&gt;&lt;/p&gt;\n</code></pre>\n\n<p>Needless to say, that's not what I wanted to happen.</p>\n\n<p>I followed <a href=\"https://wordpress.stackexchange.com/users/84219/jgraup\">jgraup</a>'s suggestion and looked into some of the ACF plugins, but it turns out I can solve it with the filters already provided by the plugin.</p>\n\n<p>The filter we want to use for this is: <code>acf/load_value/key=[field_key]</code>. Basically, this is a dynamic filter that lets you hook into the LOADING process for specific custom fields.</p>\n\n<hr>\n\n<h2>Step 1</h2>\n\n<p><strong>Redefine my custom fields (slightly).</strong></p>\n\n<p>Originally, Jobs and Job Archetypes used the same field group: <code>wf_jobStepFields</code>, but for this process to work correctly, I need to maintain two copies of the fields:</p>\n\n<ul>\n<li>wf_jobStepFields</li>\n<li>wf_archetypeStepFields</li>\n</ul>\n\n<p>Within each of those field groups is a unique repeater field: <code>wf_job_steps</code> and <code>wf_archetype_steps</code>. The sub-field keys remain the same (<code>step_title</code> and <code>step_details</code>)</p>\n\n<h2>Step 2</h2>\n\n<p><strong>Hook into the ACF filter</strong></p>\n\n<pre><code>function my_loadArchetypeValue($value, $post_id, $field) {\n\n}\nadd_filter('acf/load_value/key=wf_job_steps', 'my_loadArchetypeValue', 10, 3);\n</code></pre>\n\n<p><code>\"acf/load_value/key={$field_key}\"</code> is a flexible filter hook that allows us to latch onto the loading process for an individual field. In this case, we're latching on to the <code>wf_job_steps</code> <strong>Repeater Field</strong></p>\n\n<h2>Step 3</h2>\n\n<p><strong>Override values on the New Job Form</strong></p>\n\n<p>I've got a page on the front-end that users can visit to submit new Jobs. By default, this page contains a blank job with a single Job Step defined, but using this hook, we can override that with the selected Archetype template:</p>\n\n<pre><code> function my_loadArchetypeValue($value, $post_id, $field) {\n // FIRST: Check to make sure we are on the NEW JOB page.\n if (is_page('new-job')) {\n\n // Check to see if the \"archetypeId\" query variable is defined.\n if (get_query_var(\"archetypeId\")) {\n // If it is, grab the VALUE of the ARCHETYPE STEPS for the selected Archetype\n return get_field('wf_archetype_steps',get_query_var(\"archetypeId\"));\n }\n }\n}\n</code></pre>\n\n<h2>Step 4</h2>\n\n<p><strong>Override values on the Admin screen</strong></p>\n\n<p>Although I have a front-end form for adding new Jobs, I want to make sure that the backend screen provides the same functionality so that Archetypes can be leveraged from the admin area as well.</p>\n\n<pre><code>// First, check to make sure that the get_current_screen() function is defined.\n// It is not defined on every admin page, but it is defined on the \n// ADD NEW pages, which is where we want to be.\nif (function_exists(\"get_current_screen\")) {\n // Grab the current screen OBJECT and save it\n $screen = get_current_screen();\n\n // This statement checks to make sure that we are on the \n // ADD NEW screen for the JOB post type\n if ($screen-&gt;action == 'add' &amp;&amp; $screen-&gt;post_type == wf-job) {\n $archetypeId = $_GET[\"archetypeId\"];\n /* NOTE: the global WP_Query object has no query vars here,\n / so we need to get a little \"creative to pull the\n / variable from the URL.\n\n Technically, $_GET[\"archetypeId\"] will also work on the\n Add Job form as well, but we have access to the WP_Query\n query vars there, and I think that using the WP core whenever\n possible makes WordPress related functions easier to follow\n */\n\n if ($archetypeId) {\n return get_field('wf_archetype_steps', $archetypeId);\n }\n }\n}\n</code></pre>\n\n<h2>The Final Result</h2>\n\n<p><strong>Put it all together, and the final function looks like this:</strong></p>\n\n<pre><code>function my_loadArchetypeValue($value, $post_id, $field) {\n if (is_page('new-job')) {\n $archetypeId = get_query_var(\"archetypeId\");\n\n if ($archetypeId) {\n return get_field('wf_archetype_steps',$archetypeId);\n }\n } elseif (function_exists(\"get_current_screen\")) {\n $screen = get_current_screen();\n\n if ($screen-&gt;action == 'add' &amp;&amp; $screen-&gt;post_type == wf-job) {\n $archetypeId = $_GET[\"archetypeId\"];\n if ($archetypeId) {\n return get_field('wf_archetype_steps', $archetypeId);\n }\n }\n }\n\n return $value;\n}\nadd_filter('acf/load_value/key=wf_job_steps', 'my_loadArchetypeValue', 10, 3);\n</code></pre>\n\n<hr>\n\n<p><strong>NOTE:</strong> As a rule, I'm not a huge fan of defining a second field group. In this case, it's pretty much a textbook definition of copy/pasting code, since the field groups are functionally identical aside from a couple keys.</p>\n\n<p>But, there is a very good reason for doing it in this case.</p>\n\n<p>The filter we hook into latches on to the LOAD event for a specific field (defined by the field's KEY). In this case, we're latching onto wf_job_steps.</p>\n\n<p>If I had continued to use a single field group, this filter hook would throw the process into an <strong>infinite loop</strong>, because each time my filter function hit the <code>get_field()</code> call, the filter would be triggered again.</p>\n\n<p>Defining a second field group with a unique KEY for the repeater field prevents the infinite loop, but since the sub-fields still have the same KEY values, it allows them to transfer seamlessly over to new JOBS.</p>\n" } ]
2015/11/30
[ "https://wordpress.stackexchange.com/questions/210358", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/45704/" ]
I've tried searching for this using various terminology, but I always end up at questions pertaining to the php template files. That's not what I'm looking for, so I'm asking a new question. I apologize if this is a duplicate. Basically, I'm looking for a way to create template posts. I'm using ACF Pro on a custom "Job" post type, and I've got a Repeater Field set up for "Job Steps." To give an example, a "Make a Pizza" Job would have the following steps: 1. Ordered 2. Prep 3. Bake 4. Box 5. Deliver The way things are currently set up, users will need to manually define these steps each and every time, so what I would like to do is create a "Pizza Template" post that users can use to define the steps once, and then adding a new "Make a Pizza" job will automatically define the steps but allows users to fill in the specific details like toppings, crust, delivery address, etc. One of the things I thought about doing was adding a new "Job Template" post type that uses the same custom field definition as the "Job" type. Then, when users create a new Job, they would be prompted to pick a "Job Template". If they chose "Pizza Template", it would copy the Repeater Field values from the Job Template post and set them in the editor for the new Job. I suspect that would be a very convoluted process, so I'm hoping that someone knows a more efficient way somewhere in the core. Edit ---- Based on comments, I see that one aspect of this question wasn't as clear as I thought, so to give more info: I'm trying to create a generic Tracker plugin that can be customized by users at runtime to fit a variety of workflows. The Repeater Field gives me that flexibility, but efficient use depends on templates. Users define their workflow once as a template and then use that template when creating new Jobs. This approach also allows users to define multiple workflows without the need for multiple field groups or multiple post types. I'm working on a few possible solutions myself (and will post answers when I get there), but I'm really hoping there's something in the core that I can leverage to make this easier.
I know I posted an answer to this already, but I've found a better solution, so I wanted to take the time to share that. As it turns out, there is one small hiccup with the JS solution in my previous answer that didn't surface until I had a friend test my in progress application. The Problem ----------- Previously, I defined Job Steps as a **Repeater Field** with two sub-fields: Title and Details. The Details sub-field is a WYSIWYG field to give users some control over formatting. The problem is, tinyMCE uses JavaScript that wraps plain `textarea` inputs in the user-friendly WYSIWYG `textarea` after a page has loaded. This caused problems, because my JS solution: ``` function my_loadJobArchetype() { $('<div>').load("mysite.com/edit-archetype/?archetypeId=123" + ' ' + "[data-name='my_job_steps']", function() { $("[data-name='my_job_steps']").replaceWith( $(this).children("[data-name='my_job_steps']") ); }); } ``` Didn't execute scripts during the `load()` call. When I replaced the blank Job content with the content loaded from the archetype, my users were getting a plain text box rather than a WYSIWYG editor. So, instead of seeing things like **Quantity**, they saw: ``` <p><strong>Quantity</strong></p> ``` Needless to say, that's not what I wanted to happen. I followed [jgraup](https://wordpress.stackexchange.com/users/84219/jgraup)'s suggestion and looked into some of the ACF plugins, but it turns out I can solve it with the filters already provided by the plugin. The filter we want to use for this is: `acf/load_value/key=[field_key]`. Basically, this is a dynamic filter that lets you hook into the LOADING process for specific custom fields. --- Step 1 ------ **Redefine my custom fields (slightly).** Originally, Jobs and Job Archetypes used the same field group: `wf_jobStepFields`, but for this process to work correctly, I need to maintain two copies of the fields: * wf\_jobStepFields * wf\_archetypeStepFields Within each of those field groups is a unique repeater field: `wf_job_steps` and `wf_archetype_steps`. The sub-field keys remain the same (`step_title` and `step_details`) Step 2 ------ **Hook into the ACF filter** ``` function my_loadArchetypeValue($value, $post_id, $field) { } add_filter('acf/load_value/key=wf_job_steps', 'my_loadArchetypeValue', 10, 3); ``` `"acf/load_value/key={$field_key}"` is a flexible filter hook that allows us to latch onto the loading process for an individual field. In this case, we're latching on to the `wf_job_steps` **Repeater Field** Step 3 ------ **Override values on the New Job Form** I've got a page on the front-end that users can visit to submit new Jobs. By default, this page contains a blank job with a single Job Step defined, but using this hook, we can override that with the selected Archetype template: ``` function my_loadArchetypeValue($value, $post_id, $field) { // FIRST: Check to make sure we are on the NEW JOB page. if (is_page('new-job')) { // Check to see if the "archetypeId" query variable is defined. if (get_query_var("archetypeId")) { // If it is, grab the VALUE of the ARCHETYPE STEPS for the selected Archetype return get_field('wf_archetype_steps',get_query_var("archetypeId")); } } } ``` Step 4 ------ **Override values on the Admin screen** Although I have a front-end form for adding new Jobs, I want to make sure that the backend screen provides the same functionality so that Archetypes can be leveraged from the admin area as well. ``` // First, check to make sure that the get_current_screen() function is defined. // It is not defined on every admin page, but it is defined on the // ADD NEW pages, which is where we want to be. if (function_exists("get_current_screen")) { // Grab the current screen OBJECT and save it $screen = get_current_screen(); // This statement checks to make sure that we are on the // ADD NEW screen for the JOB post type if ($screen->action == 'add' && $screen->post_type == wf-job) { $archetypeId = $_GET["archetypeId"]; /* NOTE: the global WP_Query object has no query vars here, / so we need to get a little "creative to pull the / variable from the URL. Technically, $_GET["archetypeId"] will also work on the Add Job form as well, but we have access to the WP_Query query vars there, and I think that using the WP core whenever possible makes WordPress related functions easier to follow */ if ($archetypeId) { return get_field('wf_archetype_steps', $archetypeId); } } } ``` The Final Result ---------------- **Put it all together, and the final function looks like this:** ``` function my_loadArchetypeValue($value, $post_id, $field) { if (is_page('new-job')) { $archetypeId = get_query_var("archetypeId"); if ($archetypeId) { return get_field('wf_archetype_steps',$archetypeId); } } elseif (function_exists("get_current_screen")) { $screen = get_current_screen(); if ($screen->action == 'add' && $screen->post_type == wf-job) { $archetypeId = $_GET["archetypeId"]; if ($archetypeId) { return get_field('wf_archetype_steps', $archetypeId); } } } return $value; } add_filter('acf/load_value/key=wf_job_steps', 'my_loadArchetypeValue', 10, 3); ``` --- **NOTE:** As a rule, I'm not a huge fan of defining a second field group. In this case, it's pretty much a textbook definition of copy/pasting code, since the field groups are functionally identical aside from a couple keys. But, there is a very good reason for doing it in this case. The filter we hook into latches on to the LOAD event for a specific field (defined by the field's KEY). In this case, we're latching onto wf\_job\_steps. If I had continued to use a single field group, this filter hook would throw the process into an **infinite loop**, because each time my filter function hit the `get_field()` call, the filter would be triggered again. Defining a second field group with a unique KEY for the repeater field prevents the infinite loop, but since the sub-fields still have the same KEY values, it allows them to transfer seamlessly over to new JOBS.
210,359
<p>I would like a WordPress site to redirect all URLs to the <code>www</code> subdomain. Using the <code>.htaccess</code> configuration below, the homepage is properly redirected (i.e. visiting <code>example.com/</code> redirects to <code>www.example.com/</code>) but internal pages aren't getting redirected (both <code>www.example.com/page</code> and <code>example.com/page</code> resolve and display the same content).</p> <pre><code># Redirect non-www traffic to www RewriteEngine On RewriteCond %{HTTP_HOST} ^example.com [NC] RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301] </code></pre> <p>Why aren't all URLs being redirected to the <code>www</code> subdomain?</p>
[ { "answer_id": 210363, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p>It's possible you may have to define your own <a href=\"http://www.advancedcustomfields.com/resources/creating-a-new-field-type/\" rel=\"nofollow\">ACF Custom Field Type</a> which holds your templates. And after a template is selected then you would programmatically copy the fields to a <a href=\"http://www.advancedcustomfields.com/resources/repeater/\" rel=\"nofollow\">repeater</a>. <a href=\"https://github.com/navidkashani/awesome-acf\" rel=\"nofollow\">Awesome ACF</a> has quite a few examples, WordPress has quite a few <a href=\"https://wordpress.org/plugins/search.php?q=Advanced+Custom+Fields\" rel=\"nofollow\">plugins</a> and there is a <a href=\"http://support.advancedcustomfields.com/forums/forum/add-ons/user-submitted/\" rel=\"nofollow\">User Submitted Add-Ons</a> support forum.</p>\n" }, { "answer_id": 211299, "author": "Mike", "author_id": 45704, "author_profile": "https://wordpress.stackexchange.com/users/45704", "pm_score": 0, "selected": false, "text": "<p>I was able to pull this off with a second post type and a little bit of JavaScript.</p>\n\n<h2>Step 1: Assign the ACF Field Group</h2>\n\n<p>I already had the <strong>Job Steps</strong> field group defined, so I modified the setup a bit and assigned it to both Jobs and Job Archetypes:</p>\n\n<pre><code>// [...] This is a snip from the full custom field setup\n'location' =&gt; array (\n array (\n array (\n 'param' =&gt; 'post_type',\n 'operator' =&gt; '==',\n 'value' =&gt; 'my-job',\n ),\n ),\n\n array (\n array (\n 'param' =&gt; 'post_type',\n 'operator' =&gt; '==',\n 'value' =&gt; 'my-job-archetype',\n ),\n ),\n),\n</code></pre>\n\n<p>Now I can access Job Steps in the same way for poth content types.</p>\n\n<hr>\n\n<h2>Step 2: Register a Custom Query Var</h2>\n\n<p>The next thing I did was add a custom query variable for the Archetype post ID:</p>\n\n<pre><code>function my_registerArchetypeQueryVar($vars) {\n $vars[] = 'archetypeId;\n return $vars;\n}\nadd_filter('query_vars', 'my_registerArchetypeQueryVar');\n</code></pre>\n\n<hr>\n\n<h2>Step 3: Front End Form - Edit Archetype</h2>\n\n<p>Next, I created an Edit Archetype page with the following:</p>\n\n<pre><code>if(get_query_var('archetypeId')) {\n $id = get_query_var('archetypeId');\n\n $jobArchetype = get_post($id);\n\n if ($jobArchetype) {\n acf_form(array(\n \"id\" =&gt; \"editJobForm\",\n \"post_id\" =&gt; $id,\n \"post_title\" =&gt; true,\n 'field_groups' =&gt; array('my_jobStepFields'),\n \"return\" =&gt; \"%post_url%\",\n \"submit_value\" =&gt; __(\"Update Archetype\", 'acf'),\n ));\n } else {\n acf_form(array(\n \"id\" =&gt; \"addJobForm\",\n \"post_id\" =&gt; 'new_post',\n 'new_post' =&gt; array(\n 'post_type' =&gt; 'my-job-archetype',\n 'post_status' =&gt; 'publish'\n ),\n \"post_title\" =&gt; true,\n 'field_groups' =&gt; array('my_jobStepFields'),\n \"return\" =&gt; \"%post_url%\",\n \"submit_value\" =&gt; __(\"Add Archetype\", 'acf'),\n ));\n }\n}\n</code></pre>\n\n<p>On the this page, I grab the <code>archetypeId</code> query var and use that to pull up an ACF form for the specified post. (And if no <code>archetypeId</code> is provided, I render a New Archetype form instead.</p>\n\n<hr>\n\n<h2>Step 4: Front End Form - New Job</h2>\n\n<p>Next, I created a New Job page with the following:</p>\n\n<pre><code>$id = get_query_var('archetypeId');\n$jobArchetype = get_post($id);\n\n\nif ($jobArchetype) { ?&gt;\n &lt;script&gt;\n $(document).ready(function() {\n my_loadJobArchetype();\n });\n\n function my_loadJobArchetype() {\n $('&lt;div&gt;').load(\"&lt;?php echo get_page_by_path('edit-archetype') \n . \"?archetypeId=\" . $jobArchetype-&gt;ID; ?&gt;\" \n + ' ' + \"[data-name='wf_job_steps']\", function() {\n\n $(\"[data-name='wf_job_steps']\").replaceWith(\n $(this).children(\"[data-name='wf_job_steps']\")\n );\n });\n }\n &lt;/script&gt;\n&lt;?php }\n</code></pre>\n\n<p>When the New Job page receives an archetype ID, it loads a custom script that essentially replaces the blank Job Steps section of the New Job form with a <em>copy</em> of the Job Steps section from the Edit Archetype form.</p>\n\n<hr>\n\n<h2>The Script</h2>\n\n<p>When the page is rendered in the client's browser, it will look something like this:</p>\n\n<pre><code>&lt;script&gt;\n $(document).ready(function() {\n my_loadJobArchetype();\n });\n\n function my_loadJobArchetype() {\n $('&lt;div&gt;').load(\"mysite.com/edit-archetype/?archetypeId=123\" \n + ' ' + \"[data-name='my_job_steps']\", function() {\n\n $(\"[data-name='my_job_steps']\").replaceWith(\n $(this).children(\"[data-name='my_job_steps']\")\n );\n });\n }\n&lt;/script&gt;\n</code></pre>\n\n<p>And here's a breakdown of what's happening:</p>\n\n<p><code>$(ducument).ready()</code> calls <code>my_loadJobArchetype()</code> as soon as the page is loaded.</p>\n\n<p>Next, we load a <strong>portion</strong> of the Edit Archetype page into a new <code>&lt;div&gt;</code> element with:</p>\n\n<pre><code>$('&lt;div&gt;').load(\"mysite.com/edit-archetype/?archetypeId=123\" \n + ' ' + \"[data-name='my_job_steps']\" // ...\n);\n</code></pre>\n\n<p>We're actually passing something <em>similar</em> to two arguments here. The <code>url</code> argument of jQuery's <code>load()</code> function can also contain a jQuery selector string (separated by a space) which will load only a fragment of the target page rather than the entire document.</p>\n\n<p>I inspected the source of my Edit Archetype and New Job pages, and found that the Job Step field group was contained in a <code>&lt;div&gt;</code> tag with the attribute: <code>data-name=\"my-job-steps\"</code> (the value of this attribute happens to be the KEY I defined for the custom field group).</p>\n\n<p>Knowing that, I built a jQuery selector based on that attribute: <code>[data-name='my_job_steps']</code> which I passed in with the <code>url</code> argument of the <code>load()</code> call.</p>\n\n<p>Then, in the callback function, I grab the existing Job Steps section of the page, and replace it with the section I loaded from the Edit Template page.</p>\n\n<pre><code>function() {\n $(\"[data-name='my_job_steps']\").replaceWith(\n $(this).children(\"[data-name='my_job_steps']\")\n );\n}\n</code></pre>\n\n<p>The <code>$(this)</code> element in this case is the new <code>&lt;div&gt;</code> element we created to store the response from <code>load()</code>.</p>\n\n<p>The end result is a functional templating feature. I'm not exactly happy with the fact that I'm now relying on JavaScript for this to work, but it's a start. </p>\n\n<p>When I figure out how to achieve this without JS, I'll be sure to share.</p>\n" }, { "answer_id": 214026, "author": "Mike", "author_id": 45704, "author_profile": "https://wordpress.stackexchange.com/users/45704", "pm_score": 1, "selected": true, "text": "<p>I know I posted an answer to this already, but I've found a better solution, so I wanted to take the time to share that.</p>\n\n<p>As it turns out, there is one small hiccup with the JS solution in my previous answer that didn't surface until I had a friend test my in progress application.</p>\n\n<h2>The Problem</h2>\n\n<p>Previously, I defined Job Steps as a <strong>Repeater Field</strong> with two sub-fields: Title and Details. The Details sub-field is a WYSIWYG field to give users some control over formatting.</p>\n\n<p>The problem is, tinyMCE uses JavaScript that wraps plain <code>textarea</code> inputs in the user-friendly WYSIWYG <code>textarea</code> after a page has loaded. This caused problems, because my JS solution:</p>\n\n<pre><code>function my_loadJobArchetype() {\n $('&lt;div&gt;').load(\"mysite.com/edit-archetype/?archetypeId=123\" \n + ' ' + \"[data-name='my_job_steps']\", function() {\n\n $(\"[data-name='my_job_steps']\").replaceWith(\n $(this).children(\"[data-name='my_job_steps']\")\n );\n });\n}\n</code></pre>\n\n<p>Didn't execute scripts during the <code>load()</code> call. When I replaced the blank Job content with the content loaded from the archetype, my users were getting a plain text box rather than a WYSIWYG editor.</p>\n\n<p>So, instead of seeing things like <strong>Quantity</strong>, they saw:</p>\n\n<pre><code>&lt;p&gt;&lt;strong&gt;Quantity&lt;/strong&gt;&lt;/p&gt;\n</code></pre>\n\n<p>Needless to say, that's not what I wanted to happen.</p>\n\n<p>I followed <a href=\"https://wordpress.stackexchange.com/users/84219/jgraup\">jgraup</a>'s suggestion and looked into some of the ACF plugins, but it turns out I can solve it with the filters already provided by the plugin.</p>\n\n<p>The filter we want to use for this is: <code>acf/load_value/key=[field_key]</code>. Basically, this is a dynamic filter that lets you hook into the LOADING process for specific custom fields.</p>\n\n<hr>\n\n<h2>Step 1</h2>\n\n<p><strong>Redefine my custom fields (slightly).</strong></p>\n\n<p>Originally, Jobs and Job Archetypes used the same field group: <code>wf_jobStepFields</code>, but for this process to work correctly, I need to maintain two copies of the fields:</p>\n\n<ul>\n<li>wf_jobStepFields</li>\n<li>wf_archetypeStepFields</li>\n</ul>\n\n<p>Within each of those field groups is a unique repeater field: <code>wf_job_steps</code> and <code>wf_archetype_steps</code>. The sub-field keys remain the same (<code>step_title</code> and <code>step_details</code>)</p>\n\n<h2>Step 2</h2>\n\n<p><strong>Hook into the ACF filter</strong></p>\n\n<pre><code>function my_loadArchetypeValue($value, $post_id, $field) {\n\n}\nadd_filter('acf/load_value/key=wf_job_steps', 'my_loadArchetypeValue', 10, 3);\n</code></pre>\n\n<p><code>\"acf/load_value/key={$field_key}\"</code> is a flexible filter hook that allows us to latch onto the loading process for an individual field. In this case, we're latching on to the <code>wf_job_steps</code> <strong>Repeater Field</strong></p>\n\n<h2>Step 3</h2>\n\n<p><strong>Override values on the New Job Form</strong></p>\n\n<p>I've got a page on the front-end that users can visit to submit new Jobs. By default, this page contains a blank job with a single Job Step defined, but using this hook, we can override that with the selected Archetype template:</p>\n\n<pre><code> function my_loadArchetypeValue($value, $post_id, $field) {\n // FIRST: Check to make sure we are on the NEW JOB page.\n if (is_page('new-job')) {\n\n // Check to see if the \"archetypeId\" query variable is defined.\n if (get_query_var(\"archetypeId\")) {\n // If it is, grab the VALUE of the ARCHETYPE STEPS for the selected Archetype\n return get_field('wf_archetype_steps',get_query_var(\"archetypeId\"));\n }\n }\n}\n</code></pre>\n\n<h2>Step 4</h2>\n\n<p><strong>Override values on the Admin screen</strong></p>\n\n<p>Although I have a front-end form for adding new Jobs, I want to make sure that the backend screen provides the same functionality so that Archetypes can be leveraged from the admin area as well.</p>\n\n<pre><code>// First, check to make sure that the get_current_screen() function is defined.\n// It is not defined on every admin page, but it is defined on the \n// ADD NEW pages, which is where we want to be.\nif (function_exists(\"get_current_screen\")) {\n // Grab the current screen OBJECT and save it\n $screen = get_current_screen();\n\n // This statement checks to make sure that we are on the \n // ADD NEW screen for the JOB post type\n if ($screen-&gt;action == 'add' &amp;&amp; $screen-&gt;post_type == wf-job) {\n $archetypeId = $_GET[\"archetypeId\"];\n /* NOTE: the global WP_Query object has no query vars here,\n / so we need to get a little \"creative to pull the\n / variable from the URL.\n\n Technically, $_GET[\"archetypeId\"] will also work on the\n Add Job form as well, but we have access to the WP_Query\n query vars there, and I think that using the WP core whenever\n possible makes WordPress related functions easier to follow\n */\n\n if ($archetypeId) {\n return get_field('wf_archetype_steps', $archetypeId);\n }\n }\n}\n</code></pre>\n\n<h2>The Final Result</h2>\n\n<p><strong>Put it all together, and the final function looks like this:</strong></p>\n\n<pre><code>function my_loadArchetypeValue($value, $post_id, $field) {\n if (is_page('new-job')) {\n $archetypeId = get_query_var(\"archetypeId\");\n\n if ($archetypeId) {\n return get_field('wf_archetype_steps',$archetypeId);\n }\n } elseif (function_exists(\"get_current_screen\")) {\n $screen = get_current_screen();\n\n if ($screen-&gt;action == 'add' &amp;&amp; $screen-&gt;post_type == wf-job) {\n $archetypeId = $_GET[\"archetypeId\"];\n if ($archetypeId) {\n return get_field('wf_archetype_steps', $archetypeId);\n }\n }\n }\n\n return $value;\n}\nadd_filter('acf/load_value/key=wf_job_steps', 'my_loadArchetypeValue', 10, 3);\n</code></pre>\n\n<hr>\n\n<p><strong>NOTE:</strong> As a rule, I'm not a huge fan of defining a second field group. In this case, it's pretty much a textbook definition of copy/pasting code, since the field groups are functionally identical aside from a couple keys.</p>\n\n<p>But, there is a very good reason for doing it in this case.</p>\n\n<p>The filter we hook into latches on to the LOAD event for a specific field (defined by the field's KEY). In this case, we're latching onto wf_job_steps.</p>\n\n<p>If I had continued to use a single field group, this filter hook would throw the process into an <strong>infinite loop</strong>, because each time my filter function hit the <code>get_field()</code> call, the filter would be triggered again.</p>\n\n<p>Defining a second field group with a unique KEY for the repeater field prevents the infinite loop, but since the sub-fields still have the same KEY values, it allows them to transfer seamlessly over to new JOBS.</p>\n" } ]
2015/11/30
[ "https://wordpress.stackexchange.com/questions/210359", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76695/" ]
I would like a WordPress site to redirect all URLs to the `www` subdomain. Using the `.htaccess` configuration below, the homepage is properly redirected (i.e. visiting `example.com/` redirects to `www.example.com/`) but internal pages aren't getting redirected (both `www.example.com/page` and `example.com/page` resolve and display the same content). ``` # Redirect non-www traffic to www RewriteEngine On RewriteCond %{HTTP_HOST} ^example.com [NC] RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301] ``` Why aren't all URLs being redirected to the `www` subdomain?
I know I posted an answer to this already, but I've found a better solution, so I wanted to take the time to share that. As it turns out, there is one small hiccup with the JS solution in my previous answer that didn't surface until I had a friend test my in progress application. The Problem ----------- Previously, I defined Job Steps as a **Repeater Field** with two sub-fields: Title and Details. The Details sub-field is a WYSIWYG field to give users some control over formatting. The problem is, tinyMCE uses JavaScript that wraps plain `textarea` inputs in the user-friendly WYSIWYG `textarea` after a page has loaded. This caused problems, because my JS solution: ``` function my_loadJobArchetype() { $('<div>').load("mysite.com/edit-archetype/?archetypeId=123" + ' ' + "[data-name='my_job_steps']", function() { $("[data-name='my_job_steps']").replaceWith( $(this).children("[data-name='my_job_steps']") ); }); } ``` Didn't execute scripts during the `load()` call. When I replaced the blank Job content with the content loaded from the archetype, my users were getting a plain text box rather than a WYSIWYG editor. So, instead of seeing things like **Quantity**, they saw: ``` <p><strong>Quantity</strong></p> ``` Needless to say, that's not what I wanted to happen. I followed [jgraup](https://wordpress.stackexchange.com/users/84219/jgraup)'s suggestion and looked into some of the ACF plugins, but it turns out I can solve it with the filters already provided by the plugin. The filter we want to use for this is: `acf/load_value/key=[field_key]`. Basically, this is a dynamic filter that lets you hook into the LOADING process for specific custom fields. --- Step 1 ------ **Redefine my custom fields (slightly).** Originally, Jobs and Job Archetypes used the same field group: `wf_jobStepFields`, but for this process to work correctly, I need to maintain two copies of the fields: * wf\_jobStepFields * wf\_archetypeStepFields Within each of those field groups is a unique repeater field: `wf_job_steps` and `wf_archetype_steps`. The sub-field keys remain the same (`step_title` and `step_details`) Step 2 ------ **Hook into the ACF filter** ``` function my_loadArchetypeValue($value, $post_id, $field) { } add_filter('acf/load_value/key=wf_job_steps', 'my_loadArchetypeValue', 10, 3); ``` `"acf/load_value/key={$field_key}"` is a flexible filter hook that allows us to latch onto the loading process for an individual field. In this case, we're latching on to the `wf_job_steps` **Repeater Field** Step 3 ------ **Override values on the New Job Form** I've got a page on the front-end that users can visit to submit new Jobs. By default, this page contains a blank job with a single Job Step defined, but using this hook, we can override that with the selected Archetype template: ``` function my_loadArchetypeValue($value, $post_id, $field) { // FIRST: Check to make sure we are on the NEW JOB page. if (is_page('new-job')) { // Check to see if the "archetypeId" query variable is defined. if (get_query_var("archetypeId")) { // If it is, grab the VALUE of the ARCHETYPE STEPS for the selected Archetype return get_field('wf_archetype_steps',get_query_var("archetypeId")); } } } ``` Step 4 ------ **Override values on the Admin screen** Although I have a front-end form for adding new Jobs, I want to make sure that the backend screen provides the same functionality so that Archetypes can be leveraged from the admin area as well. ``` // First, check to make sure that the get_current_screen() function is defined. // It is not defined on every admin page, but it is defined on the // ADD NEW pages, which is where we want to be. if (function_exists("get_current_screen")) { // Grab the current screen OBJECT and save it $screen = get_current_screen(); // This statement checks to make sure that we are on the // ADD NEW screen for the JOB post type if ($screen->action == 'add' && $screen->post_type == wf-job) { $archetypeId = $_GET["archetypeId"]; /* NOTE: the global WP_Query object has no query vars here, / so we need to get a little "creative to pull the / variable from the URL. Technically, $_GET["archetypeId"] will also work on the Add Job form as well, but we have access to the WP_Query query vars there, and I think that using the WP core whenever possible makes WordPress related functions easier to follow */ if ($archetypeId) { return get_field('wf_archetype_steps', $archetypeId); } } } ``` The Final Result ---------------- **Put it all together, and the final function looks like this:** ``` function my_loadArchetypeValue($value, $post_id, $field) { if (is_page('new-job')) { $archetypeId = get_query_var("archetypeId"); if ($archetypeId) { return get_field('wf_archetype_steps',$archetypeId); } } elseif (function_exists("get_current_screen")) { $screen = get_current_screen(); if ($screen->action == 'add' && $screen->post_type == wf-job) { $archetypeId = $_GET["archetypeId"]; if ($archetypeId) { return get_field('wf_archetype_steps', $archetypeId); } } } return $value; } add_filter('acf/load_value/key=wf_job_steps', 'my_loadArchetypeValue', 10, 3); ``` --- **NOTE:** As a rule, I'm not a huge fan of defining a second field group. In this case, it's pretty much a textbook definition of copy/pasting code, since the field groups are functionally identical aside from a couple keys. But, there is a very good reason for doing it in this case. The filter we hook into latches on to the LOAD event for a specific field (defined by the field's KEY). In this case, we're latching onto wf\_job\_steps. If I had continued to use a single field group, this filter hook would throw the process into an **infinite loop**, because each time my filter function hit the `get_field()` call, the filter would be triggered again. Defining a second field group with a unique KEY for the repeater field prevents the infinite loop, but since the sub-fields still have the same KEY values, it allows them to transfer seamlessly over to new JOBS.
210,374
<p>I am working on an area of my site for members. However, I need a link on my menu that when clicked it will take people to my login form then back to the page they were previously on. I need the same with log out.</p> <p>Example: Bob logs in on page A. Bob has a successful login. Bob is returned to page A.</p> <p>Bob clicks the logout link on page A. Bob is returned to page A after being logged out.</p> <p>EDIT: The other question did not seem to have anyway to add a login logout link to the navigation menu. This is what I need acomplished. Thanks for your help.</p>
[ { "answer_id": 210379, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": 1, "selected": false, "text": "<p>Use <code>wp_login_url()</code> function with <code>get_permalink()</code> as a parameter, if a user is not logged in. Something like this:</p>\n\n<pre><code>&lt;a href=\"&lt;?php echo wp_login_url( get_permalink() ); ?&gt;\" title=\"Login\"&gt;Login&lt;/a&gt;\n</code></pre>\n\n<p>And <code>wp_logout_url</code> function with <code>get_permalink()</code> as a parameter, if a user is logged in.</p>\n\n<pre><code>&lt;a href=\"&lt;?php echo wp_logout_url( get_permalink() ); ?&gt;\"&gt;Logout&lt;/a&gt;\n</code></pre>\n\n<p><strong>EDIT:</strong> instead of using 2 different functions, you may use</p>\n\n<pre><code>&lt;?php wp_loginout(get_permalink()); ?&gt;\n</code></pre>\n\n<p>that displays a login link, or if a user is logged in, displays a logout link</p>\n" }, { "answer_id": 210483, "author": "Alex Stine", "author_id": 82369, "author_profile": "https://wordpress.stackexchange.com/users/82369", "pm_score": 0, "selected": false, "text": "<p>This is the code that fixed my problem:</p>\n\n<pre><code>add_filter( 'wp_nav_menu_items', 'add_login_logout_link', 10, 2 ); \n\nfunction add_login_logout_link( $items, $args ) {\n $pageURL = 'http://';\n $pageURL .= $_SERVER['HTTP_HOST'];\n $pageURL .= $_SERVER['REQUEST_URI'];\n\n ob_start();\n wp_loginout( $pageURL );\n $loginoutlink = ob_get_contents();\n ob_end_clean();\n $items .= '&lt;li&gt;'. $loginoutlink .'&lt;/li&gt;';\n return $items;\n}\n</code></pre>\n" } ]
2015/12/01
[ "https://wordpress.stackexchange.com/questions/210374", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82369/" ]
I am working on an area of my site for members. However, I need a link on my menu that when clicked it will take people to my login form then back to the page they were previously on. I need the same with log out. Example: Bob logs in on page A. Bob has a successful login. Bob is returned to page A. Bob clicks the logout link on page A. Bob is returned to page A after being logged out. EDIT: The other question did not seem to have anyway to add a login logout link to the navigation menu. This is what I need acomplished. Thanks for your help.
Use `wp_login_url()` function with `get_permalink()` as a parameter, if a user is not logged in. Something like this: ``` <a href="<?php echo wp_login_url( get_permalink() ); ?>" title="Login">Login</a> ``` And `wp_logout_url` function with `get_permalink()` as a parameter, if a user is logged in. ``` <a href="<?php echo wp_logout_url( get_permalink() ); ?>">Logout</a> ``` **EDIT:** instead of using 2 different functions, you may use ``` <?php wp_loginout(get_permalink()); ?> ``` that displays a login link, or if a user is logged in, displays a logout link
210,392
<p>I'm building a new site for client based on Wordpress.They already have a non-Wordpress site that logged in visitors can access (on a different domain). I've searched a solution for this all over for the last month or so but I cant seem to find a solution.</p> <p>What I need is to add a pop up login form to a menu item on the Wordpress site that will redirect successful login to the non-Wordpress site.</p> <p>The only thing I've been able to find is custom Worpress logins, but that's not what I need. </p> <p>I've found different forms that you I can add to the login.php file on Wordpress, but again, this works into providing login to the Wordpress site (which I dont want) and not to the non-Wordpress one.</p> <p>Does anyone know how I can achieve this and maybe provide instructions and the code? I'm not really a coder besides some basic HTML and CSS so I feel like I've been going in circles without getting any closer to a solution.</p> <p>So basically the flow that I need would be like this:</p> <ol> <li>User clicks on Login menu item on Wordpress site </li> <li>Loging form pops up ion lightbox/modal</li> <li>User enters Username and Password and clicks Submit</li> <li>After clicking Submit, if login is successful, they are redirected to the non-Wordpress site.</li> </ol> <p>If anyone can help with this I would be forever gratefull as I just cant seem to find a solution for this anywhere.</p> <p>Thanks a lot ion advance</p>
[ { "answer_id": 210379, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": 1, "selected": false, "text": "<p>Use <code>wp_login_url()</code> function with <code>get_permalink()</code> as a parameter, if a user is not logged in. Something like this:</p>\n\n<pre><code>&lt;a href=\"&lt;?php echo wp_login_url( get_permalink() ); ?&gt;\" title=\"Login\"&gt;Login&lt;/a&gt;\n</code></pre>\n\n<p>And <code>wp_logout_url</code> function with <code>get_permalink()</code> as a parameter, if a user is logged in.</p>\n\n<pre><code>&lt;a href=\"&lt;?php echo wp_logout_url( get_permalink() ); ?&gt;\"&gt;Logout&lt;/a&gt;\n</code></pre>\n\n<p><strong>EDIT:</strong> instead of using 2 different functions, you may use</p>\n\n<pre><code>&lt;?php wp_loginout(get_permalink()); ?&gt;\n</code></pre>\n\n<p>that displays a login link, or if a user is logged in, displays a logout link</p>\n" }, { "answer_id": 210483, "author": "Alex Stine", "author_id": 82369, "author_profile": "https://wordpress.stackexchange.com/users/82369", "pm_score": 0, "selected": false, "text": "<p>This is the code that fixed my problem:</p>\n\n<pre><code>add_filter( 'wp_nav_menu_items', 'add_login_logout_link', 10, 2 ); \n\nfunction add_login_logout_link( $items, $args ) {\n $pageURL = 'http://';\n $pageURL .= $_SERVER['HTTP_HOST'];\n $pageURL .= $_SERVER['REQUEST_URI'];\n\n ob_start();\n wp_loginout( $pageURL );\n $loginoutlink = ob_get_contents();\n ob_end_clean();\n $items .= '&lt;li&gt;'. $loginoutlink .'&lt;/li&gt;';\n return $items;\n}\n</code></pre>\n" } ]
2015/12/01
[ "https://wordpress.stackexchange.com/questions/210392", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84539/" ]
I'm building a new site for client based on Wordpress.They already have a non-Wordpress site that logged in visitors can access (on a different domain). I've searched a solution for this all over for the last month or so but I cant seem to find a solution. What I need is to add a pop up login form to a menu item on the Wordpress site that will redirect successful login to the non-Wordpress site. The only thing I've been able to find is custom Worpress logins, but that's not what I need. I've found different forms that you I can add to the login.php file on Wordpress, but again, this works into providing login to the Wordpress site (which I dont want) and not to the non-Wordpress one. Does anyone know how I can achieve this and maybe provide instructions and the code? I'm not really a coder besides some basic HTML and CSS so I feel like I've been going in circles without getting any closer to a solution. So basically the flow that I need would be like this: 1. User clicks on Login menu item on Wordpress site 2. Loging form pops up ion lightbox/modal 3. User enters Username and Password and clicks Submit 4. After clicking Submit, if login is successful, they are redirected to the non-Wordpress site. If anyone can help with this I would be forever gratefull as I just cant seem to find a solution for this anywhere. Thanks a lot ion advance
Use `wp_login_url()` function with `get_permalink()` as a parameter, if a user is not logged in. Something like this: ``` <a href="<?php echo wp_login_url( get_permalink() ); ?>" title="Login">Login</a> ``` And `wp_logout_url` function with `get_permalink()` as a parameter, if a user is logged in. ``` <a href="<?php echo wp_logout_url( get_permalink() ); ?>">Logout</a> ``` **EDIT:** instead of using 2 different functions, you may use ``` <?php wp_loginout(get_permalink()); ?> ``` that displays a login link, or if a user is logged in, displays a logout link
210,394
<pre><code>&lt;?php /* Template Name : Home */ ?&gt; get_header(); ?&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>When I type anything on content editor of the page it doesn't show any thing. </p> <p>How do I make it working?</p>
[ { "answer_id": 210379, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": 1, "selected": false, "text": "<p>Use <code>wp_login_url()</code> function with <code>get_permalink()</code> as a parameter, if a user is not logged in. Something like this:</p>\n\n<pre><code>&lt;a href=\"&lt;?php echo wp_login_url( get_permalink() ); ?&gt;\" title=\"Login\"&gt;Login&lt;/a&gt;\n</code></pre>\n\n<p>And <code>wp_logout_url</code> function with <code>get_permalink()</code> as a parameter, if a user is logged in.</p>\n\n<pre><code>&lt;a href=\"&lt;?php echo wp_logout_url( get_permalink() ); ?&gt;\"&gt;Logout&lt;/a&gt;\n</code></pre>\n\n<p><strong>EDIT:</strong> instead of using 2 different functions, you may use</p>\n\n<pre><code>&lt;?php wp_loginout(get_permalink()); ?&gt;\n</code></pre>\n\n<p>that displays a login link, or if a user is logged in, displays a logout link</p>\n" }, { "answer_id": 210483, "author": "Alex Stine", "author_id": 82369, "author_profile": "https://wordpress.stackexchange.com/users/82369", "pm_score": 0, "selected": false, "text": "<p>This is the code that fixed my problem:</p>\n\n<pre><code>add_filter( 'wp_nav_menu_items', 'add_login_logout_link', 10, 2 ); \n\nfunction add_login_logout_link( $items, $args ) {\n $pageURL = 'http://';\n $pageURL .= $_SERVER['HTTP_HOST'];\n $pageURL .= $_SERVER['REQUEST_URI'];\n\n ob_start();\n wp_loginout( $pageURL );\n $loginoutlink = ob_get_contents();\n ob_end_clean();\n $items .= '&lt;li&gt;'. $loginoutlink .'&lt;/li&gt;';\n return $items;\n}\n</code></pre>\n" } ]
2015/12/01
[ "https://wordpress.stackexchange.com/questions/210394", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84503/" ]
``` <?php /* Template Name : Home */ ?> get_header(); ?> <?php get_footer(); ?> ``` When I type anything on content editor of the page it doesn't show any thing. How do I make it working?
Use `wp_login_url()` function with `get_permalink()` as a parameter, if a user is not logged in. Something like this: ``` <a href="<?php echo wp_login_url( get_permalink() ); ?>" title="Login">Login</a> ``` And `wp_logout_url` function with `get_permalink()` as a parameter, if a user is logged in. ``` <a href="<?php echo wp_logout_url( get_permalink() ); ?>">Logout</a> ``` **EDIT:** instead of using 2 different functions, you may use ``` <?php wp_loginout(get_permalink()); ?> ``` that displays a login link, or if a user is logged in, displays a logout link
210,423
<p>I am using <a href="https://metabox.io/docs/" rel="nofollow">Metabox</a> to create metaboxes for Worpdress Post and it works like a charm. Now I have installed <a href="https://metabox.io/plugins/custom-post-type/" rel="nofollow">MetaBox Custom Post Type Extension</a> for create CPT and it works good to. I have <a href="https://wordpress.org/plugins/types/" rel="nofollow">Types</a> plugin installed for same purpose, create CPT so I can work either with Metabox or Types. I have created a CPT with slug <code>publicity</code> and I want to add some Metaboxes only to that CPT. How I can achieve this? I know how to create the Metaboxes using the plugin I just don't know how to make a difference between Wordpress post and this custom post type, perhaps by adding some conditional at <code>functions.php</code> and checking for post type slug and then including needed files but not sure and I need some push, any advice?</p>
[ { "answer_id": 210379, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": 1, "selected": false, "text": "<p>Use <code>wp_login_url()</code> function with <code>get_permalink()</code> as a parameter, if a user is not logged in. Something like this:</p>\n\n<pre><code>&lt;a href=\"&lt;?php echo wp_login_url( get_permalink() ); ?&gt;\" title=\"Login\"&gt;Login&lt;/a&gt;\n</code></pre>\n\n<p>And <code>wp_logout_url</code> function with <code>get_permalink()</code> as a parameter, if a user is logged in.</p>\n\n<pre><code>&lt;a href=\"&lt;?php echo wp_logout_url( get_permalink() ); ?&gt;\"&gt;Logout&lt;/a&gt;\n</code></pre>\n\n<p><strong>EDIT:</strong> instead of using 2 different functions, you may use</p>\n\n<pre><code>&lt;?php wp_loginout(get_permalink()); ?&gt;\n</code></pre>\n\n<p>that displays a login link, or if a user is logged in, displays a logout link</p>\n" }, { "answer_id": 210483, "author": "Alex Stine", "author_id": 82369, "author_profile": "https://wordpress.stackexchange.com/users/82369", "pm_score": 0, "selected": false, "text": "<p>This is the code that fixed my problem:</p>\n\n<pre><code>add_filter( 'wp_nav_menu_items', 'add_login_logout_link', 10, 2 ); \n\nfunction add_login_logout_link( $items, $args ) {\n $pageURL = 'http://';\n $pageURL .= $_SERVER['HTTP_HOST'];\n $pageURL .= $_SERVER['REQUEST_URI'];\n\n ob_start();\n wp_loginout( $pageURL );\n $loginoutlink = ob_get_contents();\n ob_end_clean();\n $items .= '&lt;li&gt;'. $loginoutlink .'&lt;/li&gt;';\n return $items;\n}\n</code></pre>\n" } ]
2015/12/01
[ "https://wordpress.stackexchange.com/questions/210423", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16412/" ]
I am using [Metabox](https://metabox.io/docs/) to create metaboxes for Worpdress Post and it works like a charm. Now I have installed [MetaBox Custom Post Type Extension](https://metabox.io/plugins/custom-post-type/) for create CPT and it works good to. I have [Types](https://wordpress.org/plugins/types/) plugin installed for same purpose, create CPT so I can work either with Metabox or Types. I have created a CPT with slug `publicity` and I want to add some Metaboxes only to that CPT. How I can achieve this? I know how to create the Metaboxes using the plugin I just don't know how to make a difference between Wordpress post and this custom post type, perhaps by adding some conditional at `functions.php` and checking for post type slug and then including needed files but not sure and I need some push, any advice?
Use `wp_login_url()` function with `get_permalink()` as a parameter, if a user is not logged in. Something like this: ``` <a href="<?php echo wp_login_url( get_permalink() ); ?>" title="Login">Login</a> ``` And `wp_logout_url` function with `get_permalink()` as a parameter, if a user is logged in. ``` <a href="<?php echo wp_logout_url( get_permalink() ); ?>">Logout</a> ``` **EDIT:** instead of using 2 different functions, you may use ``` <?php wp_loginout(get_permalink()); ?> ``` that displays a login link, or if a user is logged in, displays a logout link
210,438
<p>We have a class which is common to few plugins that we develop. As time goes we improve the class and add new functions so we have class variable which is the class version. </p> <p>Because multiple plugins have this class with different versions it's happen that a plugin initiate an older version of the class because it's loaded first and another plugin which may need the new version does not initiate it as it was already defined. </p> <p>What is the best way to manage this kind of situation so only the newest version of the class will be the one the will be declared &amp; initiate. </p> <p>Thanks Bob </p>
[ { "answer_id": 210440, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 1, "selected": false, "text": "<p>If you are using a version control (like Git) then using a submodule seems the best way to version a common piece among projects.</p>\n\n<p>Your class as a submodule then becomes a child of multiple parent plugins:\n<a href=\"https://git-scm.com/book/en/v2/Git-Tools-Submodules\" rel=\"nofollow\">https://git-scm.com/book/en/v2/Git-Tools-Submodules</a></p>\n" }, { "answer_id": 210444, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://github.com/WebDevStudios/CMB2\" rel=\"nofollow\">CMB2</a> has a clever way of handling the same situation. It establishes a version constant that is a high number for the first release (9999), and on each subsequent release, the version constant is decremented. The version number is used for the priority of the action that instantiates the main class. This ensures that the most recent version of the library is loaded.</p>\n\n<p>From CMB2's <a href=\"https://github.com/WebDevStudios/CMB2/blob/master/init.php\" rel=\"nofollow\">init.php</a></p>\n\n<pre><code>if ( ! class_exists( 'CMB2_Bootstrap_212', false ) ) {\n /**\n * Handles checking for and loading the newest version of CMB2\n *\n * @since 2.0.0\n *\n * @category WordPress_Plugin\n * @package CMB2\n * @author WebDevStudios\n * @license GPL-2.0+\n * @link http://webdevstudios.com\n */\n class CMB2_Bootstrap_212 {\n /**\n * Current version number\n * @var string\n * @since 1.0.0\n */\n const VERSION = '2.1.2';\n /**\n * Current version hook priority.\n * Will decrement with each release\n *\n * @var int\n * @since 2.0.0\n */\n const PRIORITY = 9987;\n /**\n * Single instance of the CMB2_Bootstrap_212 object\n *\n * @var CMB2_Bootstrap_212\n */\n public static $single_instance = null;\n /**\n * Creates/returns the single instance CMB2_Bootstrap_212 object\n *\n * @since 2.0.0\n * @return CMB2_Bootstrap_212 Single instance object\n */\n public static function initiate() {\n if ( null === self::$single_instance ) {\n self::$single_instance = new self();\n }\n return self::$single_instance;\n }\n /**\n * Starts the version checking process.\n * Creates CMB2_LOADED definition for early detection by other scripts\n *\n * Hooks CMB2 inclusion to the init hook on a high priority which decrements\n * (increasing the priority) with each version release.\n *\n * @since 2.0.0\n */\n private function __construct() {\n /**\n * A constant you can use to check if CMB2 is loaded\n * for your plugins/themes with CMB2 dependency\n */\n if ( ! defined( 'CMB2_LOADED' ) ) {\n define( 'CMB2_LOADED', true );\n }\n add_action( 'init', array( $this, 'include_cmb' ), self::PRIORITY );\n }\n /**\n * A final check if CMB2 exists before kicking off our CMB2 loading.\n * CMB2_VERSION and CMB2_DIR constants are set at this point.\n *\n * @since 2.0.0\n */\n public function include_cmb() {\n if ( class_exists( 'CMB2', false ) ) {\n return;\n }\n if ( ! defined( 'CMB2_VERSION' ) ) {\n define( 'CMB2_VERSION', self::VERSION );\n }\n if ( ! defined( 'CMB2_DIR' ) ) {\n define( 'CMB2_DIR', trailingslashit( dirname( __FILE__ ) ) );\n }\n $this-&gt;l10ni18n();\n // Include helper functions\n require_once 'includes/helper-functions.php';\n // Now kick off the class autoloader\n spl_autoload_register( 'cmb2_autoload_classes' );\n // Kick the whole thing off\n require_once 'bootstrap.php';\n }\n\n /**\n * Registers CMB2 text domain path\n * @since 2.0.0\n */\n public function l10ni18n() {\n $loaded = load_plugin_textdomain( 'cmb2', false, '/languages/' );\n if ( ! $loaded ) {\n $loaded = load_muplugin_textdomain( 'cmb2', '/languages/' );\n }\n if ( ! $loaded ) {\n $loaded = load_theme_textdomain( 'cmb2', get_stylesheet_directory() . '/languages/' );\n }\n if ( ! $loaded ) {\n $locale = apply_filters( 'plugin_locale', get_locale(), 'cmb2' );\n $mofile = dirname( __FILE__ ) . '/languages/cmb2-' . $locale . '.mo';\n load_textdomain( 'cmb2', $mofile );\n }\n }\n }\n // Make it so...\n CMB2_Bootstrap_212::initiate();\n}\n</code></pre>\n" } ]
2015/12/01
[ "https://wordpress.stackexchange.com/questions/210438", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28237/" ]
We have a class which is common to few plugins that we develop. As time goes we improve the class and add new functions so we have class variable which is the class version. Because multiple plugins have this class with different versions it's happen that a plugin initiate an older version of the class because it's loaded first and another plugin which may need the new version does not initiate it as it was already defined. What is the best way to manage this kind of situation so only the newest version of the class will be the one the will be declared & initiate. Thanks Bob
[CMB2](https://github.com/WebDevStudios/CMB2) has a clever way of handling the same situation. It establishes a version constant that is a high number for the first release (9999), and on each subsequent release, the version constant is decremented. The version number is used for the priority of the action that instantiates the main class. This ensures that the most recent version of the library is loaded. From CMB2's [init.php](https://github.com/WebDevStudios/CMB2/blob/master/init.php) ``` if ( ! class_exists( 'CMB2_Bootstrap_212', false ) ) { /** * Handles checking for and loading the newest version of CMB2 * * @since 2.0.0 * * @category WordPress_Plugin * @package CMB2 * @author WebDevStudios * @license GPL-2.0+ * @link http://webdevstudios.com */ class CMB2_Bootstrap_212 { /** * Current version number * @var string * @since 1.0.0 */ const VERSION = '2.1.2'; /** * Current version hook priority. * Will decrement with each release * * @var int * @since 2.0.0 */ const PRIORITY = 9987; /** * Single instance of the CMB2_Bootstrap_212 object * * @var CMB2_Bootstrap_212 */ public static $single_instance = null; /** * Creates/returns the single instance CMB2_Bootstrap_212 object * * @since 2.0.0 * @return CMB2_Bootstrap_212 Single instance object */ public static function initiate() { if ( null === self::$single_instance ) { self::$single_instance = new self(); } return self::$single_instance; } /** * Starts the version checking process. * Creates CMB2_LOADED definition for early detection by other scripts * * Hooks CMB2 inclusion to the init hook on a high priority which decrements * (increasing the priority) with each version release. * * @since 2.0.0 */ private function __construct() { /** * A constant you can use to check if CMB2 is loaded * for your plugins/themes with CMB2 dependency */ if ( ! defined( 'CMB2_LOADED' ) ) { define( 'CMB2_LOADED', true ); } add_action( 'init', array( $this, 'include_cmb' ), self::PRIORITY ); } /** * A final check if CMB2 exists before kicking off our CMB2 loading. * CMB2_VERSION and CMB2_DIR constants are set at this point. * * @since 2.0.0 */ public function include_cmb() { if ( class_exists( 'CMB2', false ) ) { return; } if ( ! defined( 'CMB2_VERSION' ) ) { define( 'CMB2_VERSION', self::VERSION ); } if ( ! defined( 'CMB2_DIR' ) ) { define( 'CMB2_DIR', trailingslashit( dirname( __FILE__ ) ) ); } $this->l10ni18n(); // Include helper functions require_once 'includes/helper-functions.php'; // Now kick off the class autoloader spl_autoload_register( 'cmb2_autoload_classes' ); // Kick the whole thing off require_once 'bootstrap.php'; } /** * Registers CMB2 text domain path * @since 2.0.0 */ public function l10ni18n() { $loaded = load_plugin_textdomain( 'cmb2', false, '/languages/' ); if ( ! $loaded ) { $loaded = load_muplugin_textdomain( 'cmb2', '/languages/' ); } if ( ! $loaded ) { $loaded = load_theme_textdomain( 'cmb2', get_stylesheet_directory() . '/languages/' ); } if ( ! $loaded ) { $locale = apply_filters( 'plugin_locale', get_locale(), 'cmb2' ); $mofile = dirname( __FILE__ ) . '/languages/cmb2-' . $locale . '.mo'; load_textdomain( 'cmb2', $mofile ); } } } // Make it so... CMB2_Bootstrap_212::initiate(); } ```
210,459
<p>To further clarify my question: Reviewing sites like Polygon have sections where you click on Reviews, and it shows you a page with a grid of all their reviews (latest will be at the top though). They usually have a thumbnail of the game on the left, some text in the middle, and then a score on the right. Here's an <a href="http://www.gamespot.com/reviews/" rel="nofollow noreferrer">example</a>. </p> <p>I actually made a page like this with the slug "review". I also have a custom post type with the slug "reviews". I used a page builder plugin (Beaver) to make "review" look exactly like a popular reviewing site's review page, but the problem with this is that it won't make new pages for every x amount of posts (i.e., it doesn't do what archive pages do: show all your latest posts and make a new page when you it displays the max amount of posts that you want to be shown on a page). So I'd have to create the page titled "review/2", and then I'd also have to add pagination at the bottom to make it link to the next page. Also, I have to manually update any of the pages with the slug "review". This is how it looks like: <a href="https://i.stack.imgur.com/bgCeh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bgCeh.jpg" alt="review"></a>.</p> <p>To clarify on the image, I use a thumbnail on the left (not a featured image), a text editor in the middle, and another image on the right (not a featured image).</p> <p>Now, "reviews" isn't like this; the way the archive is formatted is just like a blog's home page: have the header of the post, the content of the post, and the footer of that post. I would love it if I could just modify the archive page of "reviews" to look like "review", which would then also automatically update whenever I made a new review, and get rid of "review". </p> <p>I have the archive-reviews.php and content-reviews.php already set up, I just want to know if it's possible for me to get my archive page for "reviews" to look like the "review" page. </p> <p>In conclusion: Can you either...</p> <ol> <li>shed light on how review sites get their review pages to look like that and maybe I can implement that into my archive page</li> <li>or... tell me if I should just do it the long and manual way</li> <li>or... give me insight into how I can get my "reviews" archive page to look like my "review" page, which I provided you an image of. </li> </ol> <p>P.S. Sorry for the wordiness! Ask for clarification if you need any. </p>
[ { "answer_id": 210440, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 1, "selected": false, "text": "<p>If you are using a version control (like Git) then using a submodule seems the best way to version a common piece among projects.</p>\n\n<p>Your class as a submodule then becomes a child of multiple parent plugins:\n<a href=\"https://git-scm.com/book/en/v2/Git-Tools-Submodules\" rel=\"nofollow\">https://git-scm.com/book/en/v2/Git-Tools-Submodules</a></p>\n" }, { "answer_id": 210444, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://github.com/WebDevStudios/CMB2\" rel=\"nofollow\">CMB2</a> has a clever way of handling the same situation. It establishes a version constant that is a high number for the first release (9999), and on each subsequent release, the version constant is decremented. The version number is used for the priority of the action that instantiates the main class. This ensures that the most recent version of the library is loaded.</p>\n\n<p>From CMB2's <a href=\"https://github.com/WebDevStudios/CMB2/blob/master/init.php\" rel=\"nofollow\">init.php</a></p>\n\n<pre><code>if ( ! class_exists( 'CMB2_Bootstrap_212', false ) ) {\n /**\n * Handles checking for and loading the newest version of CMB2\n *\n * @since 2.0.0\n *\n * @category WordPress_Plugin\n * @package CMB2\n * @author WebDevStudios\n * @license GPL-2.0+\n * @link http://webdevstudios.com\n */\n class CMB2_Bootstrap_212 {\n /**\n * Current version number\n * @var string\n * @since 1.0.0\n */\n const VERSION = '2.1.2';\n /**\n * Current version hook priority.\n * Will decrement with each release\n *\n * @var int\n * @since 2.0.0\n */\n const PRIORITY = 9987;\n /**\n * Single instance of the CMB2_Bootstrap_212 object\n *\n * @var CMB2_Bootstrap_212\n */\n public static $single_instance = null;\n /**\n * Creates/returns the single instance CMB2_Bootstrap_212 object\n *\n * @since 2.0.0\n * @return CMB2_Bootstrap_212 Single instance object\n */\n public static function initiate() {\n if ( null === self::$single_instance ) {\n self::$single_instance = new self();\n }\n return self::$single_instance;\n }\n /**\n * Starts the version checking process.\n * Creates CMB2_LOADED definition for early detection by other scripts\n *\n * Hooks CMB2 inclusion to the init hook on a high priority which decrements\n * (increasing the priority) with each version release.\n *\n * @since 2.0.0\n */\n private function __construct() {\n /**\n * A constant you can use to check if CMB2 is loaded\n * for your plugins/themes with CMB2 dependency\n */\n if ( ! defined( 'CMB2_LOADED' ) ) {\n define( 'CMB2_LOADED', true );\n }\n add_action( 'init', array( $this, 'include_cmb' ), self::PRIORITY );\n }\n /**\n * A final check if CMB2 exists before kicking off our CMB2 loading.\n * CMB2_VERSION and CMB2_DIR constants are set at this point.\n *\n * @since 2.0.0\n */\n public function include_cmb() {\n if ( class_exists( 'CMB2', false ) ) {\n return;\n }\n if ( ! defined( 'CMB2_VERSION' ) ) {\n define( 'CMB2_VERSION', self::VERSION );\n }\n if ( ! defined( 'CMB2_DIR' ) ) {\n define( 'CMB2_DIR', trailingslashit( dirname( __FILE__ ) ) );\n }\n $this-&gt;l10ni18n();\n // Include helper functions\n require_once 'includes/helper-functions.php';\n // Now kick off the class autoloader\n spl_autoload_register( 'cmb2_autoload_classes' );\n // Kick the whole thing off\n require_once 'bootstrap.php';\n }\n\n /**\n * Registers CMB2 text domain path\n * @since 2.0.0\n */\n public function l10ni18n() {\n $loaded = load_plugin_textdomain( 'cmb2', false, '/languages/' );\n if ( ! $loaded ) {\n $loaded = load_muplugin_textdomain( 'cmb2', '/languages/' );\n }\n if ( ! $loaded ) {\n $loaded = load_theme_textdomain( 'cmb2', get_stylesheet_directory() . '/languages/' );\n }\n if ( ! $loaded ) {\n $locale = apply_filters( 'plugin_locale', get_locale(), 'cmb2' );\n $mofile = dirname( __FILE__ ) . '/languages/cmb2-' . $locale . '.mo';\n load_textdomain( 'cmb2', $mofile );\n }\n }\n }\n // Make it so...\n CMB2_Bootstrap_212::initiate();\n}\n</code></pre>\n" } ]
2015/12/01
[ "https://wordpress.stackexchange.com/questions/210459", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84582/" ]
To further clarify my question: Reviewing sites like Polygon have sections where you click on Reviews, and it shows you a page with a grid of all their reviews (latest will be at the top though). They usually have a thumbnail of the game on the left, some text in the middle, and then a score on the right. Here's an [example](http://www.gamespot.com/reviews/). I actually made a page like this with the slug "review". I also have a custom post type with the slug "reviews". I used a page builder plugin (Beaver) to make "review" look exactly like a popular reviewing site's review page, but the problem with this is that it won't make new pages for every x amount of posts (i.e., it doesn't do what archive pages do: show all your latest posts and make a new page when you it displays the max amount of posts that you want to be shown on a page). So I'd have to create the page titled "review/2", and then I'd also have to add pagination at the bottom to make it link to the next page. Also, I have to manually update any of the pages with the slug "review". This is how it looks like: [![review](https://i.stack.imgur.com/bgCeh.jpg)](https://i.stack.imgur.com/bgCeh.jpg). To clarify on the image, I use a thumbnail on the left (not a featured image), a text editor in the middle, and another image on the right (not a featured image). Now, "reviews" isn't like this; the way the archive is formatted is just like a blog's home page: have the header of the post, the content of the post, and the footer of that post. I would love it if I could just modify the archive page of "reviews" to look like "review", which would then also automatically update whenever I made a new review, and get rid of "review". I have the archive-reviews.php and content-reviews.php already set up, I just want to know if it's possible for me to get my archive page for "reviews" to look like the "review" page. In conclusion: Can you either... 1. shed light on how review sites get their review pages to look like that and maybe I can implement that into my archive page 2. or... tell me if I should just do it the long and manual way 3. or... give me insight into how I can get my "reviews" archive page to look like my "review" page, which I provided you an image of. P.S. Sorry for the wordiness! Ask for clarification if you need any.
[CMB2](https://github.com/WebDevStudios/CMB2) has a clever way of handling the same situation. It establishes a version constant that is a high number for the first release (9999), and on each subsequent release, the version constant is decremented. The version number is used for the priority of the action that instantiates the main class. This ensures that the most recent version of the library is loaded. From CMB2's [init.php](https://github.com/WebDevStudios/CMB2/blob/master/init.php) ``` if ( ! class_exists( 'CMB2_Bootstrap_212', false ) ) { /** * Handles checking for and loading the newest version of CMB2 * * @since 2.0.0 * * @category WordPress_Plugin * @package CMB2 * @author WebDevStudios * @license GPL-2.0+ * @link http://webdevstudios.com */ class CMB2_Bootstrap_212 { /** * Current version number * @var string * @since 1.0.0 */ const VERSION = '2.1.2'; /** * Current version hook priority. * Will decrement with each release * * @var int * @since 2.0.0 */ const PRIORITY = 9987; /** * Single instance of the CMB2_Bootstrap_212 object * * @var CMB2_Bootstrap_212 */ public static $single_instance = null; /** * Creates/returns the single instance CMB2_Bootstrap_212 object * * @since 2.0.0 * @return CMB2_Bootstrap_212 Single instance object */ public static function initiate() { if ( null === self::$single_instance ) { self::$single_instance = new self(); } return self::$single_instance; } /** * Starts the version checking process. * Creates CMB2_LOADED definition for early detection by other scripts * * Hooks CMB2 inclusion to the init hook on a high priority which decrements * (increasing the priority) with each version release. * * @since 2.0.0 */ private function __construct() { /** * A constant you can use to check if CMB2 is loaded * for your plugins/themes with CMB2 dependency */ if ( ! defined( 'CMB2_LOADED' ) ) { define( 'CMB2_LOADED', true ); } add_action( 'init', array( $this, 'include_cmb' ), self::PRIORITY ); } /** * A final check if CMB2 exists before kicking off our CMB2 loading. * CMB2_VERSION and CMB2_DIR constants are set at this point. * * @since 2.0.0 */ public function include_cmb() { if ( class_exists( 'CMB2', false ) ) { return; } if ( ! defined( 'CMB2_VERSION' ) ) { define( 'CMB2_VERSION', self::VERSION ); } if ( ! defined( 'CMB2_DIR' ) ) { define( 'CMB2_DIR', trailingslashit( dirname( __FILE__ ) ) ); } $this->l10ni18n(); // Include helper functions require_once 'includes/helper-functions.php'; // Now kick off the class autoloader spl_autoload_register( 'cmb2_autoload_classes' ); // Kick the whole thing off require_once 'bootstrap.php'; } /** * Registers CMB2 text domain path * @since 2.0.0 */ public function l10ni18n() { $loaded = load_plugin_textdomain( 'cmb2', false, '/languages/' ); if ( ! $loaded ) { $loaded = load_muplugin_textdomain( 'cmb2', '/languages/' ); } if ( ! $loaded ) { $loaded = load_theme_textdomain( 'cmb2', get_stylesheet_directory() . '/languages/' ); } if ( ! $loaded ) { $locale = apply_filters( 'plugin_locale', get_locale(), 'cmb2' ); $mofile = dirname( __FILE__ ) . '/languages/cmb2-' . $locale . '.mo'; load_textdomain( 'cmb2', $mofile ); } } } // Make it so... CMB2_Bootstrap_212::initiate(); } ```
210,463
<p>I have IDs for my child categories, <code>11,14,21,35,38,39</code>, where these all are various child categories from their main category:</p> <ul> <li>Parent category <code>1</code> has: <code>11,14</code></li> <li>Parent category <code>2</code> has: <code>21</code></li> <li>Parent category <code>3</code> has: <code>35,38,39</code></li> </ul> <p>How can I group my child IDs as per their parent category, like below?</p> <pre><code>array( 1 =&gt; array ( 11,14 ), 2 =&gt; array ( 21 ), 3 =&gt; array ( 35,38,39 ) ) </code></pre>
[ { "answer_id": 210471, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": true, "text": "<p>The quick take would be something like this:</p>\n\n<pre><code>$categories = [ ];\n$parent_categories = get_categories( [ 'parent' =&gt; 0 ] );\n\nforeach ( $parent_categories as $parent_category ) {\n $id = $parent_category-&gt;term_id;\n $categories[ $id ] = wp_list_pluck( get_categories( [ 'parent' =&gt; $id ] ), 'term_id' );\n}\n</code></pre>\n\n<p>The important bit is a <code>parent</code> argument, which limits retrieved to immediate children (parent of 0 is a top level).</p>\n\n<p>Depending on how <em>many</em> of these you have it might be preferable to instead retrieve all of them first and then re-arrange out of singe result set.</p>\n" }, { "answer_id": 311610, "author": "Reza Mamun", "author_id": 10556, "author_profile": "https://wordpress.stackexchange.com/users/10556", "pm_score": 0, "selected": false, "text": "<p>I had exactly same requirement as you. The below piece of code is my solution:</p>\n\n<pre><code>$termArr = array();\n$termIds = array_filter(explode(',','11,14,21,35,38,39'),'is_numeric');\nif( !empty($termIds) ){\n $terms = get_terms(array(\n 'taxonomy' =&gt; 'my_taxonomy',\n 'include' =&gt; $termIds\n ));\n\n foreach($terms as $t){\n if( !isset($termArr[$t-&gt;parent]) )\n $termArr[$t-&gt;parent] = array();\n $termArr[$t-&gt;parent][] = $t-&gt;term_id;\n }\n\n print_r($termArr); //===&gt; This is the array which you need :)\n}\n</code></pre>\n" } ]
2015/12/01
[ "https://wordpress.stackexchange.com/questions/210463", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84151/" ]
I have IDs for my child categories, `11,14,21,35,38,39`, where these all are various child categories from their main category: * Parent category `1` has: `11,14` * Parent category `2` has: `21` * Parent category `3` has: `35,38,39` How can I group my child IDs as per their parent category, like below? ``` array( 1 => array ( 11,14 ), 2 => array ( 21 ), 3 => array ( 35,38,39 ) ) ```
The quick take would be something like this: ``` $categories = [ ]; $parent_categories = get_categories( [ 'parent' => 0 ] ); foreach ( $parent_categories as $parent_category ) { $id = $parent_category->term_id; $categories[ $id ] = wp_list_pluck( get_categories( [ 'parent' => $id ] ), 'term_id' ); } ``` The important bit is a `parent` argument, which limits retrieved to immediate children (parent of 0 is a top level). Depending on how *many* of these you have it might be preferable to instead retrieve all of them first and then re-arrange out of singe result set.
210,493
<p>I have this piece of code:</p> <pre><code>$normal_args = array( 'order' =&gt; 'desc', 'ignore_sticky_posts' =&gt; 1, 'meta_query' =&gt; array( array( 'key' =&gt; 'rw_show_at_position', 'value' =&gt; '1', 'compare' =&gt; '=' ) ), 'post__not_in' =&gt; $prev_post_ids, 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; get_option( 'column_right' ), 'post_type' =&gt; array( 'opinion', 'especiales', 'clasificados', 'portadadeldia', 'anunciantes', 'post', 'pages', 'esp-publicitarios' ) ); $normal_query = new WP_Query( $normal_args ); $i = 0; if ( $normal_query-&gt;have_posts() ) { while ( $normal_query-&gt;have_posts() ) { $normal_query-&gt;the_post(); ?&gt; &lt;?php echo $i . ' ==&gt; '; ?&gt; &lt;?php if ( get_post_type( $post-&gt;ID ) == 'esp-publicitarios' ) { $adv_pos = rwmb_meta( 'rw_adversiting_position', 'type=select', $post-&gt;ID ); echo $adv_pos . EOL; } else { ?&gt; // do something here &lt;?php } $i ++; } } </code></pre> <p>And I want to reorder items based on <code>post_type</code> and a metakey <code>rw_adversiting_position</code> and then display them normally. Right now I am getting this result:</p> <pre><code>0 ==&gt; 183034 ==&gt; 9 1 ==&gt; 183033 ==&gt; 6 2 ==&gt; 183032 ==&gt; 3 3 ==&gt; 183002 ==&gt; 4 ==&gt; 182973 ==&gt; 5 ==&gt; 182971 ==&gt; 6 ==&gt; 182969 ==&gt; 7 ==&gt; 182999 ==&gt; 8 ==&gt; 182997 ==&gt; 9 ==&gt; 182995 ==&gt; 10 ==&gt; 182962 ==&gt; 11 ==&gt; 182948 ==&gt; </code></pre> <p>That's because only the 0, 1 and 2 are <code>esp-publicitarios</code> post types. The number at the right 9, 6 and 3 is the position where I should push the item so having this info the result should be something like: </p> <pre><code>0 ==&gt; 183002 ==&gt; 1 ==&gt; 182973 ==&gt; 2 ==&gt; 182971 ==&gt; 2 ==&gt; 183032 ==&gt; 3 4 ==&gt; 182969 ==&gt; 5 ==&gt; 182999 ==&gt; 6 ==&gt; 183033 ==&gt; 6 7 ==&gt; 182997 ==&gt; 8 ==&gt; 182995 ==&gt; 9 ==&gt; 183034 ==&gt; 9 10 ==&gt; 182962 ==&gt; 11 ==&gt; 182948 ==&gt; </code></pre> <p>Can any give me some ideas to achieve this? </p> <p><strong>UPDATE 1</strong></p> <p>I did found <a href="http://kuttler.eu/code/order-posts-in-a-wp_query-manually/" rel="nofollow">this</a> but I am not sure how to apply it.</p> <p><strong>UPDATE 2</strong></p> <p>This is the PHP code for achieve the sorting, <code>sort_position</code> could be <code>rw_adversiting_position</code>:</p> <pre><code>$arr = [ '183034' =&gt; [ 'sort_position' =&gt; 9 ], '183033' =&gt; [ 'sort_position' =&gt; 5 ], '183032' =&gt; [ 'sort_position' =&gt; 3 ], '183002' =&gt; [ ], '182973' =&gt; [ ], '182971' =&gt; [ ], '182969' =&gt; [ ], '182999' =&gt; [ ], '182997' =&gt; [ ], '182995' =&gt; [ ], '182962' =&gt; [ ], '182948' =&gt; [ ] ]; $count = count( $arr ); $has_sortorder = [ ]; $no_sortorder = [ ]; krsort( $arr ); foreach ( $arr as $key =&gt; $val ) { if ( isset( $val['sort_position'] ) ) { $has_sortorder[ $val['sort_position'] ] = [ $key, $val ]; } else { $no_sortorder[] = [ $key, $val ]; } } $out = [ ]; for ( $i = 0; $i &lt; $count; $i ++ ) { if ( isset( $has_sortorder[ $i ] ) ) { $out[ $has_sortorder[ $i ][0] ] = $has_sortorder[ $i ][1]; } else { $element = array_shift( $no_sortorder ); $out[ $element[0] ] = $element[1]; } } var_dump( $out ); </code></pre> <p>I just need to know how to apply this to WP_Query before get the result, any?</p> <p><strong>UPDATE 3</strong></p> <p>Here is a snippet of <code>var_export($normal_query-&gt;posts)</code> as you can see there is no meta-key so I can order based on values of a meta, then how?</p> <pre><code>$var = array( 0 =&gt; WP_Post::__set_state( array( 'ID' =&gt; 183034, 'post_author' =&gt; '4', 'post_date' =&gt; '2015-12-01 16:44:35', 'post_date_gmt' =&gt; '2015-12-01 21:14:35', 'post_content' =&gt; '', 'post_title' =&gt; 'Espacio Pub 3', 'post_excerpt' =&gt; '', 'post_status' =&gt; 'publish', 'comment_status' =&gt; 'closed', 'ping_status' =&gt; 'closed', 'post_password' =&gt; '', 'post_name' =&gt; 'espacio-pub-3', 'to_ping' =&gt; '', 'pinged' =&gt; '', 'post_modified' =&gt; '2015-12-01 16:54:38', 'post_modified_gmt' =&gt; '2015-12-01 21:24:38', 'post_content_filtered' =&gt; '', 'post_parent' =&gt; 0, 'guid' =&gt; 'http://elclarinweb.local/?post_type=esp-publicitarios&amp;p=183034', 'menu_order' =&gt; 0, 'post_type' =&gt; 'esp-publicitarios', 'post_mime_type' =&gt; '', 'comment_count' =&gt; '0', 'filter' =&gt; 'raw', ) ), 1 =&gt; WP_Post::__set_state( array( 'ID' =&gt; 183033, 'post_author' =&gt; '4', 'post_date' =&gt; '2015-12-01 16:44:13', 'post_date_gmt' =&gt; '2015-12-01 21:14:13', 'post_content' =&gt; '', 'post_title' =&gt; 'Espacio Pub 2', 'post_excerpt' =&gt; '', 'post_status' =&gt; 'publish', 'comment_status' =&gt; 'closed', 'ping_status' =&gt; 'closed', 'post_password' =&gt; '', 'post_name' =&gt; '183033', 'to_ping' =&gt; '', 'pinged' =&gt; '', 'post_modified' =&gt; '2015-12-01 16:44:21', 'post_modified_gmt' =&gt; '2015-12-01 21:14:21', 'post_content_filtered' =&gt; '', 'post_parent' =&gt; 0, 'guid' =&gt; 'http://elclarinweb.local/?post_type=esp-publicitarios&amp;p=183033', 'menu_order' =&gt; 0, 'post_type' =&gt; 'esp-publicitarios', 'post_mime_type' =&gt; '', 'comment_count' =&gt; '0', 'filter' =&gt; 'raw', ) ), 2 =&gt; WP_Post::__set_state( array( 'ID' =&gt; 183032, 'post_author' =&gt; '4', 'post_date' =&gt; '2015-12-01 15:53:56', 'post_date_gmt' =&gt; '2015-12-01 20:23:56', 'post_content' =&gt; '', 'post_title' =&gt; 'Publicidad 1', 'post_excerpt' =&gt; '', 'post_status' =&gt; 'publish', 'comment_status' =&gt; 'closed', 'ping_status' =&gt; 'closed', 'post_password' =&gt; '', 'post_name' =&gt; 'publicidad-1', 'to_ping' =&gt; '', 'pinged' =&gt; '', 'post_modified' =&gt; '2015-12-01 15:53:56', 'post_modified_gmt' =&gt; '2015-12-01 20:23:56', 'post_content_filtered' =&gt; '', 'post_parent' =&gt; 0, 'guid' =&gt; 'http://elclarinweb.local/?post_type=esp-publicitarios&amp;p=183032', 'menu_order' =&gt; 0, 'post_type' =&gt; 'esp-publicitarios', 'post_mime_type' =&gt; '', 'comment_count' =&gt; '0', 'filter' =&gt; 'raw', ) ), 3 =&gt; WP_Post::__set_state( array( 'ID' =&gt; 183002, 'post_author' =&gt; '7', 'post_date' =&gt; '2015-11-22 00:08:00', 'post_date_gmt' =&gt; '2015-11-22 04:38:00', 'post_content' =&gt; 'Borrón y cuenta nueva es lo que han hecho los Bravos de Margarita en este comienzo de la segunda parte de la campaña, en la que ayer sumaron su cuarto triunfo seguido, al vencer a los Tiburones de La Guaira 5 carreras por 3. Margarita, que ganó dos de tres ante los escualos en la semana, madrugó al dominicano Alexis Candelario, quien llegó a dicha cita como el mejor lanzador del campeonato. Los artilleros isleños fabricaron cuatro de sus cinco carreras en las primeras dos entradas, catapultados por un doble impulsor de dos de Eliézer Alfonzo. “No importa quién esté en la lomita contraria, siempre que los muchachos crean en ellos mismos, estos van a ser los resultados”, señaló el dirigente Henry Blanco. Bravos se haría presente en el marcador una vez más en el sexto con doble remolcador del jardinero Junior Sosa y aguantaría un intento de remontada de los litoralenses en la parte final para sellar el lauro. “La mentalidad que tenemos es no pensar en la primera parte, hay que salir a ganar”, indicó Alfonzo, quien cerró el cotejo de 5-2 con un par de impulsadas y ahora acumula cinco rayitas traídas al plato en los últimos dos desafíos. “Estaba bastante perdido cuando comenzó la temporada, pero he hecho el ajuste necesario”.', 'post_title' =&gt; 'Ahora Bravos es puntero de la LVBP', 'post_excerpt' =&gt; 'Las curiosidades del nuevo sistema de puntos del torneo coloca al antiguo colero de puntero', 'post_status' =&gt; 'publish', 'comment_status' =&gt; 'open', 'ping_status' =&gt; 'open', 'post_password' =&gt; '', 'post_name' =&gt; 'ahora-bravos-es-puntero-de-la-lvbp', 'to_ping' =&gt; '', 'pinged' =&gt; '', 'post_modified' =&gt; '2015-11-22 00:08:00', 'post_modified_gmt' =&gt; '2015-11-22 04:38:00', 'post_content_filtered' =&gt; '', 'post_parent' =&gt; 0, 'guid' =&gt; 'http://elclarinweb.local/?p=183002', 'menu_order' =&gt; 0, 'post_type' =&gt; 'post', 'post_mime_type' =&gt; '', 'comment_count' =&gt; '0', 'filter' =&gt; 'raw' ) ) ); </code></pre> <p><strong>UPDATE 4</strong></p> <p>@bosco I have made some minors changes to your code and now it looks as follow:</p> <pre><code>function wpse_210493_apply_advertising_position( &amp;$posts, $return = false ) { $ad_posts = array(); // Seperate $posts into "Ads" and "Content" arrays based on whether or not they have 'rw_adversiting_position' meta-data foreach ( $posts as $post ) { $position = intval( get_post_meta( $post-&gt;ID, 'rw_adversiting_position', true ) ); $post_date = $post-&gt;post_date; $post_modified = $post-&gt;post_modified; if ( ! empty( $position ) ) { if ( ! empty ( $ad_posts ) ) { if ( $post_date &gt; $ad_posts[ $position ]-&gt;post_date || $post_modified &gt; $ad_posts[ $position ]-&gt;post_modified ) { $ad_posts[ $position ] = $post; } } else { $ad_posts[ $position ] = $post; } } else { $content_posts[] = $post; } } // Sort the ads from smallest position index to greatest such that re-insertion properly factors in all ads ksort( $ad_posts ); // Add the ads back into the content at their specified positions foreach ( $ad_posts as $position =&gt; $ad ) { array_splice( $content_posts, $position, 0, array( $ad ) ); } // If $return is true, return the resulting array. Otherwise replace the original $posts array with it. if ( $return ) { return $content_posts; } else { $posts = $content_posts; } } </code></pre> <p>If I debug this on the template I get the following output:</p> <pre><code>echo '&lt;pre&gt; BEFORE'; echo count($normal_query-&gt;posts); echo '&lt;/pre&gt;'; wpse_210493_apply_advertising_position( $normal_query-&gt;posts ); echo '&lt;pre&gt; AFTER'; echo count($normal_query-&gt;posts); echo '&lt;/pre&gt;'; // Output BEFORE25 AFTER23 </code></pre> <p>The AFTER is the right value but the loop is using the BEFORE and is adding to empty elements on the loop, why? See <a href="http://content.screencast.com/users/ReynierPM/folders/Snagit/media/52f01187-79a5-4363-a8d1-e8c1decd5490/12.04.2015-22.01.png" rel="nofollow">this pic</a> for more info.</p>
[ { "answer_id": 210613, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 3, "selected": true, "text": "<p>You could use the <a href=\"https://codex.wordpress.org/Metadata_API\" rel=\"nofollow noreferrer\">Metadata API</a> to retrieve the <code>rw_advertising_position</code> metadata for each post, seperate the ads from the content, and then re-insert the ads at the proper locations:</p>\n\n<pre><code>/**\n * Extracts from an array posts with positional metadata and re-inserts them at the proper\n * indices. See https://wordpress.stackexchange.com/questions/210493\n **/\nfunction wpse_210493_apply_advertising_position( &amp;$posts, $return = false ) {\n $ad_posts = array();\n $content_posts = array();\n\n // Seperate $posts into \"Ads\" and \"Content\" arrays based on whether or not they have 'rw_adversiting_position' meta-data \n foreach( $posts as $post ) {\n $position = get_post_meta( $post-&gt;ID, 'rw_adversiting_position', true );\n\n if( ! empty( $position ) )\n $ad_posts[ intval( $position ) ] = $post;\n else\n $content_posts[] = $post; \n }\n\n // Sort the ads from smallest position index to greatest such that re-insertion properly factors in all ads\n ksort( $ad_posts );\n\n // Add the ads back into the content at their specified positions\n foreach( $ad_posts as $position =&gt; $ad ) {\n array_splice( $content_posts, $position, 0, array( $ad ) );\n }\n\n // If $return is true, return the resulting array. Otherwise replace the original $posts array with it.\n if( $return )\n return $content_posts;\n else\n $posts = $content_posts;\n}\n</code></pre>\n\n<blockquote>\n <h3>DISCLAIMER</h3>\n \n <p>In the example above, I specify a function parameter <code>&amp;$posts</code> which instructs PHP to use a <a href=\"http://php.net/manual/en/language.references.pass.php\" rel=\"nofollow noreferrer\"><em>pass-by-reference</a> evaluation strategy</em> for the argument passed to the function as <code>$posts</code>. This means that instead of referring to a locally-scoped copy of the data passed as the first argument, the <code>$posts</code> variable will refer to the data <em>at it's original place in memory</em>.</p>\n \n <p>Here I've used this mechanism to provide the (default) option to directly re-arrange an array of post objects without needing to handle a return value. The function itself merely sorting an array, I choose to pass the array argument by reference in order to provide behavior more consistent with <a href=\"http://php.net/manual/en/array.sorting.php\" rel=\"nofollow noreferrer\">all 12 of PHP's array sorting functions</a>.</p>\n \n <p>As <a href=\"https://wordpress.stackexchange.com/users/45169/andrei-gheorghiu\">@Andrei Gheorghiu</a> points out in the comments, passing by reference can produce unexpected results if you're unfamiliar with the practice. In such a scenario you may wish to steer clear of it which can be done by setting the <code>$return</code> argument in the example to <code>true</code>, or to be completely safe <a href=\"https://wordpress.stackexchange.com/questions/210493#answer-210876\">remove the option entirely as Andrei has</a>.</p>\n</blockquote>\n\n<p>In your template:</p>\n\n<pre><code>// [...]\n$normal_query = new WP_Query( $normal_args );\n\nwpse_210493_apply_advertising_position( $normal_query-&gt;posts );\n\nif ( $normal_query-&gt;have_posts() ) {\n// [...]\n</code></pre>\n\n<p>I haven't tested that code - it's just for illustrative purposes.</p>\n\n<p>Alternately, using a second query to retrieve the ads alone might work a little better.</p>\n" }, { "answer_id": 210876, "author": "tao", "author_id": 45169, "author_profile": "https://wordpress.stackexchange.com/users/45169", "pm_score": 2, "selected": false, "text": "<p>This is a revised version of <a href=\"https://wordpress.stackexchange.com/a/210613/45169\">bosco's</a> answer which <strong>does answer the question</strong> but adds too much flexibility by allowing direct modification of query properties, that I personally consider bad practice.</p>\n\n<pre><code>function wpse_210493_apply_advertising_position( $posts ) {\n $ad_posts = array();\n $content_posts = array();\n\n // Seperate $posts into \"Ads\" and \"Content\" arrays based on whether or not they have 'rw_adversiting_position' meta-data \n foreach( $posts as $post ) {\n $position = get_post_meta( $post-&gt;ID, 'rw_adversiting_position', true );\n\n if( ! empty( $position ) )\n $ad_posts[ intval( $position ) ] = $post;\n else\n $content_posts[] = $post; \n }\n\n // Sort the ads from smallest position index to greatest such that re-insertion properly factors in all ads\n ksort( $ad_posts );\n\n // Add the ads back into the content at their specified positions\n foreach( $ad_posts as $position =&gt; $ad ) {\n array_splice( $content_posts, $position, 0, array( $ad ) );\n }\n\n return $content_posts;\n}\n</code></pre>\n\n<p>After running the filter, we check to see if any posts were returned and if so, we use them in a <code>foreach</code> that outputs our result:</p>\n\n<pre><code>$normal_query = new WP_Query( $normal_args );\n\n$filtered_posts = wpse_210493_apply_advertising_position( $normal_query-&gt;posts );\n\nif ( count($filtered_posts) ) :\n foreach ($filtered_posts as $post) :\n setup_postdata($post);\n /* run any functions available in WP loop here \n * (the_title(), the_content(), etc...)\n *\n */\n endforeach;\n wp_reset_postdata();\nendif;\n</code></pre>\n" } ]
2015/12/02
[ "https://wordpress.stackexchange.com/questions/210493", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16412/" ]
I have this piece of code: ``` $normal_args = array( 'order' => 'desc', 'ignore_sticky_posts' => 1, 'meta_query' => array( array( 'key' => 'rw_show_at_position', 'value' => '1', 'compare' => '=' ) ), 'post__not_in' => $prev_post_ids, 'post_status' => 'publish', 'posts_per_page' => get_option( 'column_right' ), 'post_type' => array( 'opinion', 'especiales', 'clasificados', 'portadadeldia', 'anunciantes', 'post', 'pages', 'esp-publicitarios' ) ); $normal_query = new WP_Query( $normal_args ); $i = 0; if ( $normal_query->have_posts() ) { while ( $normal_query->have_posts() ) { $normal_query->the_post(); ?> <?php echo $i . ' ==> '; ?> <?php if ( get_post_type( $post->ID ) == 'esp-publicitarios' ) { $adv_pos = rwmb_meta( 'rw_adversiting_position', 'type=select', $post->ID ); echo $adv_pos . EOL; } else { ?> // do something here <?php } $i ++; } } ``` And I want to reorder items based on `post_type` and a metakey `rw_adversiting_position` and then display them normally. Right now I am getting this result: ``` 0 ==> 183034 ==> 9 1 ==> 183033 ==> 6 2 ==> 183032 ==> 3 3 ==> 183002 ==> 4 ==> 182973 ==> 5 ==> 182971 ==> 6 ==> 182969 ==> 7 ==> 182999 ==> 8 ==> 182997 ==> 9 ==> 182995 ==> 10 ==> 182962 ==> 11 ==> 182948 ==> ``` That's because only the 0, 1 and 2 are `esp-publicitarios` post types. The number at the right 9, 6 and 3 is the position where I should push the item so having this info the result should be something like: ``` 0 ==> 183002 ==> 1 ==> 182973 ==> 2 ==> 182971 ==> 2 ==> 183032 ==> 3 4 ==> 182969 ==> 5 ==> 182999 ==> 6 ==> 183033 ==> 6 7 ==> 182997 ==> 8 ==> 182995 ==> 9 ==> 183034 ==> 9 10 ==> 182962 ==> 11 ==> 182948 ==> ``` Can any give me some ideas to achieve this? **UPDATE 1** I did found [this](http://kuttler.eu/code/order-posts-in-a-wp_query-manually/) but I am not sure how to apply it. **UPDATE 2** This is the PHP code for achieve the sorting, `sort_position` could be `rw_adversiting_position`: ``` $arr = [ '183034' => [ 'sort_position' => 9 ], '183033' => [ 'sort_position' => 5 ], '183032' => [ 'sort_position' => 3 ], '183002' => [ ], '182973' => [ ], '182971' => [ ], '182969' => [ ], '182999' => [ ], '182997' => [ ], '182995' => [ ], '182962' => [ ], '182948' => [ ] ]; $count = count( $arr ); $has_sortorder = [ ]; $no_sortorder = [ ]; krsort( $arr ); foreach ( $arr as $key => $val ) { if ( isset( $val['sort_position'] ) ) { $has_sortorder[ $val['sort_position'] ] = [ $key, $val ]; } else { $no_sortorder[] = [ $key, $val ]; } } $out = [ ]; for ( $i = 0; $i < $count; $i ++ ) { if ( isset( $has_sortorder[ $i ] ) ) { $out[ $has_sortorder[ $i ][0] ] = $has_sortorder[ $i ][1]; } else { $element = array_shift( $no_sortorder ); $out[ $element[0] ] = $element[1]; } } var_dump( $out ); ``` I just need to know how to apply this to WP\_Query before get the result, any? **UPDATE 3** Here is a snippet of `var_export($normal_query->posts)` as you can see there is no meta-key so I can order based on values of a meta, then how? ``` $var = array( 0 => WP_Post::__set_state( array( 'ID' => 183034, 'post_author' => '4', 'post_date' => '2015-12-01 16:44:35', 'post_date_gmt' => '2015-12-01 21:14:35', 'post_content' => '', 'post_title' => 'Espacio Pub 3', 'post_excerpt' => '', 'post_status' => 'publish', 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_password' => '', 'post_name' => 'espacio-pub-3', 'to_ping' => '', 'pinged' => '', 'post_modified' => '2015-12-01 16:54:38', 'post_modified_gmt' => '2015-12-01 21:24:38', 'post_content_filtered' => '', 'post_parent' => 0, 'guid' => 'http://elclarinweb.local/?post_type=esp-publicitarios&p=183034', 'menu_order' => 0, 'post_type' => 'esp-publicitarios', 'post_mime_type' => '', 'comment_count' => '0', 'filter' => 'raw', ) ), 1 => WP_Post::__set_state( array( 'ID' => 183033, 'post_author' => '4', 'post_date' => '2015-12-01 16:44:13', 'post_date_gmt' => '2015-12-01 21:14:13', 'post_content' => '', 'post_title' => 'Espacio Pub 2', 'post_excerpt' => '', 'post_status' => 'publish', 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_password' => '', 'post_name' => '183033', 'to_ping' => '', 'pinged' => '', 'post_modified' => '2015-12-01 16:44:21', 'post_modified_gmt' => '2015-12-01 21:14:21', 'post_content_filtered' => '', 'post_parent' => 0, 'guid' => 'http://elclarinweb.local/?post_type=esp-publicitarios&p=183033', 'menu_order' => 0, 'post_type' => 'esp-publicitarios', 'post_mime_type' => '', 'comment_count' => '0', 'filter' => 'raw', ) ), 2 => WP_Post::__set_state( array( 'ID' => 183032, 'post_author' => '4', 'post_date' => '2015-12-01 15:53:56', 'post_date_gmt' => '2015-12-01 20:23:56', 'post_content' => '', 'post_title' => 'Publicidad 1', 'post_excerpt' => '', 'post_status' => 'publish', 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_password' => '', 'post_name' => 'publicidad-1', 'to_ping' => '', 'pinged' => '', 'post_modified' => '2015-12-01 15:53:56', 'post_modified_gmt' => '2015-12-01 20:23:56', 'post_content_filtered' => '', 'post_parent' => 0, 'guid' => 'http://elclarinweb.local/?post_type=esp-publicitarios&p=183032', 'menu_order' => 0, 'post_type' => 'esp-publicitarios', 'post_mime_type' => '', 'comment_count' => '0', 'filter' => 'raw', ) ), 3 => WP_Post::__set_state( array( 'ID' => 183002, 'post_author' => '7', 'post_date' => '2015-11-22 00:08:00', 'post_date_gmt' => '2015-11-22 04:38:00', 'post_content' => 'Borrón y cuenta nueva es lo que han hecho los Bravos de Margarita en este comienzo de la segunda parte de la campaña, en la que ayer sumaron su cuarto triunfo seguido, al vencer a los Tiburones de La Guaira 5 carreras por 3. Margarita, que ganó dos de tres ante los escualos en la semana, madrugó al dominicano Alexis Candelario, quien llegó a dicha cita como el mejor lanzador del campeonato. Los artilleros isleños fabricaron cuatro de sus cinco carreras en las primeras dos entradas, catapultados por un doble impulsor de dos de Eliézer Alfonzo. “No importa quién esté en la lomita contraria, siempre que los muchachos crean en ellos mismos, estos van a ser los resultados”, señaló el dirigente Henry Blanco. Bravos se haría presente en el marcador una vez más en el sexto con doble remolcador del jardinero Junior Sosa y aguantaría un intento de remontada de los litoralenses en la parte final para sellar el lauro. “La mentalidad que tenemos es no pensar en la primera parte, hay que salir a ganar”, indicó Alfonzo, quien cerró el cotejo de 5-2 con un par de impulsadas y ahora acumula cinco rayitas traídas al plato en los últimos dos desafíos. “Estaba bastante perdido cuando comenzó la temporada, pero he hecho el ajuste necesario”.', 'post_title' => 'Ahora Bravos es puntero de la LVBP', 'post_excerpt' => 'Las curiosidades del nuevo sistema de puntos del torneo coloca al antiguo colero de puntero', 'post_status' => 'publish', 'comment_status' => 'open', 'ping_status' => 'open', 'post_password' => '', 'post_name' => 'ahora-bravos-es-puntero-de-la-lvbp', 'to_ping' => '', 'pinged' => '', 'post_modified' => '2015-11-22 00:08:00', 'post_modified_gmt' => '2015-11-22 04:38:00', 'post_content_filtered' => '', 'post_parent' => 0, 'guid' => 'http://elclarinweb.local/?p=183002', 'menu_order' => 0, 'post_type' => 'post', 'post_mime_type' => '', 'comment_count' => '0', 'filter' => 'raw' ) ) ); ``` **UPDATE 4** @bosco I have made some minors changes to your code and now it looks as follow: ``` function wpse_210493_apply_advertising_position( &$posts, $return = false ) { $ad_posts = array(); // Seperate $posts into "Ads" and "Content" arrays based on whether or not they have 'rw_adversiting_position' meta-data foreach ( $posts as $post ) { $position = intval( get_post_meta( $post->ID, 'rw_adversiting_position', true ) ); $post_date = $post->post_date; $post_modified = $post->post_modified; if ( ! empty( $position ) ) { if ( ! empty ( $ad_posts ) ) { if ( $post_date > $ad_posts[ $position ]->post_date || $post_modified > $ad_posts[ $position ]->post_modified ) { $ad_posts[ $position ] = $post; } } else { $ad_posts[ $position ] = $post; } } else { $content_posts[] = $post; } } // Sort the ads from smallest position index to greatest such that re-insertion properly factors in all ads ksort( $ad_posts ); // Add the ads back into the content at their specified positions foreach ( $ad_posts as $position => $ad ) { array_splice( $content_posts, $position, 0, array( $ad ) ); } // If $return is true, return the resulting array. Otherwise replace the original $posts array with it. if ( $return ) { return $content_posts; } else { $posts = $content_posts; } } ``` If I debug this on the template I get the following output: ``` echo '<pre> BEFORE'; echo count($normal_query->posts); echo '</pre>'; wpse_210493_apply_advertising_position( $normal_query->posts ); echo '<pre> AFTER'; echo count($normal_query->posts); echo '</pre>'; // Output BEFORE25 AFTER23 ``` The AFTER is the right value but the loop is using the BEFORE and is adding to empty elements on the loop, why? See [this pic](http://content.screencast.com/users/ReynierPM/folders/Snagit/media/52f01187-79a5-4363-a8d1-e8c1decd5490/12.04.2015-22.01.png) for more info.
You could use the [Metadata API](https://codex.wordpress.org/Metadata_API) to retrieve the `rw_advertising_position` metadata for each post, seperate the ads from the content, and then re-insert the ads at the proper locations: ``` /** * Extracts from an array posts with positional metadata and re-inserts them at the proper * indices. See https://wordpress.stackexchange.com/questions/210493 **/ function wpse_210493_apply_advertising_position( &$posts, $return = false ) { $ad_posts = array(); $content_posts = array(); // Seperate $posts into "Ads" and "Content" arrays based on whether or not they have 'rw_adversiting_position' meta-data foreach( $posts as $post ) { $position = get_post_meta( $post->ID, 'rw_adversiting_position', true ); if( ! empty( $position ) ) $ad_posts[ intval( $position ) ] = $post; else $content_posts[] = $post; } // Sort the ads from smallest position index to greatest such that re-insertion properly factors in all ads ksort( $ad_posts ); // Add the ads back into the content at their specified positions foreach( $ad_posts as $position => $ad ) { array_splice( $content_posts, $position, 0, array( $ad ) ); } // If $return is true, return the resulting array. Otherwise replace the original $posts array with it. if( $return ) return $content_posts; else $posts = $content_posts; } ``` > > ### DISCLAIMER > > > In the example above, I specify a function parameter `&$posts` which instructs PHP to use a [*pass-by-reference*](http://php.net/manual/en/language.references.pass.php) evaluation strategy for the argument passed to the function as `$posts`. This means that instead of referring to a locally-scoped copy of the data passed as the first argument, the `$posts` variable will refer to the data *at it's original place in memory*. > > > Here I've used this mechanism to provide the (default) option to directly re-arrange an array of post objects without needing to handle a return value. The function itself merely sorting an array, I choose to pass the array argument by reference in order to provide behavior more consistent with [all 12 of PHP's array sorting functions](http://php.net/manual/en/array.sorting.php). > > > As [@Andrei Gheorghiu](https://wordpress.stackexchange.com/users/45169/andrei-gheorghiu) points out in the comments, passing by reference can produce unexpected results if you're unfamiliar with the practice. In such a scenario you may wish to steer clear of it which can be done by setting the `$return` argument in the example to `true`, or to be completely safe [remove the option entirely as Andrei has](https://wordpress.stackexchange.com/questions/210493#answer-210876). > > > In your template: ``` // [...] $normal_query = new WP_Query( $normal_args ); wpse_210493_apply_advertising_position( $normal_query->posts ); if ( $normal_query->have_posts() ) { // [...] ``` I haven't tested that code - it's just for illustrative purposes. Alternately, using a second query to retrieve the ads alone might work a little better.
210,496
<p>I want to prepend a hashtag (#) in front of the tags on my post pages in Wordpress using jQuery. This code is not working:</p> <pre><code>$('div.tags a').prepend('#'); </code></pre> <p>This is the php:</p> <pre><code>&lt;div class="tags"&gt; &lt;?php the_tags( ' ', ' ', '' ); ?&gt; &lt;/div&gt; </code></pre> <p>I don't want the "#" to be part of the the stored tag, just added for display purposes. Thank you. </p>
[ { "answer_id": 210511, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>Using JS is not really the best possible solution as it can be disabled on client side. You can also use PHP like regular expressions and DOM to alter the links, but I really think the most reliable way to achive this is to rebuild the list throught the <a href=\"https://developer.wordpress.org/reference/hooks/term_links-taxonomy/\" rel=\"nofollow\"><code>term_link-post_tag</code> filter</a> which is located inside the <a href=\"https://developer.wordpress.org/reference/functions/get_the_term_list/\" rel=\"nofollow\"><code>get_the_term_list()</code> function</a> which is used by <a href=\"https://developer.wordpress.org/reference/functions/get_the_tag_list/\" rel=\"nofollow\"><code>get_the_tag_list</code></a> which in turn is used by <a href=\"https://developer.wordpress.org/reference/functions/the_tags/\" rel=\"nofollow\"><code>the_tags()</code></a>.</p>\n\n<p>The following is untested, but you can try something like this</p>\n\n<pre><code>add_filter( 'term_link-post_tag', function ( $links )\n{\n // Return if $links are empty\n if ( empty( $links ) )\n return $links;\n\n // Reset $links to an empty array\n unset ( $links );\n $links = [];\n\n // Get the current post ID\n $id = get_the_ID();\n // Get all the tags attached to the post\n $taxonomy = 'post_tag';\n $terms = get_the_terms( $id, $taxonomy );\n\n // Make double sure we have tags\n if ( !$terms )\n return $links; \n\n // Loop through the tags and build the links\n foreach ( $terms as $term ) {\n $link = get_term_link( $term, $taxonomy );\n\n // Here we add our hastag, so we get #Tag Name with link\n $links[] = '&lt;a href=\"' . esc_url( $link ) . '\" rel=\"tag\"&gt;#' . $term-&gt;name . '&lt;/a&gt;';\n }\n\n return $links;\n});\n</code></pre>\n" }, { "answer_id": 210712, "author": "Zenneson", "author_id": 69541, "author_profile": "https://wordpress.stackexchange.com/users/69541", "pm_score": 1, "selected": true, "text": "<p>I didn't want to edit the tags themselves, I just wanted to add the \"#\" for visual purposes. </p>\n\n<p>I decided to add this to the CSS to solve the problem:</p>\n\n<pre><code>.tags a::before {\n content: '#';\n}\n</code></pre>\n\n<p>Thanks for your time and input. </p>\n" } ]
2015/12/02
[ "https://wordpress.stackexchange.com/questions/210496", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69541/" ]
I want to prepend a hashtag (#) in front of the tags on my post pages in Wordpress using jQuery. This code is not working: ``` $('div.tags a').prepend('#'); ``` This is the php: ``` <div class="tags"> <?php the_tags( ' ', ' ', '' ); ?> </div> ``` I don't want the "#" to be part of the the stored tag, just added for display purposes. Thank you.
I didn't want to edit the tags themselves, I just wanted to add the "#" for visual purposes. I decided to add this to the CSS to solve the problem: ``` .tags a::before { content: '#'; } ``` Thanks for your time and input.
210,505
<p>The below will return the other post in the same category but it will also return the current post too. </p> <p>Is there a way to exclude the current post from the query?</p> <pre><code>$args = array( 'post_type' =&gt; 'custom_post_type', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'custom_taxo', 'field' =&gt; 'term_id', 'terms' =&gt; array(1,2,5), 'operator' =&gt; 'IN' ) ) ); $query = new WP_Query( $args ); </code></pre>
[ { "answer_id": 210513, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>Simply add</p>\n\n<pre><code>'post__not_in' =&gt; [get_queried_object_id()],\n</code></pre>\n\n<p>to your array of query arguments. <code>get_queried_object_id()</code> will return the post ID of the currently viewed single post, and <code>post__not_in</code> will skip the posts whos ID's was passed as an array to the parameter</p>\n" }, { "answer_id": 356006, "author": "NJENGAH", "author_id": 67761, "author_profile": "https://wordpress.stackexchange.com/users/67761", "pm_score": 0, "selected": false, "text": "<p>You can use <code>post__not_in</code> with the <code>get_the_ID</code> of the post in this case your code should be like this : </p>\n\n<pre><code> $args = array(\n 'post_type' =&gt; 'custom_post_type',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'custom_taxo',\n 'field' =&gt; 'term_id',\n 'terms' =&gt; array(1,2,5),\n 'operator' =&gt; 'IN'\n )\n ),\n 'post__not_in' =&gt; array (get_the_ID()), \n\n );\n\n $query = new WP_Query( $args );\n</code></pre>\n\n<p><strong>Note:</strong> The value has to be an array <code>'post__not_in' =&gt; array (get_the_ID())</code></p>\n" } ]
2015/12/02
[ "https://wordpress.stackexchange.com/questions/210505", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54374/" ]
The below will return the other post in the same category but it will also return the current post too. Is there a way to exclude the current post from the query? ``` $args = array( 'post_type' => 'custom_post_type', 'tax_query' => array( array( 'taxonomy' => 'custom_taxo', 'field' => 'term_id', 'terms' => array(1,2,5), 'operator' => 'IN' ) ) ); $query = new WP_Query( $args ); ```
Simply add ``` 'post__not_in' => [get_queried_object_id()], ``` to your array of query arguments. `get_queried_object_id()` will return the post ID of the currently viewed single post, and `post__not_in` will skip the posts whos ID's was passed as an array to the parameter
210,518
<p>Is that possible to get current post ID without passing in shortcode as parameter. Like [related-post] I want to get the post ID in which post this shortcode will use.</p> <pre><code>add_shortcode( 'related-article', 'related_article_title' ); function related_article_title( $atts ) { $post_id = get_the_ID(); echo $post_id; ob_start(); $query = new WP_Query( array( 'post_type' =&gt; 'post', 'posts_per_page' =&gt; 1, 'order' =&gt; 'DESC', ) ); if ( $query-&gt;have_posts() ) { ?&gt; &lt;div class="menu-row"&gt; &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; Leggi anche: &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;?php endwhile; wp_reset_postdata(); ?&gt; &lt;/div&gt; &lt;?php $myvariable = ob_get_clean(); return $myvariable; } } </code></pre>
[ { "answer_id": 263938, "author": "Erenor Paz", "author_id": 90143, "author_profile": "https://wordpress.stackexchange.com/users/90143", "pm_score": 2, "selected": false, "text": "<p>Just as @gorakh-shrestha was trying, using <code>global $post</code> and then <code>$post-&gt;ID</code>, is a good way to proceed, even inside a shortcode</p>\n" }, { "answer_id": 329047, "author": "Vasim Shaikh", "author_id": 87704, "author_profile": "https://wordpress.stackexchange.com/users/87704", "pm_score": 3, "selected": false, "text": "<pre><code>add_shortcode( 'related-article', 'related_article_title' );\nfunction related_article_title( $atts ) {\n global $post;\n echo $post-&gt;ID; // currently viewing post id\n ob_start();\n $query = new WP_Query( array(\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; 1,\n 'order' =&gt; 'DESC',\n )\n );\n if ( $query-&gt;have_posts() ) { ?&gt;\n &lt;div class=\"menu-row\"&gt;\n &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt;\n Leggi anche: &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;\n &lt;?php endwhile; wp_reset_postdata(); ?&gt;\n &lt;/div&gt;\n &lt;?php $myvariable = ob_get_clean();\n return $myvariable;\n}\n}\n</code></pre>\n" } ]
2015/12/02
[ "https://wordpress.stackexchange.com/questions/210518", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80519/" ]
Is that possible to get current post ID without passing in shortcode as parameter. Like [related-post] I want to get the post ID in which post this shortcode will use. ``` add_shortcode( 'related-article', 'related_article_title' ); function related_article_title( $atts ) { $post_id = get_the_ID(); echo $post_id; ob_start(); $query = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => 1, 'order' => 'DESC', ) ); if ( $query->have_posts() ) { ?> <div class="menu-row"> <?php while ( $query->have_posts() ) : $query->the_post(); ?> Leggi anche: <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <?php endwhile; wp_reset_postdata(); ?> </div> <?php $myvariable = ob_get_clean(); return $myvariable; } } ```
``` add_shortcode( 'related-article', 'related_article_title' ); function related_article_title( $atts ) { global $post; echo $post->ID; // currently viewing post id ob_start(); $query = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => 1, 'order' => 'DESC', ) ); if ( $query->have_posts() ) { ?> <div class="menu-row"> <?php while ( $query->have_posts() ) : $query->the_post(); ?> Leggi anche: <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <?php endwhile; wp_reset_postdata(); ?> </div> <?php $myvariable = ob_get_clean(); return $myvariable; } } ```
210,520
<p>I am getting too frustrated while creating new home page using template in Storefront theme. <a href="https://wordpress.org/themes/storefront/" rel="nofollow">https://wordpress.org/themes/storefront/</a>.</p> <p>With the help of this <a href="https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/" rel="nofollow">https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/</a> i tried bt not getting success.. anyone can tell me how can i do this without plug-in..</p> <p>I want to change home page , and want to show my custom template home page. – </p> <p><strong>Template Script</strong></p> <pre><code>&lt;?php /** * Template name: Homepage My Custom * * @package storefront */ get_header(); ?&gt; &lt;div id="primary" class="content-area"&gt; &lt;main id="main" class="site-main" role="main"&gt; **My Custom Home Template** &lt;/main&gt;&lt;!-- #main --&gt; &lt;/div&gt;&lt;!-- #primary --&gt; &lt;?php get_footer(); ?&gt; </code></pre>
[ { "answer_id": 210532, "author": "Envision eCommerce", "author_id": 84031, "author_profile": "https://wordpress.stackexchange.com/users/84031", "pm_score": 0, "selected": false, "text": "<p>First create a new page in theme directory</p>\n\n<p>example <code>template-newhomepage.php</code> (Copy of <code>template-homepage.php</code>)</p>\n\n<p>Change theme name to</p>\n\n<pre><code>Template name: New Homepage\n</code></pre>\n\n<p>Next step is to Change: </p>\n\n<pre><code>do_action( 'homepage' );\n</code></pre>\n\n<p>to</p>\n\n<pre><code>do_action( 'homepagenew' );\n</code></pre>\n\n<p>For create homepagenew hook in hook.php</p>\n\n<p>Follow directory path:</p>\n\n<pre><code>/wp-content/themes/storefront/inc/structure\n</code></pre>\n\n<p>add this code under homepage hook:</p>\n\n<pre><code>add_action( 'homepagenew', 'storefront_homepagenew_content', 10 );\nadd_action( 'homepagenew', 'storefront_product_categories', 20 );\nadd_action( 'homepagenew', 'storefront_recent_products', 30 );\nadd_action( 'homepagenew', 'storefront_featured_products', 40 );\nadd_action( 'homepagenew', 'storefront_popular_products', 50 );\nadd_action( 'homepagenew', 'storefront_on_sale_products', 60 );\n</code></pre>\n\n<p>Next thing we have to do is add below code in template-tag.php in same directory:</p>\n\n<pre><code>if ( ! function_exists( 'storefront_homepagenew_content' ) ) {\n/**\n * Display homepage content\n\n* Hooked into the `homepage` action in the homepage template\n\n* @since 1.0.0\n * @return void\n */\nfunction storefront_homepagenew_content() {\n\nwhile ( have_posts() ) : the_post();\n get_template_part( 'content', 'newhomepage' );\n\nendwhile; \n// end of the loop.\n\n}\n}\n</code></pre>\n\n<p>Now Create a Content-newhomepage.php file replica of content-homepage.php in theme directory</p>\n\n<pre><code>/wp-content/themes/storefront/\n</code></pre>\n\n<p>Now you can create a New homepage in WordPress admin and assign template \"New Homepage\" to this page.</p>\n" }, { "answer_id": 210543, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": true, "text": "<p>First step in modifying a theme, is <a href=\"https://codex.wordpress.org/Child_Themes#How_to_Create_a_Child_Theme\" rel=\"nofollow\">creating a child theme</a>.</p>\n\n<p>Now that you have a theme that is basically the same as the original, you can simply copy files of the original theme that you want to modify into exactly the same relative location as in the original theme and modify them to whatever you need. In your specific case, after locating the page template for the home page and copying it you can just modify the code in it and there is no need to create a new one.</p>\n" } ]
2015/12/02
[ "https://wordpress.stackexchange.com/questions/210520", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25404/" ]
I am getting too frustrated while creating new home page using template in Storefront theme. <https://wordpress.org/themes/storefront/>. With the help of this <https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/> i tried bt not getting success.. anyone can tell me how can i do this without plug-in.. I want to change home page , and want to show my custom template home page. – **Template Script** ``` <?php /** * Template name: Homepage My Custom * * @package storefront */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> **My Custom Home Template** </main><!-- #main --> </div><!-- #primary --> <?php get_footer(); ?> ```
First step in modifying a theme, is [creating a child theme](https://codex.wordpress.org/Child_Themes#How_to_Create_a_Child_Theme). Now that you have a theme that is basically the same as the original, you can simply copy files of the original theme that you want to modify into exactly the same relative location as in the original theme and modify them to whatever you need. In your specific case, after locating the page template for the home page and copying it you can just modify the code in it and there is no need to create a new one.
210,534
<p>i has create galley in post as: <code>[gallery columns="6" link="file" ids="156,113,99,67,103,102"]</code></p> <p>Now, how to show list image in <code>[gallery columns="6" link="file" ids="156,113,99,67,103,102"]</code> in to index as:</p> <pre><code>&lt;a href="#" title=""&gt;&lt;img src="link image in gallery"&gt; ..... &lt;a href="#" title=""&gt;&lt;img src="link image in gallery"&gt; </code></pre> <p>Any idea give me!</p> <p>Thanks</p>
[ { "answer_id": 210532, "author": "Envision eCommerce", "author_id": 84031, "author_profile": "https://wordpress.stackexchange.com/users/84031", "pm_score": 0, "selected": false, "text": "<p>First create a new page in theme directory</p>\n\n<p>example <code>template-newhomepage.php</code> (Copy of <code>template-homepage.php</code>)</p>\n\n<p>Change theme name to</p>\n\n<pre><code>Template name: New Homepage\n</code></pre>\n\n<p>Next step is to Change: </p>\n\n<pre><code>do_action( 'homepage' );\n</code></pre>\n\n<p>to</p>\n\n<pre><code>do_action( 'homepagenew' );\n</code></pre>\n\n<p>For create homepagenew hook in hook.php</p>\n\n<p>Follow directory path:</p>\n\n<pre><code>/wp-content/themes/storefront/inc/structure\n</code></pre>\n\n<p>add this code under homepage hook:</p>\n\n<pre><code>add_action( 'homepagenew', 'storefront_homepagenew_content', 10 );\nadd_action( 'homepagenew', 'storefront_product_categories', 20 );\nadd_action( 'homepagenew', 'storefront_recent_products', 30 );\nadd_action( 'homepagenew', 'storefront_featured_products', 40 );\nadd_action( 'homepagenew', 'storefront_popular_products', 50 );\nadd_action( 'homepagenew', 'storefront_on_sale_products', 60 );\n</code></pre>\n\n<p>Next thing we have to do is add below code in template-tag.php in same directory:</p>\n\n<pre><code>if ( ! function_exists( 'storefront_homepagenew_content' ) ) {\n/**\n * Display homepage content\n\n* Hooked into the `homepage` action in the homepage template\n\n* @since 1.0.0\n * @return void\n */\nfunction storefront_homepagenew_content() {\n\nwhile ( have_posts() ) : the_post();\n get_template_part( 'content', 'newhomepage' );\n\nendwhile; \n// end of the loop.\n\n}\n}\n</code></pre>\n\n<p>Now Create a Content-newhomepage.php file replica of content-homepage.php in theme directory</p>\n\n<pre><code>/wp-content/themes/storefront/\n</code></pre>\n\n<p>Now you can create a New homepage in WordPress admin and assign template \"New Homepage\" to this page.</p>\n" }, { "answer_id": 210543, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": true, "text": "<p>First step in modifying a theme, is <a href=\"https://codex.wordpress.org/Child_Themes#How_to_Create_a_Child_Theme\" rel=\"nofollow\">creating a child theme</a>.</p>\n\n<p>Now that you have a theme that is basically the same as the original, you can simply copy files of the original theme that you want to modify into exactly the same relative location as in the original theme and modify them to whatever you need. In your specific case, after locating the page template for the home page and copying it you can just modify the code in it and there is no need to create a new one.</p>\n" } ]
2015/12/02
[ "https://wordpress.stackexchange.com/questions/210534", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65359/" ]
i has create galley in post as: `[gallery columns="6" link="file" ids="156,113,99,67,103,102"]` Now, how to show list image in `[gallery columns="6" link="file" ids="156,113,99,67,103,102"]` in to index as: ``` <a href="#" title=""><img src="link image in gallery"> ..... <a href="#" title=""><img src="link image in gallery"> ``` Any idea give me! Thanks
First step in modifying a theme, is [creating a child theme](https://codex.wordpress.org/Child_Themes#How_to_Create_a_Child_Theme). Now that you have a theme that is basically the same as the original, you can simply copy files of the original theme that you want to modify into exactly the same relative location as in the original theme and modify them to whatever you need. In your specific case, after locating the page template for the home page and copying it you can just modify the code in it and there is no need to create a new one.
210,551
<p>I'm trying to do is the following. <strong>If the excerpt length is shorter than 30 charakters</strong>, than do..</p> <pre><code>&lt;?php if ( get_the_excerpt() &lt;= 30 AND has_post_thumbnail() ) : ?&gt; &lt;div&gt;&lt;/div&gt; &lt;?php else : ?&gt; &lt;div&gt;&lt;/div&gt; &lt;?php endif; ?&gt; </code></pre> <p>But it seems like that's not the way to read out the length. I was playing around with some definitions that I found like:</p> <pre><code>&lt;?php if ( the_excerpt() &lt;= 30 AND has_post_thumbnail() ) : ?&gt; &lt;?php if ( $count($the_excerpt) &lt;= 30 AND has_post_thumbnail() ) : ?&gt; &lt;?php if ( excerpt_length($count) &lt;= 30 AND has_post_thumbnail() ) : ?&gt; </code></pre> <p>..but I'm helpless. So..you kind guys. Any idea?</p>
[ { "answer_id": 210557, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": true, "text": "<p>This is more PHP as you need to use <a href=\"http://php.net/manual/en/function.str-word-count.php\" rel=\"nofollow\"><code>str_word_count()</code></a> to count the amount of words in the excerpt. Just note, to be safe, if you allow any tags in the excerpt, you would want to use <code>strip_tags()</code> to remove html tags to avoid incorrect word counts.</p>\n\n<h2>EXAMPLE:</h2>\n\n<pre><code>echo str_word_count( strip_tags( get_the_excerpt() ) );\n</code></pre>\n\n<p>If you need to display wordcount on the front end, you can also wrap the above in <code>number_format_i18n()</code> to return the integer value according to locale set</p>\n\n<pre><code>echo number_format_i18n( str_word_count( strip_tags( get_the_excerpt() ) ) );\n</code></pre>\n" }, { "answer_id": 210558, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 0, "selected": false, "text": "<p>The answer is basic PHP:</p>\n\n<pre><code>$exc = get_the_excerpt();\n// var_dump($exc);\n$exc = strlen($exc);\n// var_dump($exc);\nif ( $exc &lt;= 30 AND has_post_thumbnail() ) {\n\n} else {\n\n}\n</code></pre>\n\n<p>You need to count the string's characters before trying to compare the string to an integer. PHP's <code>strlen()</code> does that. </p>\n\n<p>However, you also misunderstand a few things...</p>\n\n<pre><code>if ( the_excerpt() &lt;= 30 AND has_post_thumbnail() ) :\n</code></pre>\n\n<p><code>the_excerpt()</code> prints content. All that will do is <code>echo</code> the excerpt to the screen. There is no data \"captured\" to operate on.</p>\n\n<pre><code>if ( $count($the_excerpt) &lt;= 30 AND has_post_thumbnail() )\n</code></pre>\n\n<p>The leading <code>$</code> makes this a function. While you can create a <a href=\"http://php.net/manual/en/functions.variable-functions.php\" rel=\"nofollow noreferrer\">variable function</a> in PHP, I doubt you have. Without the <code>$</code>, <code>count()</code> will just return <code>1</code> with a string. It doesn't count the characters.</p>\n\n<pre><code>if ( excerpt_length($count) &lt;= 30 AND has_post_thumbnail() )\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/excerpt_length\" rel=\"nofollow noreferrer\"><code>excerpt_length</code></a> doesn't work that way. In fact, it isn't even a function. It is a filter. </p>\n\n<p>I'd suggest that if you are going to be hacking your site, get familiar with the <a href=\"http://php.net/docs.php\" rel=\"nofollow noreferrer\">PHP Docs</a> and the <a href=\"https://codex.wordpress.org/\" rel=\"nofollow noreferrer\">Codex</a>, and stop trying to guess at functions, infer from other languages, or just make things up. <a href=\"https://wordpress.stackexchange.com/a/103644/21376\">This</a> may be helpful too.</p>\n" } ]
2015/12/02
[ "https://wordpress.stackexchange.com/questions/210551", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77898/" ]
I'm trying to do is the following. **If the excerpt length is shorter than 30 charakters**, than do.. ``` <?php if ( get_the_excerpt() <= 30 AND has_post_thumbnail() ) : ?> <div></div> <?php else : ?> <div></div> <?php endif; ?> ``` But it seems like that's not the way to read out the length. I was playing around with some definitions that I found like: ``` <?php if ( the_excerpt() <= 30 AND has_post_thumbnail() ) : ?> <?php if ( $count($the_excerpt) <= 30 AND has_post_thumbnail() ) : ?> <?php if ( excerpt_length($count) <= 30 AND has_post_thumbnail() ) : ?> ``` ..but I'm helpless. So..you kind guys. Any idea?
This is more PHP as you need to use [`str_word_count()`](http://php.net/manual/en/function.str-word-count.php) to count the amount of words in the excerpt. Just note, to be safe, if you allow any tags in the excerpt, you would want to use `strip_tags()` to remove html tags to avoid incorrect word counts. EXAMPLE: -------- ``` echo str_word_count( strip_tags( get_the_excerpt() ) ); ``` If you need to display wordcount on the front end, you can also wrap the above in `number_format_i18n()` to return the integer value according to locale set ``` echo number_format_i18n( str_word_count( strip_tags( get_the_excerpt() ) ) ); ```
210,564
<p>I am following a tutorial that will hopefully allow me to insert templates straight from my plugin into WordPress. I am using the template_include filter, I can't get my head around how the whole filter process works. </p> <p>Here is the code.</p> <pre><code>public function view_project_template( $template ) { global $post; if (!isset( $this-&gt;templates[get_post_meta($post-&gt;ID, '_wp_page_template', true ) ] ) ) { return $template; } $file = plugin_dir_path(__FILE__) . get_post_meta( $post-&gt;ID, '_wp_page_template', true ); if ( file_exists( $file ) ) { return $file; } else { echo $file; } return $template; } </code></pre> <p>I understand the filter takes one argument $template but then at the end when I return $template I haven't affected it in anyway. How does this then affect the filter? Would be great to get this cleared up.</p>
[ { "answer_id": 210566, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 0, "selected": false, "text": "<p>You have no effect, because you haven't done anything with <code>$template</code> - not that you have to. It doesn't really affect the filter anyway, I would rather say, the filter gives you the possibility to intervene in the process. On the other hand, if <code>$file</code> exists and you <code>return</code> it, then you should see an effect - provided that <code>$file</code> is different from <code>$template</code>.</p>\n" }, { "answer_id": 210568, "author": "Sabari", "author_id": 31757, "author_profile": "https://wordpress.stackexchange.com/users/31757", "pm_score": 0, "selected": false, "text": "<p>What the filter - <code>apply_filters($tag, $value)</code> do is passes the '<strong>value</strong>' argument to each of the functions '<strong>hooked</strong>' (using <code>add_filter</code>) into the specified filter 'tag'. Each function performs some processing on the value and returns a modified value to be passed to the next function in the sequence.</p>\n\n<p>In your case, you are checking whether your template file exists and if it exists you are returning the <code>file</code>. In that case, you are telling WordPress that load your file instead of original template that WordPress is trying to load. WordPress by default loads the template that is outputted from the filter</p>\n" }, { "answer_id": 210576, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>You are using the filter wrongly, that is why you might not get the desired result. Lets first look at the <code>template_include</code> filter which you can check out in <a href=\"https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-includes/template-loader.php#L74\" rel=\"nofollow\"><code>wp-includes/template-loader.php</code></a> (<em>current version 4.3.1</em>)</p>\n\n<pre><code>44 if ( defined('WP_USE_THEMES') &amp;&amp; WP_USE_THEMES ) :\n45 $template = false;\n46 if ( is_404() &amp;&amp; $template = get_404_template() ) :\n47 elseif ( is_search() &amp;&amp; $template = get_search_template() ) :\n48 elseif ( is_front_page() &amp;&amp; $template = get_front_page_template() ) :\n49 elseif ( is_home() &amp;&amp; $template = get_home_template() ) :\n50 elseif ( is_post_type_archive() &amp;&amp; $template = get_post_type_archive_template() ) :\n51 elseif ( is_tax() &amp;&amp; $template = get_taxonomy_template() ) :\n52 elseif ( is_attachment() &amp;&amp; $template = get_attachment_template() ) :\n53 remove_filter('the_content', 'prepend_attachment');\n54 elseif ( is_single() &amp;&amp; $template = get_single_template() ) :\n55 elseif ( is_page() &amp;&amp; $template = get_page_template() ) :\n56 elseif ( is_singular() &amp;&amp; $template = get_singular_template() ) :\n57 elseif ( is_category() &amp;&amp; $template = get_category_template() ) :\n58 elseif ( is_tag() &amp;&amp; $template = get_tag_template() ) :\n59 elseif ( is_author() &amp;&amp; $template = get_author_template() ) :\n60 elseif ( is_date() &amp;&amp; $template = get_date_template() ) :\n61 elseif ( is_archive() &amp;&amp; $template = get_archive_template() ) :\n62 elseif ( is_comments_popup() &amp;&amp; $template = get_comments_popup_template() ) :\n63 elseif ( is_paged() &amp;&amp; $template = get_paged_template() ) :\n64 else :\n65 $template = get_index_template();\n66 endif;\n67 /**\n68 * Filter the path of the current template before including it.\n69 *\n70 * @since 3.0.0\n71 *\n72 * @param string $template The path of the template to include.\n73 */\n74 if ( $template = apply_filters( 'template_include', $template ) )\n75 include( $template );\n76 return;\n77 endif;\n</code></pre>\n\n<p>Because we are on a real page, the value of <code>$template</code> that is passed to the filter in line 74 will be the value of <a href=\"https://developer.wordpress.org/reference/functions/get_page_template/\" rel=\"nofollow\"><code>get_page_template()</code></a> (<em>because <code>is_page()</code> returned true</em>) which value is filterable through the <a href=\"https://developer.wordpress.org/reference/hooks/type_template/\" rel=\"nofollow\"><code>{$type}_template</code></a> filter located in <a href=\"https://developer.wordpress.org/reference/functions/get_query_template/\" rel=\"nofollow\"><code>get_query_template()</code></a> (<em>which is used by <code>get_page_template()</code></em>).</p>\n\n<p>OK, so we can tackle this two ways, either use <code>template_include</code> or <code>page_template</code> (<em>remember the <code>{$type}_template</code> filter, here <code>$type === 'page'</code></em>). If you are going to use <code>template_include</code>, you will need to use the <code>is_page()</code> condition to target real pages only. If you use the <code>page_template</code> filter (<em>which is more desired here</em>), you do not need this check.</p>\n\n<p>I'm not really sure what the following line is suppose to do, and most probably why your filter never reach beyond this section</p>\n\n<pre><code>if (!isset( $this-&gt;templates[get_post_meta($post-&gt;ID, '_wp_page_template', true ) ] ) ) {\n return $template;\n}\n</code></pre>\n\n<p>Because you are dealing with true pages, <code>_wp_page_template</code> should always have a value, so all we really need to do is to check if our template exists inside the template and then returning it</p>\n\n<p>You can try the following:</p>\n\n<pre><code>public function view_project_template( $template ) {\n\n // Use get_queried_object_id() to get page id, much more reliable\n $current_page_id = get_queried_object_id();\n\n $page_template = get_post_meta( \n $current_page_id, // Current page ID\n '_wp_page_template', // Meta key holding the page template value\n true // Return single value\n );\n\n /**\n * You can add extra protection and make sure $page_template has a value\n * although it should not be really necessary\n */\n // if ( !$page_template )\n // return $template;\n\n $file = plugin_dir_path(__FILE__) . $page_template;\n\n // Check if file exists, if not, return $template\n if ( !file_exists( $file ) ) \n return $template;\n\n // If we reached this part, we can include our new template\n return $template = $file; // Or you can simply do return $file;\n\n}\n</code></pre>\n\n<p>You should then hook your method as follow (<em>as this is inside a class</em>)</p>\n\n<pre><code>add_filter( 'page_template', [$this, 'view_project_template'] );\n</code></pre>\n\n<p>Just a small thought here, why not make the method private as you would not want it available outside of the class</p>\n" } ]
2015/12/02
[ "https://wordpress.stackexchange.com/questions/210564", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64115/" ]
I am following a tutorial that will hopefully allow me to insert templates straight from my plugin into WordPress. I am using the template\_include filter, I can't get my head around how the whole filter process works. Here is the code. ``` public function view_project_template( $template ) { global $post; if (!isset( $this->templates[get_post_meta($post->ID, '_wp_page_template', true ) ] ) ) { return $template; } $file = plugin_dir_path(__FILE__) . get_post_meta( $post->ID, '_wp_page_template', true ); if ( file_exists( $file ) ) { return $file; } else { echo $file; } return $template; } ``` I understand the filter takes one argument $template but then at the end when I return $template I haven't affected it in anyway. How does this then affect the filter? Would be great to get this cleared up.
You are using the filter wrongly, that is why you might not get the desired result. Lets first look at the `template_include` filter which you can check out in [`wp-includes/template-loader.php`](https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-includes/template-loader.php#L74) (*current version 4.3.1*) ``` 44 if ( defined('WP_USE_THEMES') && WP_USE_THEMES ) : 45 $template = false; 46 if ( is_404() && $template = get_404_template() ) : 47 elseif ( is_search() && $template = get_search_template() ) : 48 elseif ( is_front_page() && $template = get_front_page_template() ) : 49 elseif ( is_home() && $template = get_home_template() ) : 50 elseif ( is_post_type_archive() && $template = get_post_type_archive_template() ) : 51 elseif ( is_tax() && $template = get_taxonomy_template() ) : 52 elseif ( is_attachment() && $template = get_attachment_template() ) : 53 remove_filter('the_content', 'prepend_attachment'); 54 elseif ( is_single() && $template = get_single_template() ) : 55 elseif ( is_page() && $template = get_page_template() ) : 56 elseif ( is_singular() && $template = get_singular_template() ) : 57 elseif ( is_category() && $template = get_category_template() ) : 58 elseif ( is_tag() && $template = get_tag_template() ) : 59 elseif ( is_author() && $template = get_author_template() ) : 60 elseif ( is_date() && $template = get_date_template() ) : 61 elseif ( is_archive() && $template = get_archive_template() ) : 62 elseif ( is_comments_popup() && $template = get_comments_popup_template() ) : 63 elseif ( is_paged() && $template = get_paged_template() ) : 64 else : 65 $template = get_index_template(); 66 endif; 67 /** 68 * Filter the path of the current template before including it. 69 * 70 * @since 3.0.0 71 * 72 * @param string $template The path of the template to include. 73 */ 74 if ( $template = apply_filters( 'template_include', $template ) ) 75 include( $template ); 76 return; 77 endif; ``` Because we are on a real page, the value of `$template` that is passed to the filter in line 74 will be the value of [`get_page_template()`](https://developer.wordpress.org/reference/functions/get_page_template/) (*because `is_page()` returned true*) which value is filterable through the [`{$type}_template`](https://developer.wordpress.org/reference/hooks/type_template/) filter located in [`get_query_template()`](https://developer.wordpress.org/reference/functions/get_query_template/) (*which is used by `get_page_template()`*). OK, so we can tackle this two ways, either use `template_include` or `page_template` (*remember the `{$type}_template` filter, here `$type === 'page'`*). If you are going to use `template_include`, you will need to use the `is_page()` condition to target real pages only. If you use the `page_template` filter (*which is more desired here*), you do not need this check. I'm not really sure what the following line is suppose to do, and most probably why your filter never reach beyond this section ``` if (!isset( $this->templates[get_post_meta($post->ID, '_wp_page_template', true ) ] ) ) { return $template; } ``` Because you are dealing with true pages, `_wp_page_template` should always have a value, so all we really need to do is to check if our template exists inside the template and then returning it You can try the following: ``` public function view_project_template( $template ) { // Use get_queried_object_id() to get page id, much more reliable $current_page_id = get_queried_object_id(); $page_template = get_post_meta( $current_page_id, // Current page ID '_wp_page_template', // Meta key holding the page template value true // Return single value ); /** * You can add extra protection and make sure $page_template has a value * although it should not be really necessary */ // if ( !$page_template ) // return $template; $file = plugin_dir_path(__FILE__) . $page_template; // Check if file exists, if not, return $template if ( !file_exists( $file ) ) return $template; // If we reached this part, we can include our new template return $template = $file; // Or you can simply do return $file; } ``` You should then hook your method as follow (*as this is inside a class*) ``` add_filter( 'page_template', [$this, 'view_project_template'] ); ``` Just a small thought here, why not make the method private as you would not want it available outside of the class
210,578
<p>I have a private theme and I want to deploy new theme versions of it as smoothly as possible.</p> <p>I've heard about:</p> <ul> <li>hosting the theme somewhere like wp-updates.com</li> <li>using plugins to update theme automatically directly from a repository (using plugins like <a href="https://github.com/afragen/github-updater" rel="nofollow">https://github.com/afragen/github-updater</a> or <a href="https://wordpress.org/plugins/revisr/" rel="nofollow">https://wordpress.org/plugins/revisr/</a>)</li> <li>uploading zip archive with a newer version of the theme (it requires activating another theme, deleting previous theme version and uploading a new zip archive with the new theme version).</li> </ul> <p>So I came up with an idea to update theme using each time a zip file with a different name (for example <code>my-awesome-theme-0.1.zip</code> and so on).</p> <p>Is it a good idea or am I missing something?</p>
[ { "answer_id": 210649, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 0, "selected": false, "text": "<p>With direct access to server <em>typically</em> people just upload/sync file changes on top. However this leaves possibility that someone is visiting the site just as theme is in the process of being updated.</p>\n\n<p>The way to do it with minimum interruption:</p>\n\n<ol>\n<li>Upload new version to a separate directory (e.g. <code>theme-name-update</code>).</li>\n<li>Rename old theme directory ( <code>theme-name</code> > <code>theme-name-old</code>).</li>\n<li>Rename update directory (<code>theme-name-update</code> > <code>theme-name</code>).</li>\n</ol>\n\n<p>When you do steps 2 &amp; 3 in one CLI command (or have a script for it) that makes the swap <em>extremely</em> fast and unlikely to cause issues.</p>\n" }, { "answer_id": 211129, "author": "chestozo", "author_id": 84627, "author_profile": "https://wordpress.stackexchange.com/users/84627", "pm_score": 2, "selected": true, "text": "<p>I've been using this approach for private theme updates using versioned archives and it seems to work for me pretty well.\nNo problems found yet.\nSo I guess for private themes - it is a good one.</p>\n\n<p>Also I came up with a script for building versioned theme archive like this:</p>\n\n<pre><code>#!/bin/bash\n\necho \"======================\";\necho \"BUILDING THEME ARCHIVE\";\necho \"======================\";\n\n# Get version from style.css and CHANGES.md and compare them.\n# If they are the same - proceed.\n\nVER_STYLE=\"$(cat style.css | grep 'Version: ' | perl -pe \"s/Version: (.*)\\\\n/\\1/g\")\"\nVER_CHANGES=\"$(head -n 1 CHANGES.md | xargs | awk '{ print $2 }')\"\n\nif [ $VER_STYLE != $VER_CHANGES ]; then\n printf \"\\e[31;5;21m%s\\e[0m\\n\" \"BUILD FAILED\"\n echo \"Your version in style.css ($VER_STYLE) differs from version in CHANGES.md ($VER_CHANGES).\";\n echo \"Please actualize.\";\n exit 1;\nfi\n\n# Theme archive build.\n# Also create a new tag for builded version.\n\nbuild_name=\"my-theme_$VER_STYLE.zip\"\n\necho \"Building $build_name ...\";\n\nzip -r -q \\\n --exclude=.* \\\n --exclude=sass/* \\\n --exclude=*/.DS_Store \\\n --exclude=*.md \\\n --exclude=*.zip \\\n --exclude=*.sh \\\n $build_name . &amp;&amp; git tag $VER_STYLE &amp;&amp; git push --tags &amp;&amp; printf \"\\e[32;5;21m%s\\e[0m\\n\" \"done\" ;\n\nexit 0;\n</code></pre>\n" } ]
2015/12/02
[ "https://wordpress.stackexchange.com/questions/210578", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84627/" ]
I have a private theme and I want to deploy new theme versions of it as smoothly as possible. I've heard about: * hosting the theme somewhere like wp-updates.com * using plugins to update theme automatically directly from a repository (using plugins like <https://github.com/afragen/github-updater> or <https://wordpress.org/plugins/revisr/>) * uploading zip archive with a newer version of the theme (it requires activating another theme, deleting previous theme version and uploading a new zip archive with the new theme version). So I came up with an idea to update theme using each time a zip file with a different name (for example `my-awesome-theme-0.1.zip` and so on). Is it a good idea or am I missing something?
I've been using this approach for private theme updates using versioned archives and it seems to work for me pretty well. No problems found yet. So I guess for private themes - it is a good one. Also I came up with a script for building versioned theme archive like this: ``` #!/bin/bash echo "======================"; echo "BUILDING THEME ARCHIVE"; echo "======================"; # Get version from style.css and CHANGES.md and compare them. # If they are the same - proceed. VER_STYLE="$(cat style.css | grep 'Version: ' | perl -pe "s/Version: (.*)\\n/\1/g")" VER_CHANGES="$(head -n 1 CHANGES.md | xargs | awk '{ print $2 }')" if [ $VER_STYLE != $VER_CHANGES ]; then printf "\e[31;5;21m%s\e[0m\n" "BUILD FAILED" echo "Your version in style.css ($VER_STYLE) differs from version in CHANGES.md ($VER_CHANGES)."; echo "Please actualize."; exit 1; fi # Theme archive build. # Also create a new tag for builded version. build_name="my-theme_$VER_STYLE.zip" echo "Building $build_name ..."; zip -r -q \ --exclude=.* \ --exclude=sass/* \ --exclude=*/.DS_Store \ --exclude=*.md \ --exclude=*.zip \ --exclude=*.sh \ $build_name . && git tag $VER_STYLE && git push --tags && printf "\e[32;5;21m%s\e[0m\n" "done" ; exit 0; ```
210,597
<p>Using v2 of the REST API, I'm wanting to query some posts by <strong>multiple</strong> meta keys. With v1 I was able to format the url like <code>&amp;filter[meta_value][month]=12&amp;[meta_value][year]=2015</code> and it worked (after exposing the meta values to the API).</p> <p>Now with v2, I can only get this to work by using the methods listed on this GitHub thread: <a href="https://github.com/WP-API/WP-API/issues/1599#issuecomment-161166805">https://github.com/WP-API/WP-API/issues/1599#issuecomment-161166805</a></p> <p>Basically, added the meta fields using the <code>rest_query_vars</code> filter like:</p> <p><code>add_filter( 'rest_query_vars', 'flux_allow_meta_query' ); function flux_allow_meta_query( $valid_vars ) { $valid_vars = array_merge( $valid_vars, array( 'meta_key', 'meta_value', 'meta_compare' ) ); return $valid_vars; }</code></p> <p>With that, I can filter by <strong>one</strong> meta key using a url like <code>wp-json/wp/v2/posts?filter[meta_key]=test&amp;filter[meta_value]=on</code>.</p> <p>However, it sounds like the only way to filter on multiple meta keys is to write a custom filter. Could someone point me in the right direction of doing that?</p>
[ { "answer_id": 212113, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 4, "selected": true, "text": "<p>Adding a <a href=\"http://v2.wp-api.org/extending/adding/\" rel=\"noreferrer\">custom endpoint</a> is pretty straightforward.</p>\n\n<p>I also modified the url to look more like</p>\n\n<p><code>http://example.com/wp-json/namespace/v2/posts?filter[meta_value][month]=12&amp;filter[meta_value][year]=2015</code></p>\n\n<pre><code>function wp_json_namespace_v2__init()\n{\n\n // create json-api endpoint\n\n add_action('rest_api_init', function () {\n\n // http://example.com/wp-json/namespace/v2/posts?filter[meta_value][month]=12&amp;filter[meta_value][year]=2015\n\n register_rest_route('namespace/v2', '/posts', array (\n 'methods' =&gt; 'GET',\n 'callback' =&gt; 'wp_json_namespace_v2__posts',\n 'permission_callback' =&gt; function (WP_REST_Request $request) {\n return true;\n }\n ));\n });\n\n // handle the request\n\n function wp_json_namespace_v2__posts($request)\n {\n // json-api params\n\n $parameters = $request-&gt;get_query_params();\n\n // default search args\n\n $args = array(\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n 'numberposts' =&gt; -1,\n // limit to only ids\n // 'fields' =&gt; 'ids', \n );\n\n // check the query and add valid items\n\n if (isset($parameters['filter']['meta_value'])) {\n foreach ($parameters['filter']['meta_value'] as $key =&gt; $value) {\n switch ($key) {\n\n case 'month':\n if (is_numeric($value))\n $args['monthnum'] = $value;\n break;\n\n case 'year':\n if (is_numeric($value))\n $args['year'] = $value;\n break;\n }\n }\n }\n\n // run query\n\n $posts = get_posts($args);\n\n // return results\n\n $data = array(\n 'success' =&gt; true,\n 'request' =&gt; $parameters,\n 'count' =&gt; count($posts),\n 'posts' =&gt; $posts,\n );\n\n return new WP_REST_Response($data, 200);\n }\n\n flush_rewrite_rules(true); // FIXME: &lt;------- DONT LEAVE ME HERE\n}\n\nadd_action('init', 'wp_json_namespace_v2__init');\n</code></pre>\n" }, { "answer_id": 355964, "author": "ricardorios", "author_id": 124577, "author_profile": "https://wordpress.stackexchange.com/users/124577", "pm_score": 0, "selected": false, "text": "<p>I know this question was solved, but this plugin is out and solved my problem \n<a href=\"https://wordpress.org/plugins/wp-rest-filter/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-rest-filter/</a></p>\n" } ]
2015/12/02
[ "https://wordpress.stackexchange.com/questions/210597", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25756/" ]
Using v2 of the REST API, I'm wanting to query some posts by **multiple** meta keys. With v1 I was able to format the url like `&filter[meta_value][month]=12&[meta_value][year]=2015` and it worked (after exposing the meta values to the API). Now with v2, I can only get this to work by using the methods listed on this GitHub thread: <https://github.com/WP-API/WP-API/issues/1599#issuecomment-161166805> Basically, added the meta fields using the `rest_query_vars` filter like: `add_filter( 'rest_query_vars', 'flux_allow_meta_query' ); function flux_allow_meta_query( $valid_vars ) { $valid_vars = array_merge( $valid_vars, array( 'meta_key', 'meta_value', 'meta_compare' ) ); return $valid_vars; }` With that, I can filter by **one** meta key using a url like `wp-json/wp/v2/posts?filter[meta_key]=test&filter[meta_value]=on`. However, it sounds like the only way to filter on multiple meta keys is to write a custom filter. Could someone point me in the right direction of doing that?
Adding a [custom endpoint](http://v2.wp-api.org/extending/adding/) is pretty straightforward. I also modified the url to look more like `http://example.com/wp-json/namespace/v2/posts?filter[meta_value][month]=12&filter[meta_value][year]=2015` ``` function wp_json_namespace_v2__init() { // create json-api endpoint add_action('rest_api_init', function () { // http://example.com/wp-json/namespace/v2/posts?filter[meta_value][month]=12&filter[meta_value][year]=2015 register_rest_route('namespace/v2', '/posts', array ( 'methods' => 'GET', 'callback' => 'wp_json_namespace_v2__posts', 'permission_callback' => function (WP_REST_Request $request) { return true; } )); }); // handle the request function wp_json_namespace_v2__posts($request) { // json-api params $parameters = $request->get_query_params(); // default search args $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'numberposts' => -1, // limit to only ids // 'fields' => 'ids', ); // check the query and add valid items if (isset($parameters['filter']['meta_value'])) { foreach ($parameters['filter']['meta_value'] as $key => $value) { switch ($key) { case 'month': if (is_numeric($value)) $args['monthnum'] = $value; break; case 'year': if (is_numeric($value)) $args['year'] = $value; break; } } } // run query $posts = get_posts($args); // return results $data = array( 'success' => true, 'request' => $parameters, 'count' => count($posts), 'posts' => $posts, ); return new WP_REST_Response($data, 200); } flush_rewrite_rules(true); // FIXME: <------- DONT LEAVE ME HERE } add_action('init', 'wp_json_namespace_v2__init'); ```
210,604
<p>The output I am trying to achieve is this:</p> <pre><code>&lt;div class="row"&gt; &lt;div class="small-1 large-4 columns"&gt;&lt;a href="some link"&gt;&lt;img src="some image"&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="small-1 large-4 columns"&gt;&lt;a href="some link"&gt;&lt;img src="some image"&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="small-1 large-4 columns"&gt;&lt;a href="some link"&gt;&lt;img src="some image"&gt;&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="small-1 large-4 columns"&gt;&lt;a href="some link"&gt;&lt;img src="some image"&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="small-1 large-4 columns"&gt;&lt;a href="some link"&gt;&lt;img src="some image"&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="small-1 large-4 columns"&gt;&lt;a href="some link"&gt;&lt;img src="some image"&gt;&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="small-1 large-4 columns"&gt;&lt;a href="some link"&gt;&lt;img src="some image"&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="small-1 large-4 columns"&gt;&lt;a href="some link"&gt;&lt;img src="some image"&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="small-1 large-4 columns"&gt;&lt;a href="some link"&gt;&lt;img src="some image"&gt;&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>This is my PHP</p> <pre><code>&lt;?php $first_query = new WP_Query('cat=22&amp;posts_per_page=9'); ?&gt; &lt;?php while ($first_query-&gt;have_posts()) : $first_query-&gt;the_post(); ?&gt; &lt;?php if($first_query-&gt;current_post &amp;&amp; !($first_query-&gt;current_post % 3) ) : ?&gt; &lt;div class="row"&gt; &lt;?php endif; ?&gt; &lt;?php if($first_query-&gt;current_post &amp;&amp; !($first_query-&gt;current_post % 1) ) : ?&gt; &lt;div class="small-1 large-4 columns"&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;?php the_post_thumbnail('large'); ?&gt;&lt;/a&gt;&lt;/div&gt; &lt;?php endif; ?&gt; &lt;?php if($first_query-&gt;current_post &amp;&amp; !($first_query-&gt;current_post % 3) ) : ?&gt; &lt;/div&gt; &lt;?php endif; ?&gt; &lt;?php endwhile; // End the loop. ?&gt; </code></pre> <p>So basically I need a DIV with the class of row to enclose three divs with the class of small-1 large-4 columns. What I'm getting with the code shown in this post is </p>
[ { "answer_id": 210641, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>You could simplify things by using the <a href=\"http://php.net/manual/en/function.array-chunk.php\" rel=\"nofollow\"><code>array_chunk()</code></a> PHP function, to split an array into smaller chunks. Then you don't need to worry about opening and closing divs with some math tricks.</p>\n\n<p>Let's rewrite your code snippet and hopefully make it easier to work with:</p>\n\n<p>\n\n<pre><code>// Let's get all posts with thumbnail set in some category\n$args = [ \n 'cat' =&gt; 22,\n 'posts_per_page' =&gt; 9,\n 'meta_key' =&gt; '_thumbnail_id'\n];\n\n// Fetch posts\n$query = new WP_Query( $args );\n\nif( $query-&gt;have_posts() )\n{\n while ( $query-&gt;have_posts() )\n {\n $query-&gt;the_post(); \n\n // Collect all items into a temp array \n $tmp[] = sprintf( \n '&lt;div class=\"small-1 large-4 columns\"&gt;&lt;a href=\"%s\"&gt;%s&lt;/a&gt;&lt;/div&gt;',\n get_permalink(),\n get_the_post_thumbnail( get_the_ID(), 'large' )\n );\n } \n\n // Split the divs into rows of 3 items\n $rows = array_chunk( $tmp, 3 );\n\n // Housecleaning\n unset( $tmp );\n wp_reset_postdata();\n\n // Output the rows\n foreach( $rows as $row )\n printf( '&lt;div class=\"row\"&gt;%s&lt;/div&gt;', join( '', $row ) ); \n\n}\n</code></pre>\n\n<p><em>Look Ma, no math used here! ;-)</em></p>\n\n<p>Hopefully you can adjust this to your needs. </p>\n" }, { "answer_id": 210688, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>For the maths version ;) -</p>\n\n<p>Open and close the first/last row <em>outside</em> the loop, then you only have to worry about closing/opening rows every third post that isn't the last post.</p>\n\n<pre><code>echo '&lt;div class=\"row\"&gt;';\n\nwhile ( $query-&gt;have_posts() ){\n\n // output content for this post here\n\n if( 0 == ( $first_query-&gt;current_post + 1 ) % 3\n &amp;&amp; ( $first_query-&gt;current_post + 1 ) != $first_query-&gt;post_count ){\n echo '&lt;/div&gt;&lt;div class=\"row\"&gt;';\n }\n\n}\n\necho '&lt;/div&gt;';\n</code></pre>\n" } ]
2015/12/03
[ "https://wordpress.stackexchange.com/questions/210604", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84666/" ]
The output I am trying to achieve is this: ``` <div class="row"> <div class="small-1 large-4 columns"><a href="some link"><img src="some image"></a></div> <div class="small-1 large-4 columns"><a href="some link"><img src="some image"></a></div> <div class="small-1 large-4 columns"><a href="some link"><img src="some image"></a></div> </div> <div class="row"> <div class="small-1 large-4 columns"><a href="some link"><img src="some image"></a></div> <div class="small-1 large-4 columns"><a href="some link"><img src="some image"></a></div> <div class="small-1 large-4 columns"><a href="some link"><img src="some image"></a></div> </div> <div class="row"> <div class="small-1 large-4 columns"><a href="some link"><img src="some image"></a></div> <div class="small-1 large-4 columns"><a href="some link"><img src="some image"></a></div> <div class="small-1 large-4 columns"><a href="some link"><img src="some image"></a></div> </div> ``` This is my PHP ``` <?php $first_query = new WP_Query('cat=22&posts_per_page=9'); ?> <?php while ($first_query->have_posts()) : $first_query->the_post(); ?> <?php if($first_query->current_post && !($first_query->current_post % 3) ) : ?> <div class="row"> <?php endif; ?> <?php if($first_query->current_post && !($first_query->current_post % 1) ) : ?> <div class="small-1 large-4 columns"><a href="<?php the_permalink(); ?>"> <?php the_post_thumbnail('large'); ?></a></div> <?php endif; ?> <?php if($first_query->current_post && !($first_query->current_post % 3) ) : ?> </div> <?php endif; ?> <?php endwhile; // End the loop. ?> ``` So basically I need a DIV with the class of row to enclose three divs with the class of small-1 large-4 columns. What I'm getting with the code shown in this post is
You could simplify things by using the [`array_chunk()`](http://php.net/manual/en/function.array-chunk.php) PHP function, to split an array into smaller chunks. Then you don't need to worry about opening and closing divs with some math tricks. Let's rewrite your code snippet and hopefully make it easier to work with: ``` // Let's get all posts with thumbnail set in some category $args = [ 'cat' => 22, 'posts_per_page' => 9, 'meta_key' => '_thumbnail_id' ]; // Fetch posts $query = new WP_Query( $args ); if( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); // Collect all items into a temp array $tmp[] = sprintf( '<div class="small-1 large-4 columns"><a href="%s">%s</a></div>', get_permalink(), get_the_post_thumbnail( get_the_ID(), 'large' ) ); } // Split the divs into rows of 3 items $rows = array_chunk( $tmp, 3 ); // Housecleaning unset( $tmp ); wp_reset_postdata(); // Output the rows foreach( $rows as $row ) printf( '<div class="row">%s</div>', join( '', $row ) ); } ``` *Look Ma, no math used here! ;-)* Hopefully you can adjust this to your needs.
210,609
<p>I'm trying to create a post when a user registers using the code from here:</p> <p><a href="https://wordpress.stackexchange.com/questions/53328/create-posts-on-user-registration">Create posts on user registration</a></p> <p>The user registers and the post is created BUT the user firstname and user lastname is not working. Each time a post is created just with the title of "Bio"</p> <p>Here is my code: <pre><code> function create_new_user_posts($user_id){ // Get user ID for Post Title $user = get_user_by('id', $user_id); if (!$user_id>0) return; // Here we know the user has been created so to create a post we call wp_insert_post // Create post object $my_bio_post = array( 'post_title' => $user->user_firstname . " ". $user->user_lastname . 'bio', 'post_content' => '[li_profile id="author"]', 'post_status' => 'publish', 'post_author' => $user_id ); // Insert the post into the database wp_insert_post( $my_bio_post ); } add_action('user_register','create_new_user_posts'); </pre></code></p>
[ { "answer_id": 210641, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>You could simplify things by using the <a href=\"http://php.net/manual/en/function.array-chunk.php\" rel=\"nofollow\"><code>array_chunk()</code></a> PHP function, to split an array into smaller chunks. Then you don't need to worry about opening and closing divs with some math tricks.</p>\n\n<p>Let's rewrite your code snippet and hopefully make it easier to work with:</p>\n\n<p>\n\n<pre><code>// Let's get all posts with thumbnail set in some category\n$args = [ \n 'cat' =&gt; 22,\n 'posts_per_page' =&gt; 9,\n 'meta_key' =&gt; '_thumbnail_id'\n];\n\n// Fetch posts\n$query = new WP_Query( $args );\n\nif( $query-&gt;have_posts() )\n{\n while ( $query-&gt;have_posts() )\n {\n $query-&gt;the_post(); \n\n // Collect all items into a temp array \n $tmp[] = sprintf( \n '&lt;div class=\"small-1 large-4 columns\"&gt;&lt;a href=\"%s\"&gt;%s&lt;/a&gt;&lt;/div&gt;',\n get_permalink(),\n get_the_post_thumbnail( get_the_ID(), 'large' )\n );\n } \n\n // Split the divs into rows of 3 items\n $rows = array_chunk( $tmp, 3 );\n\n // Housecleaning\n unset( $tmp );\n wp_reset_postdata();\n\n // Output the rows\n foreach( $rows as $row )\n printf( '&lt;div class=\"row\"&gt;%s&lt;/div&gt;', join( '', $row ) ); \n\n}\n</code></pre>\n\n<p><em>Look Ma, no math used here! ;-)</em></p>\n\n<p>Hopefully you can adjust this to your needs. </p>\n" }, { "answer_id": 210688, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>For the maths version ;) -</p>\n\n<p>Open and close the first/last row <em>outside</em> the loop, then you only have to worry about closing/opening rows every third post that isn't the last post.</p>\n\n<pre><code>echo '&lt;div class=\"row\"&gt;';\n\nwhile ( $query-&gt;have_posts() ){\n\n // output content for this post here\n\n if( 0 == ( $first_query-&gt;current_post + 1 ) % 3\n &amp;&amp; ( $first_query-&gt;current_post + 1 ) != $first_query-&gt;post_count ){\n echo '&lt;/div&gt;&lt;div class=\"row\"&gt;';\n }\n\n}\n\necho '&lt;/div&gt;';\n</code></pre>\n" } ]
2015/12/03
[ "https://wordpress.stackexchange.com/questions/210609", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84671/" ]
I'm trying to create a post when a user registers using the code from here: [Create posts on user registration](https://wordpress.stackexchange.com/questions/53328/create-posts-on-user-registration) The user registers and the post is created BUT the user firstname and user lastname is not working. Each time a post is created just with the title of "Bio" Here is my code: ``` function create_new_user_posts($user_id){ // Get user ID for Post Title $user = get_user_by('id', $user_id); if (!$user_id>0) return; // Here we know the user has been created so to create a post we call wp_insert_post // Create post object $my_bio_post = array( 'post_title' => $user->user_firstname . " ". $user->user_lastname . 'bio', 'post_content' => '[li_profile id="author"]', 'post_status' => 'publish', 'post_author' => $user_id ); // Insert the post into the database wp_insert_post( $my_bio_post ); } add_action('user_register','create_new_user_posts'); ```
You could simplify things by using the [`array_chunk()`](http://php.net/manual/en/function.array-chunk.php) PHP function, to split an array into smaller chunks. Then you don't need to worry about opening and closing divs with some math tricks. Let's rewrite your code snippet and hopefully make it easier to work with: ``` // Let's get all posts with thumbnail set in some category $args = [ 'cat' => 22, 'posts_per_page' => 9, 'meta_key' => '_thumbnail_id' ]; // Fetch posts $query = new WP_Query( $args ); if( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); // Collect all items into a temp array $tmp[] = sprintf( '<div class="small-1 large-4 columns"><a href="%s">%s</a></div>', get_permalink(), get_the_post_thumbnail( get_the_ID(), 'large' ) ); } // Split the divs into rows of 3 items $rows = array_chunk( $tmp, 3 ); // Housecleaning unset( $tmp ); wp_reset_postdata(); // Output the rows foreach( $rows as $row ) printf( '<div class="row">%s</div>', join( '', $row ) ); } ``` *Look Ma, no math used here! ;-)* Hopefully you can adjust this to your needs.
210,639
<p>Is it possible to grab the custom post type post id just only from slug? </p> <p>As much i know we can get from id by using title. But there can be same title in a custom post type so as slugs are unique is it possible???</p>
[ { "answer_id": 210646, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 7, "selected": true, "text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/get_page_by_path/\" rel=\"noreferrer\"><code>get_page_by_path()</code></a> - don't let the name fool you, third argument is the post type:</p>\n<pre><code>if ( $post = get_page_by_path( 'the_slug', OBJECT, 'post_type' ) )\n $id = $post-&gt;ID;\nelse\n $id = 0;\n</code></pre>\n" }, { "answer_id": 210647, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": false, "text": "<p>If you wait a couple of days, and upgrade to <a href=\"https://codex.wordpress.org/Version_4.4\" rel=\"noreferrer\">Wordpress 4.4</a> which will be released the 8th of December (<em>AFAIK</em>), you can use the new <code>post_name__in</code> parameter in <code>WP_Query</code> which takes an array of slugs</p>\n\n<h2>EXAMPLE</h2>\n\n<p>If you need the complete post object</p>\n\n<pre><code>$args = [\n 'post_type' =&gt; 'my_custom_post_type',\n 'posts_per_page' =&gt; 1,\n 'post_name__in' =&gt; ['post-slug']\n];\n$q = get_posts( $args );\nvar_dump( $q );\n</code></pre>\n\n<p>If you only need the ID</p>\n\n<pre><code>$args = [\n 'post_type' =&gt; 'my_custom_post_type',\n 'posts_per_page' =&gt; 1,\n 'post_name__in' =&gt; ['post-slug'],\n 'fields' =&gt; 'ids' \n];\n$q = get_posts( $args );\nvar_dump( $q );\n</code></pre>\n" }, { "answer_id": 284917, "author": "Syclone", "author_id": 130856, "author_profile": "https://wordpress.stackexchange.com/users/130856", "pm_score": 3, "selected": false, "text": "<p>If you just want the post id this will do the trick in one line. </p>\n\n<pre><code>url_to_postid( site_url('the_slug') );\n</code></pre>\n" } ]
2015/12/03
[ "https://wordpress.stackexchange.com/questions/210639", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82119/" ]
Is it possible to grab the custom post type post id just only from slug? As much i know we can get from id by using title. But there can be same title in a custom post type so as slugs are unique is it possible???
You can use [`get_page_by_path()`](https://developer.wordpress.org/reference/functions/get_page_by_path/) - don't let the name fool you, third argument is the post type: ``` if ( $post = get_page_by_path( 'the_slug', OBJECT, 'post_type' ) ) $id = $post->ID; else $id = 0; ```
210,666
<p>I have this function:</p> <pre><code>function wpse_210493_apply_advertising_position( &amp;$posts, $return = false ) { $ad_posts = array(); $content_posts = array_filter( $posts, function ( $post ) { $position = get_post_meta( $post-&gt;ID, 'rw_adversiting_position', true ); if ( empty( $position ) ) { return true; } $ad_posts[ intval( $position ) ] = $post; return false; } ); $content_posts = array_values( $content_posts ); ksort( $ad_posts ); echo "sdfksfkjshdfsdf"; foreach ( $ad_posts as $position =&gt; $ad ) { array_splice( $content_posts, $position, 0, $ad ); } if ( $return ) { return $content_posts; } else { $posts = $content_posts; } } </code></pre> <p>I need to debug <code>$ad_posts</code> after the <code>ksort()</code> but output is not going to browser. I did test with the <code>echo</code> you see there and that text also is not going to browser as output. How do I debug the values properly?</p>
[ { "answer_id": 210668, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 5, "selected": true, "text": "<p>You can simply use <code>var_dump()</code> to do this. That is how I check values inside functions and filters. </p>\n\n<p>I have the following line of code in a file which I simply copy and paste where needed to dump the value of a variable</p>\n\n<pre><code>?&gt;&lt;pre&gt;&lt;?php var_dump( $variable_to_test ); ?&gt;&lt;/pre&gt;&lt;?php\n</code></pre>\n\n<p>The <code>pre</code> tags dump a nice readable array/object/string depending on the value. Inside your function you can just do </p>\n\n<pre><code>?&gt;&lt;pre&gt;&lt;?php var_dump($ad_posts); ?&gt;&lt;/pre&gt;&lt;?php \n</code></pre>\n\n<p>after <code>ksort( $ad_posts );</code>.</p>\n\n<p>Just make sure to call the function somewhere if it is not hooked to some kind of hook otherwise nothing will happen</p>\n" }, { "answer_id": 336410, "author": "Navidot", "author_id": 101910, "author_profile": "https://wordpress.stackexchange.com/users/101910", "pm_score": 2, "selected": false, "text": "<p>To debug these values you don't have to display them in browser. Rather then do:</p>\n\n<pre><code>error_log(your-variable-or-whatever);\n</code></pre>\n\n<p>And check your error log in <code>wp-content/debug.log</code>.</p>\n\n<p>To make it working you have to have <code>define( 'WP_DEBUG_LOG', true );</code> set in your <code>wp-config.php</code>.</p>\n\n<p>EDIT:\nAs @nmr pointed out, <code>define( 'WP_DEBUG', true );</code> is also required.</p>\n" }, { "answer_id": 336426, "author": "sMyles", "author_id": 51201, "author_profile": "https://wordpress.stackexchange.com/users/51201", "pm_score": 2, "selected": false, "text": "<p>The proper and correct way to do this would be using XDebug and some kind of IDE that supports it, while working on development locally.</p>\n\n<p>The easiest setup I can recommend would be using Local by Flywheel (free) for local development:\n<a href=\"https://localbyflywheel.com/\" rel=\"nofollow noreferrer\">https://localbyflywheel.com/</a></p>\n\n<p>Local has option under Utilities (for a site) to add XDebug configuration to PHPStorm, after clicking that button reopen the project in PHPStorm and you will see a debug configuration already setup for that site.</p>\n\n<p>PHPStorm EAP (eap was free previously) can be downloaded here (also has 30 day trial):\n<a href=\"https://blog.jetbrains.com/phpstorm/2019/04/phpstorm-2019-1-2-preview-191-7141-5/\" rel=\"nofollow noreferrer\">https://blog.jetbrains.com/phpstorm/2019/04/phpstorm-2019-1-2-preview-191-7141-5/</a></p>\n\n<p>Docs on setting up XDebug:\n<a href=\"https://www.jetbrains.com/help/phpstorm/debugging-with-phpstorm-ultimate-guide.html\" rel=\"nofollow noreferrer\">https://www.jetbrains.com/help/phpstorm/debugging-with-phpstorm-ultimate-guide.html</a></p>\n\n<p>You can then set a breakpoint in your code and inspect it using XDebug.</p>\n\n<p>The options above do work in a crunch, but the correct way to debug PHP is using an IDE and XDebug, and will save you TONS of time if you learn to do it the right way.</p>\n\n<p><strong>Using <code>error_log</code>:</strong></p>\n\n<p>To expand on others responses about <code>error_log</code> output, if it's an array or something that's not a string, it's best to use <code>print_r</code> and set return to <code>true</code>:</p>\n\n<pre><code>error_log( 'MY STUFF: ' . print_r( $something, true ) );\n</code></pre>\n" } ]
2015/12/03
[ "https://wordpress.stackexchange.com/questions/210666", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16412/" ]
I have this function: ``` function wpse_210493_apply_advertising_position( &$posts, $return = false ) { $ad_posts = array(); $content_posts = array_filter( $posts, function ( $post ) { $position = get_post_meta( $post->ID, 'rw_adversiting_position', true ); if ( empty( $position ) ) { return true; } $ad_posts[ intval( $position ) ] = $post; return false; } ); $content_posts = array_values( $content_posts ); ksort( $ad_posts ); echo "sdfksfkjshdfsdf"; foreach ( $ad_posts as $position => $ad ) { array_splice( $content_posts, $position, 0, $ad ); } if ( $return ) { return $content_posts; } else { $posts = $content_posts; } } ``` I need to debug `$ad_posts` after the `ksort()` but output is not going to browser. I did test with the `echo` you see there and that text also is not going to browser as output. How do I debug the values properly?
You can simply use `var_dump()` to do this. That is how I check values inside functions and filters. I have the following line of code in a file which I simply copy and paste where needed to dump the value of a variable ``` ?><pre><?php var_dump( $variable_to_test ); ?></pre><?php ``` The `pre` tags dump a nice readable array/object/string depending on the value. Inside your function you can just do ``` ?><pre><?php var_dump($ad_posts); ?></pre><?php ``` after `ksort( $ad_posts );`. Just make sure to call the function somewhere if it is not hooked to some kind of hook otherwise nothing will happen
210,667
<p>I have created a custom excerpt length in my functions.php, I would like to extend this function to increase the excerpt length of the first post in a loop.</p> <p><strong>My function at the moment:</strong></p> <pre><code>/* Change Excerpt length */ function custom_excerpt_length( $length ) { return 30; } </code></pre> <p><strong>Was thinking of something along these lines</strong></p> <pre><code>function new_excerpt_length($length) { global $post; if ($post-&gt; FIRST POST?) return 50; else return 20; } </code></pre> <p>Is there a way of getting post count from <strong>$post-></strong>?</p>
[ { "answer_id": 210668, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 5, "selected": true, "text": "<p>You can simply use <code>var_dump()</code> to do this. That is how I check values inside functions and filters. </p>\n\n<p>I have the following line of code in a file which I simply copy and paste where needed to dump the value of a variable</p>\n\n<pre><code>?&gt;&lt;pre&gt;&lt;?php var_dump( $variable_to_test ); ?&gt;&lt;/pre&gt;&lt;?php\n</code></pre>\n\n<p>The <code>pre</code> tags dump a nice readable array/object/string depending on the value. Inside your function you can just do </p>\n\n<pre><code>?&gt;&lt;pre&gt;&lt;?php var_dump($ad_posts); ?&gt;&lt;/pre&gt;&lt;?php \n</code></pre>\n\n<p>after <code>ksort( $ad_posts );</code>.</p>\n\n<p>Just make sure to call the function somewhere if it is not hooked to some kind of hook otherwise nothing will happen</p>\n" }, { "answer_id": 336410, "author": "Navidot", "author_id": 101910, "author_profile": "https://wordpress.stackexchange.com/users/101910", "pm_score": 2, "selected": false, "text": "<p>To debug these values you don't have to display them in browser. Rather then do:</p>\n\n<pre><code>error_log(your-variable-or-whatever);\n</code></pre>\n\n<p>And check your error log in <code>wp-content/debug.log</code>.</p>\n\n<p>To make it working you have to have <code>define( 'WP_DEBUG_LOG', true );</code> set in your <code>wp-config.php</code>.</p>\n\n<p>EDIT:\nAs @nmr pointed out, <code>define( 'WP_DEBUG', true );</code> is also required.</p>\n" }, { "answer_id": 336426, "author": "sMyles", "author_id": 51201, "author_profile": "https://wordpress.stackexchange.com/users/51201", "pm_score": 2, "selected": false, "text": "<p>The proper and correct way to do this would be using XDebug and some kind of IDE that supports it, while working on development locally.</p>\n\n<p>The easiest setup I can recommend would be using Local by Flywheel (free) for local development:\n<a href=\"https://localbyflywheel.com/\" rel=\"nofollow noreferrer\">https://localbyflywheel.com/</a></p>\n\n<p>Local has option under Utilities (for a site) to add XDebug configuration to PHPStorm, after clicking that button reopen the project in PHPStorm and you will see a debug configuration already setup for that site.</p>\n\n<p>PHPStorm EAP (eap was free previously) can be downloaded here (also has 30 day trial):\n<a href=\"https://blog.jetbrains.com/phpstorm/2019/04/phpstorm-2019-1-2-preview-191-7141-5/\" rel=\"nofollow noreferrer\">https://blog.jetbrains.com/phpstorm/2019/04/phpstorm-2019-1-2-preview-191-7141-5/</a></p>\n\n<p>Docs on setting up XDebug:\n<a href=\"https://www.jetbrains.com/help/phpstorm/debugging-with-phpstorm-ultimate-guide.html\" rel=\"nofollow noreferrer\">https://www.jetbrains.com/help/phpstorm/debugging-with-phpstorm-ultimate-guide.html</a></p>\n\n<p>You can then set a breakpoint in your code and inspect it using XDebug.</p>\n\n<p>The options above do work in a crunch, but the correct way to debug PHP is using an IDE and XDebug, and will save you TONS of time if you learn to do it the right way.</p>\n\n<p><strong>Using <code>error_log</code>:</strong></p>\n\n<p>To expand on others responses about <code>error_log</code> output, if it's an array or something that's not a string, it's best to use <code>print_r</code> and set return to <code>true</code>:</p>\n\n<pre><code>error_log( 'MY STUFF: ' . print_r( $something, true ) );\n</code></pre>\n" } ]
2015/12/03
[ "https://wordpress.stackexchange.com/questions/210667", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71177/" ]
I have created a custom excerpt length in my functions.php, I would like to extend this function to increase the excerpt length of the first post in a loop. **My function at the moment:** ``` /* Change Excerpt length */ function custom_excerpt_length( $length ) { return 30; } ``` **Was thinking of something along these lines** ``` function new_excerpt_length($length) { global $post; if ($post-> FIRST POST?) return 50; else return 20; } ``` Is there a way of getting post count from **$post->**?
You can simply use `var_dump()` to do this. That is how I check values inside functions and filters. I have the following line of code in a file which I simply copy and paste where needed to dump the value of a variable ``` ?><pre><?php var_dump( $variable_to_test ); ?></pre><?php ``` The `pre` tags dump a nice readable array/object/string depending on the value. Inside your function you can just do ``` ?><pre><?php var_dump($ad_posts); ?></pre><?php ``` after `ksort( $ad_posts );`. Just make sure to call the function somewhere if it is not hooked to some kind of hook otherwise nothing will happen
210,683
<p>I have a dynamic list of checkboxes that are showing on a user profile in the admin area (user-edit.php). A user should be able to select the checkboxes which will save their selections as an array in a usermeta field. Easy enough. However when I load the user profile after Updating the User, the boxes are not checked even though the options were saved in the usermeta field and the checkbox has a property of checked="checked". </p> <p>At first I was just using a basic in_array() to check if the checkbox value was in the array from the usermeta. If it was then I set checked="checked". This worked and showed in dev tools as showing checked="checked", however there was still no checkmark. Here's what that looked like:</p> <pre><code>$courseResults = DwgFunctions::get_all_courses(); $userWaivedModules = DwgFunctions::checkCourses('scorm_waived_courses',$user); foreach($courseResults as $course){ $courseListing.= '&lt;input type="checkbox" name="waivedCourses[]" value="'.$course-&gt;getCourseId().'" '.(in_array($course-&gt;getCourseId(),$userWaivedModules)?"checked=\"checked\"":"").'/&gt;'.$course-&gt;getTitle().'&lt;br /&gt;'; } </code></pre> <p>After doing some reading I discovered that WordPress likes to make us use the checked() function. Of course it just checks strings and I needed it to check against an array. So I used a handy function I found on the forums and now have this:</p> <pre><code> $courseResults = DwgFunctions::get_all_courses(); $userWaivedModules = DwgFunctions::checkCourses('scorm_waived_courses',$user); foreach($courseResults as $course){ $courseListing.= '&lt;input type="checkbox" name="waivedCourses[]" value="'.$course-&gt;getCourseId().'" '.DwgFunctions::dwg_checked($userWaivedModules,$course-&gt;getCourseId()).'/&gt;'.$course-&gt;getTitle().'&lt;br /&gt;'; } </code></pre> <p>And my deg_checked function looks like this:</p> <pre><code> function dwg_checked($haystack, $current){ if(is_array($haystack) &amp;&amp; in_array($current, $haystack)) { $current = $haystack = 1; } return checked($haystack, $current); } </code></pre> <p>Both ways the result is the same:</p> <pre><code>&lt;input type="checkbox" name="waivedCourses[]" value="1-555e1f4f86bd2"&gt;SC DDSN Family-Arranged Respite - An Overview for Families&lt;br&gt; &lt;input type="checkbox" name="waivedCourses[]" value="1-555e1f89ae931" checked="checked"&gt;Overview for Families - Quiz&lt;br&gt; &lt;input type="checkbox" name="waivedCourses[]" value="1-555e1f9d1d688" checked="checked"&gt;Overview for Families - Quiz&lt;br&gt; &lt;input type="checkbox" name="waivedCourses[]" value="1-555e20e3079ad" checked="checked"&gt;Overview for Families - Quiz&lt;br&gt; &lt;input type="checkbox" name="waivedCourses[]" value="FamilyModule_FinalQuizc0ea0981-8158-4077-b94a-6d182db566a3"&gt;FamilyModule_FinalQuiz&lt;br&gt; &lt;input type="checkbox" name="waivedCourses[]" value="FAMILYMODULE_QUIZ3ecc3d81-1281-4477-adb8-ac81ef96724a"&gt;FAMILYMODULE_QUIZ&lt;br&gt; &lt;input type="checkbox" name="waivedCourses[]" value="FamilyModule_TheFinalQuizad828150-f6da-4e19-b69c-5a78a74d412a"&gt;FamilyModule_FinalQuiz_2&lt;br&gt; </code></pre> <p>However it shows on the screen as: <a href="https://i.stack.imgur.com/yneXf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yneXf.png" alt="unchecked boxes"></a></p> <p>If I update the user as is (with some boxes showing checked="checked" however none actually showing a checkmark), it will clear my usermeta value completely.</p> <p>If I actually check the checkbox it will show the checkmark and also implement the css for input[type=checkbox]:checked:before , and will save the setting in the usermeta. Notice though that the css before pseudoclass is not implemented when the checked attribute is dynamically added. <a href="https://i.stack.imgur.com/nU5q8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nU5q8.png" alt="checked"></a></p> <pre><code>input[type=checkbox]:checked:before { content: '\f147'; margin: -3px 0 0 -4px; color: #1e8cbe; } </code></pre> <p>Any ideas what could be going on? Other places I have checkboxes that are working fine, however those are not using arrays (nor are they using the checked() function)</p>
[ { "answer_id": 210668, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 5, "selected": true, "text": "<p>You can simply use <code>var_dump()</code> to do this. That is how I check values inside functions and filters. </p>\n\n<p>I have the following line of code in a file which I simply copy and paste where needed to dump the value of a variable</p>\n\n<pre><code>?&gt;&lt;pre&gt;&lt;?php var_dump( $variable_to_test ); ?&gt;&lt;/pre&gt;&lt;?php\n</code></pre>\n\n<p>The <code>pre</code> tags dump a nice readable array/object/string depending on the value. Inside your function you can just do </p>\n\n<pre><code>?&gt;&lt;pre&gt;&lt;?php var_dump($ad_posts); ?&gt;&lt;/pre&gt;&lt;?php \n</code></pre>\n\n<p>after <code>ksort( $ad_posts );</code>.</p>\n\n<p>Just make sure to call the function somewhere if it is not hooked to some kind of hook otherwise nothing will happen</p>\n" }, { "answer_id": 336410, "author": "Navidot", "author_id": 101910, "author_profile": "https://wordpress.stackexchange.com/users/101910", "pm_score": 2, "selected": false, "text": "<p>To debug these values you don't have to display them in browser. Rather then do:</p>\n\n<pre><code>error_log(your-variable-or-whatever);\n</code></pre>\n\n<p>And check your error log in <code>wp-content/debug.log</code>.</p>\n\n<p>To make it working you have to have <code>define( 'WP_DEBUG_LOG', true );</code> set in your <code>wp-config.php</code>.</p>\n\n<p>EDIT:\nAs @nmr pointed out, <code>define( 'WP_DEBUG', true );</code> is also required.</p>\n" }, { "answer_id": 336426, "author": "sMyles", "author_id": 51201, "author_profile": "https://wordpress.stackexchange.com/users/51201", "pm_score": 2, "selected": false, "text": "<p>The proper and correct way to do this would be using XDebug and some kind of IDE that supports it, while working on development locally.</p>\n\n<p>The easiest setup I can recommend would be using Local by Flywheel (free) for local development:\n<a href=\"https://localbyflywheel.com/\" rel=\"nofollow noreferrer\">https://localbyflywheel.com/</a></p>\n\n<p>Local has option under Utilities (for a site) to add XDebug configuration to PHPStorm, after clicking that button reopen the project in PHPStorm and you will see a debug configuration already setup for that site.</p>\n\n<p>PHPStorm EAP (eap was free previously) can be downloaded here (also has 30 day trial):\n<a href=\"https://blog.jetbrains.com/phpstorm/2019/04/phpstorm-2019-1-2-preview-191-7141-5/\" rel=\"nofollow noreferrer\">https://blog.jetbrains.com/phpstorm/2019/04/phpstorm-2019-1-2-preview-191-7141-5/</a></p>\n\n<p>Docs on setting up XDebug:\n<a href=\"https://www.jetbrains.com/help/phpstorm/debugging-with-phpstorm-ultimate-guide.html\" rel=\"nofollow noreferrer\">https://www.jetbrains.com/help/phpstorm/debugging-with-phpstorm-ultimate-guide.html</a></p>\n\n<p>You can then set a breakpoint in your code and inspect it using XDebug.</p>\n\n<p>The options above do work in a crunch, but the correct way to debug PHP is using an IDE and XDebug, and will save you TONS of time if you learn to do it the right way.</p>\n\n<p><strong>Using <code>error_log</code>:</strong></p>\n\n<p>To expand on others responses about <code>error_log</code> output, if it's an array or something that's not a string, it's best to use <code>print_r</code> and set return to <code>true</code>:</p>\n\n<pre><code>error_log( 'MY STUFF: ' . print_r( $something, true ) );\n</code></pre>\n" } ]
2015/12/03
[ "https://wordpress.stackexchange.com/questions/210683", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/34548/" ]
I have a dynamic list of checkboxes that are showing on a user profile in the admin area (user-edit.php). A user should be able to select the checkboxes which will save their selections as an array in a usermeta field. Easy enough. However when I load the user profile after Updating the User, the boxes are not checked even though the options were saved in the usermeta field and the checkbox has a property of checked="checked". At first I was just using a basic in\_array() to check if the checkbox value was in the array from the usermeta. If it was then I set checked="checked". This worked and showed in dev tools as showing checked="checked", however there was still no checkmark. Here's what that looked like: ``` $courseResults = DwgFunctions::get_all_courses(); $userWaivedModules = DwgFunctions::checkCourses('scorm_waived_courses',$user); foreach($courseResults as $course){ $courseListing.= '<input type="checkbox" name="waivedCourses[]" value="'.$course->getCourseId().'" '.(in_array($course->getCourseId(),$userWaivedModules)?"checked=\"checked\"":"").'/>'.$course->getTitle().'<br />'; } ``` After doing some reading I discovered that WordPress likes to make us use the checked() function. Of course it just checks strings and I needed it to check against an array. So I used a handy function I found on the forums and now have this: ``` $courseResults = DwgFunctions::get_all_courses(); $userWaivedModules = DwgFunctions::checkCourses('scorm_waived_courses',$user); foreach($courseResults as $course){ $courseListing.= '<input type="checkbox" name="waivedCourses[]" value="'.$course->getCourseId().'" '.DwgFunctions::dwg_checked($userWaivedModules,$course->getCourseId()).'/>'.$course->getTitle().'<br />'; } ``` And my deg\_checked function looks like this: ``` function dwg_checked($haystack, $current){ if(is_array($haystack) && in_array($current, $haystack)) { $current = $haystack = 1; } return checked($haystack, $current); } ``` Both ways the result is the same: ``` <input type="checkbox" name="waivedCourses[]" value="1-555e1f4f86bd2">SC DDSN Family-Arranged Respite - An Overview for Families<br> <input type="checkbox" name="waivedCourses[]" value="1-555e1f89ae931" checked="checked">Overview for Families - Quiz<br> <input type="checkbox" name="waivedCourses[]" value="1-555e1f9d1d688" checked="checked">Overview for Families - Quiz<br> <input type="checkbox" name="waivedCourses[]" value="1-555e20e3079ad" checked="checked">Overview for Families - Quiz<br> <input type="checkbox" name="waivedCourses[]" value="FamilyModule_FinalQuizc0ea0981-8158-4077-b94a-6d182db566a3">FamilyModule_FinalQuiz<br> <input type="checkbox" name="waivedCourses[]" value="FAMILYMODULE_QUIZ3ecc3d81-1281-4477-adb8-ac81ef96724a">FAMILYMODULE_QUIZ<br> <input type="checkbox" name="waivedCourses[]" value="FamilyModule_TheFinalQuizad828150-f6da-4e19-b69c-5a78a74d412a">FamilyModule_FinalQuiz_2<br> ``` However it shows on the screen as: [![unchecked boxes](https://i.stack.imgur.com/yneXf.png)](https://i.stack.imgur.com/yneXf.png) If I update the user as is (with some boxes showing checked="checked" however none actually showing a checkmark), it will clear my usermeta value completely. If I actually check the checkbox it will show the checkmark and also implement the css for input[type=checkbox]:checked:before , and will save the setting in the usermeta. Notice though that the css before pseudoclass is not implemented when the checked attribute is dynamically added. [![checked](https://i.stack.imgur.com/nU5q8.png)](https://i.stack.imgur.com/nU5q8.png) ``` input[type=checkbox]:checked:before { content: '\f147'; margin: -3px 0 0 -4px; color: #1e8cbe; } ``` Any ideas what could be going on? Other places I have checkboxes that are working fine, however those are not using arrays (nor are they using the checked() function)
You can simply use `var_dump()` to do this. That is how I check values inside functions and filters. I have the following line of code in a file which I simply copy and paste where needed to dump the value of a variable ``` ?><pre><?php var_dump( $variable_to_test ); ?></pre><?php ``` The `pre` tags dump a nice readable array/object/string depending on the value. Inside your function you can just do ``` ?><pre><?php var_dump($ad_posts); ?></pre><?php ``` after `ksort( $ad_posts );`. Just make sure to call the function somewhere if it is not hooked to some kind of hook otherwise nothing will happen
210,701
<p>I want to display an admin_notice error message on the custom admin page of my plugin - but I want it to only be displayed from a jQuery event. </p> <p>All of my jQuery is working. I can send data, see alerts, receive data. But I cannot get the error message to work from the jQuery event.</p> <p>This displays the error message on every screen in the dashboard.</p> <pre><code>add_action('admin_notices', 'my_error_notice'); function my_error_notice () { echo '&lt;div class="error"&gt;&lt;p&gt;This is my error message.&lt;/p&gt;&lt;/div&gt;'; } </code></pre> <p>This displays the error message on my admin page only.</p> <pre><code>add_action('admin_notices', 'my_error_notice'); function my_error_notice () { global $my_admin_page; $screen = get_current_screen(); if ( $screen-&gt;id == $my_admin_page ) { echo '&lt;div class="error"&gt;&lt;p&gt;This is my error message.&lt;/p&gt;&lt;/div&gt;'; } else { return; } } </code></pre> <p>I want to only display the error message from a jQuery event.</p> <pre><code>add_action('wp_ajax_test_function', 'test_function'); function test_function() { add_action('admin_notices', 'my_error_notice'); } function my_error_notice () { global $my_admin_page; $screen = get_current_screen(); if ( $screen-&gt;id == $my_admin_page ) { echo '&lt;div class="error"&gt;&lt;p&gt;This is my error message.&lt;/p&gt;&lt;/div&gt;'; } else { return; } } </code></pre> <p>jQuery</p> <pre><code>jQuery(document).ready(function() { jQuery("#my-button").click(function() { jQuery.ajax({ type: 'POST', url: myAjax.ajaxurl, data: { "action": "test_function" } }); }); </code></pre>
[ { "answer_id": 210707, "author": "Douglas.Sesar", "author_id": 19945, "author_profile": "https://wordpress.stackexchange.com/users/19945", "pm_score": 2, "selected": false, "text": "<p>You can add the error message HTML in the success function of your AJAX call: </p>\n\n<pre><code>jQuery(document).ready(function() {\njQuery(\"#my-button\").click(function() {\n jQuery.ajax({\n type: 'POST',\n url: myAjax.ajaxurl,\n data: {\n \"action\": \"test_function\"\n },\n success: function(response){\n jQuery('#wpbody-content').prepend('&lt;div class=\"error\"&gt;&lt;p&gt;'+response.error_message+'&lt;/p&gt;&lt;/div&gt;');\n }\n });\n});\n</code></pre>\n" }, { "answer_id": 211842, "author": "mosley", "author_id": 84705, "author_profile": "https://wordpress.stackexchange.com/users/84705", "pm_score": 2, "selected": false, "text": "<p>Thanks to Douglas.Sesar for pointing me in the right direction. Much appreciated! This is what I did...</p>\n\n<p>First put the following id in the title heading of the plugin. I am adding the admin message html (via jQuery) directly after this heading.</p>\n\n<pre><code>&lt;h1 id=\"my-admin-message\"&gt;My Plugin Title&lt;/h1&gt;\n</code></pre>\n\n<p>My jQuery function:</p>\n\n<pre><code>function fnDisplayAdminMessage(adminMessage, adminMessageColor) {\njQuery.ajax({\n type: 'POST',\n url: myAjax.ajaxurl,\n success: function(response) {\n jQuery('#my-admin-message').after('&lt;div class=\"error notice is-dismissible\"&gt;&lt;p&gt;' + adminMessage + '&lt;/p&gt;&lt;button id=\"my-dismiss-admin-message\" class=\"notice-dismiss\" type=\"button\"&gt;&lt;span class=\"screen-reader-text\"&gt;Dismiss this notice.&lt;/span&gt;&lt;/button&gt;&lt;/div&gt;');\n jQuery(\"#my-dismiss-admin-message\").click(function(event) {\n event.preventDefault();\n jQuery('.' + 'error').fadeTo(100, 0, function() {\n jQuery('.' + 'error').slideUp(100, function() {\n jQuery('.' + 'error').remove();\n });\n });\n });\n switch (adminMessageColor) {\n case 'yellow':\n jQuery(\"div.error\").css(\"border-left\", \"4px solid #ffba00\");\n break;\n case 'red':\n jQuery(\"div.error\").css(\"border-left\", \"4px solid #dd3d36\");\n break;\n default:\n jQuery(\"div.error\").css(\"border-left\", \"4px solid #7ad03a\");\n }\n }\n});\n}\n</code></pre>\n\n<p>And my call:</p>\n\n<pre><code>fnDisplayAdminMessage('There was an error.', 'red');\n</code></pre>\n\n<p>I made it so I am always using the 'error' admin notice, and just changing the color.</p>\n\n<p>Lastly, a function to remove the message:</p>\n\n<pre><code>function fnRemoveAdminMessage() {\n// check if there is an admin message displayed, if so then remove it\nif (jQuery(\"div.error\").length) {\n jQuery(\"div.error\").fadeTo(100, 0, function() {\n jQuery(\"div.error\").slideUp(100, function() {\n jQuery(\"div.error\").remove();\n });\n });\n}\n}\n</code></pre>\n\n<p>I hope someone else finds this useful.</p>\n" }, { "answer_id": 402597, "author": "sariDon", "author_id": 92425, "author_profile": "https://wordpress.stackexchange.com/users/92425", "pm_score": 0, "selected": false, "text": "<p>I have come up to another simple working solution to throw a dismissable notice in wordpress admin from jquery javascript with ajax. Hope this helps someone.</p>\n<pre class=\"lang-js prettyprint-override\"><code>jQuery(document).ready(function() {\njQuery(&quot;#my-button&quot;).click(function() {\n jQuery('.my_notice').remove(); // remove previous notices\n jQuery.ajax({\n type: 'POST',\n url: myAjax.ajaxurl,\n data: {&quot;action&quot;: &quot;test_function&quot;},\n success: function(response){\n var msg= '';\n if(response.error_message=='')\n msg= '&lt;div class=&quot;notice notice-success is-dismissible my_notice&quot;&gt;&lt;p&gt;&lt;strong&gt;SUCCESS: &lt;/strong&gt;This is my success message.&lt;/p&gt;&lt;button type=&quot;button&quot; class=&quot;notice-dismiss&quot; onclick=&quot;javascript: return px_dissmiss_notice(this);&quot;&gt;&lt;span class=&quot;screen-reader-text&quot;&gt;Dismiss this notice.&lt;/span&gt;&lt;/button&gt;&lt;/div&gt;';\n else\n msg= '&lt;div class=&quot;notice notice-error is-dismissible my_notice&quot;&gt;&lt;p&gt;&lt;strong&gt;ERROR: &lt;/strong&gt;'+response.error_message+'.&lt;/p&gt;&lt;button type=&quot;button&quot; class=&quot;notice-dismiss&quot; onclick=&quot;javascript: return px_dissmiss_notice(this);&quot;&gt;&lt;span class=&quot;screen-reader-text&quot;&gt;Dismiss this notice.&lt;/span&gt;&lt;/button&gt;&lt;/div&gt;';\n jQuery('.wp-header-end').after(msg);\n },\n error: function(xhr){\n jQuery('.wp-header-end').after('&lt;div class=&quot;notice notice-error is-dismissible my_notice&quot;&gt;&lt;p&gt;&lt;strong&gt;ERROR: &lt;/strong&gt;'+ xhr.status +' '+ xhr.statusText+'.&lt;/p&gt;&lt;button type=&quot;button&quot; class=&quot;notice-dismiss&quot; onclick=&quot;javascript: return px_dissmiss_notice(this);&quot;&gt;&lt;span class=&quot;screen-reader-text&quot;&gt;Dismiss this notice.&lt;/span&gt;&lt;/button&gt;&lt;/div&gt;');\n },\n });\n});\n\nfunction px_dissmiss_notice(dobj)\n{\n jQuery(dobj).parent().slideUp(&quot;normal&quot;, function() {jQuery(this).remove();});\n return false;\n}\n</code></pre>\n<p><strong>NOTE:</strong>\nRemember to put <code>&lt;hr class=&quot;wp-header-end&quot;&gt;</code> below the title.</p>\n<p>Thats all.</p>\n" }, { "answer_id": 407267, "author": "Zeeshan Web", "author_id": 223656, "author_profile": "https://wordpress.stackexchange.com/users/223656", "pm_score": 0, "selected": false, "text": "<p>This is Work For me!</p>\n<pre><code>if( 'before' == response ) {\n\n $( '.rcpl-form-content' ).css( 'visibility', 'hidden' );\n $( '.rcpl-success-message' ).show();\n } else {\n\n let jsonEncode = JSON.parse( response );\n if( jsonEncode.status == 'false' ) {\n\n $( '.rcpl-success-message' ).addClass( 'notice notice-error' );\n $( '.rcpl-success-message' ).html( '&lt;div class=&quot;rcpl-error-wrap&quot;&gt;'+jsonEncode.message+' &lt;span class=&quot;dashicons dashicons-no-alt rcpl-close-icon&quot;&gt;&lt;/span&gt; &lt;/div&gt;' );\n\n } else {\n location.reload( true );\n }\n }\n</code></pre>\n" } ]
2015/12/03
[ "https://wordpress.stackexchange.com/questions/210701", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84705/" ]
I want to display an admin\_notice error message on the custom admin page of my plugin - but I want it to only be displayed from a jQuery event. All of my jQuery is working. I can send data, see alerts, receive data. But I cannot get the error message to work from the jQuery event. This displays the error message on every screen in the dashboard. ``` add_action('admin_notices', 'my_error_notice'); function my_error_notice () { echo '<div class="error"><p>This is my error message.</p></div>'; } ``` This displays the error message on my admin page only. ``` add_action('admin_notices', 'my_error_notice'); function my_error_notice () { global $my_admin_page; $screen = get_current_screen(); if ( $screen->id == $my_admin_page ) { echo '<div class="error"><p>This is my error message.</p></div>'; } else { return; } } ``` I want to only display the error message from a jQuery event. ``` add_action('wp_ajax_test_function', 'test_function'); function test_function() { add_action('admin_notices', 'my_error_notice'); } function my_error_notice () { global $my_admin_page; $screen = get_current_screen(); if ( $screen->id == $my_admin_page ) { echo '<div class="error"><p>This is my error message.</p></div>'; } else { return; } } ``` jQuery ``` jQuery(document).ready(function() { jQuery("#my-button").click(function() { jQuery.ajax({ type: 'POST', url: myAjax.ajaxurl, data: { "action": "test_function" } }); }); ```
You can add the error message HTML in the success function of your AJAX call: ``` jQuery(document).ready(function() { jQuery("#my-button").click(function() { jQuery.ajax({ type: 'POST', url: myAjax.ajaxurl, data: { "action": "test_function" }, success: function(response){ jQuery('#wpbody-content').prepend('<div class="error"><p>'+response.error_message+'</p></div>'); } }); }); ```
210,717
<p>I have set up my plugin option on admin panel with</p> <pre><code> /** * Register and add settings */ public function page_init() { register_setting( 'my_option_group', // Option group 'write_here_options', // Option name array( $this, 'sanitize' ) // Sanitize ); add_settings_section( 'setting_section_id', // ID 'Set Edit Page', // Title array( $this, 'print_section_info' ), // Callback 'write-here-setting' // Page ); add_settings_field( "pid_num", "Select Page &gt;&gt;", array( $this, 'wh_select_list' ), "write-here-setting", "setting_section_id" ); add_settings_field( 'num_of_posts', // ID 'Number of Posts to show', // Title array( $this, 'num_of_posts_callback' ), // Callback 'write-here-setting', // Page 'setting_section_id' // Section ); } </code></pre> <p>So in DB, my plugin setting saved in <code>wp_options</code> table under column name <code>option_name</code> as <code>write_here_options</code> in my case as object.</p> <p>When people activate the plugin, I want to save default values in the DB for <code>pid_num =&gt; 0</code> and <code>num_of_posts =&gt; 10</code>. </p> <p>How do I make this work??</p>
[ { "answer_id": 210781, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": false, "text": "<p>Your code will certainly use <a href=\"http://codex.wordpress.org/Function_Reference/get_option\" rel=\"nofollow\"><code>get_option()</code></a> to retrieve the values for your options. <code>get_option()</code> accepts a second argument that allows you to specify a default. Use that instead of inserted values into the database unnecessarily.</p>\n\n<pre><code>get_option( $option, $default );\n</code></pre>\n\n<p>If you are concerned about third party code, there is there is the <a href=\"https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-includes/option.php#L116\" rel=\"nofollow\"><code>option_{$option}</code> filter</a> that you should be able to use to preserve your default even then:</p>\n\n<pre><code>116 /**\n117 * Filter the value of an existing option.\n118 *\n119 * The dynamic portion of the hook name, `$option`, refers to the option name.\n120 *\n121 * @since 1.5.0 As 'option_' . $setting\n122 * @since 3.0.0\n123 *\n124 * @param mixed $value Value of the option. If stored serialized, it will be\n125 * unserialized prior to being returned.\n126 */\n127 return apply_filters( 'option_' . $option, maybe_unserialize( $value ) );\n</code></pre>\n" }, { "answer_id": 210806, "author": "Ohsik", "author_id": 74171, "author_profile": "https://wordpress.stackexchange.com/users/74171", "pm_score": 1, "selected": true, "text": "<p>I added below code to set default value to DB when plugin is activated.</p>\n\n<pre><code>function write_here_activation_actions(){\n do_action( 'wp_writehere_extension_activation' );\n}\nregister_activation_hook( __FILE__, 'write_here_activation_actions' );\n// Set default values here\nfunction write_here_default_options(){\n $default = array(\n 'pid_num' =&gt; '0',\n 'num_of_posts' =&gt; '10'\n );\n update_option( 'write_here_options', $default );\n}\nadd_action( 'wp_writehere_extension_activation', 'write_here_default_options' );\n</code></pre>\n" }, { "answer_id": 315705, "author": "Remzi Cavdar", "author_id": 149484, "author_profile": "https://wordpress.stackexchange.com/users/149484", "pm_score": 1, "selected": false, "text": "<p>Use add_option instead of update_option. If you use add_option existing options will not be updated and checks are performed to ensure that you aren’t adding a protected WordPress option.</p>\n\n<p>See <a href=\"https://developer.wordpress.org/reference/functions/add_option/\" rel=\"nofollow noreferrer\">add_option</a> and <a href=\"https://developer.wordpress.org/reference/functions/update_option/\" rel=\"nofollow noreferrer\">update_option at developer.wordpress.org</a></p>\n\n<pre><code>// Activation\nfunction name_plugin_activation(){\n do_action( 'name_plugin_default_options' );\n}\nregister_activation_hook( __FILE__, 'name_plugin_activation' );\n\n\n// Set default values here\nfunction name_plugin_default_values(){\n\n // Form settings\n add_option('name_form_to', '[email protected]');\n add_option('name_form_subject', 'New');\n\n\n}\nadd_action( 'name_plugin_default_options', 'name_plugin_default_values' );\n</code></pre>\n" } ]
2015/12/03
[ "https://wordpress.stackexchange.com/questions/210717", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74171/" ]
I have set up my plugin option on admin panel with ``` /** * Register and add settings */ public function page_init() { register_setting( 'my_option_group', // Option group 'write_here_options', // Option name array( $this, 'sanitize' ) // Sanitize ); add_settings_section( 'setting_section_id', // ID 'Set Edit Page', // Title array( $this, 'print_section_info' ), // Callback 'write-here-setting' // Page ); add_settings_field( "pid_num", "Select Page >>", array( $this, 'wh_select_list' ), "write-here-setting", "setting_section_id" ); add_settings_field( 'num_of_posts', // ID 'Number of Posts to show', // Title array( $this, 'num_of_posts_callback' ), // Callback 'write-here-setting', // Page 'setting_section_id' // Section ); } ``` So in DB, my plugin setting saved in `wp_options` table under column name `option_name` as `write_here_options` in my case as object. When people activate the plugin, I want to save default values in the DB for `pid_num => 0` and `num_of_posts => 10`. How do I make this work??
I added below code to set default value to DB when plugin is activated. ``` function write_here_activation_actions(){ do_action( 'wp_writehere_extension_activation' ); } register_activation_hook( __FILE__, 'write_here_activation_actions' ); // Set default values here function write_here_default_options(){ $default = array( 'pid_num' => '0', 'num_of_posts' => '10' ); update_option( 'write_here_options', $default ); } add_action( 'wp_writehere_extension_activation', 'write_here_default_options' ); ```
210,752
<p>I want to change the status of already publish post to draft using its id.</p> <pre><code> add_action( 'save_post', 'change_post_status', 1 ); function change_post_status( $post_id ){ $my_post = array( 'ID' =&gt; 1, 'post_status' =&gt; 'draft', ); // unhook this function so it doesn't loop infinitely remove_action('save_post', 'change_post_status'); if( $post_id == 1 ){ wp_update_post( $my_post ); } // re-hook this function add_action('save_post', 'change_post_status'); } </code></pre> <p>I want to change the status of specific post which has id = 1 to be changed to draft.It is working but leading to</p> <blockquote> <p>Maximum function nesting level of '100' reached, aborting!</p> </blockquote> <p>why it is getting this error ?</p> <p>What I think is it is running when post is updated or saving , I want to just run the function independent of save or update action like on <code>wp_init</code> or <code>wp_admin</code> or <code>admin_init</code> some other hook, is it possible.</p>
[ { "answer_id": 210756, "author": "jas", "author_id": 80247, "author_profile": "https://wordpress.stackexchange.com/users/80247", "pm_score": 2, "selected": false, "text": "<p>In your <code>functions.php</code> :</p>\n\n<pre><code>add_action('publish_post', 'check_user_publish', 10, 2);\n\nfunction check_user_publish ($post_id, $post) {\n\n if($post_id == 1){\n $query = array(\n 'ID' =&gt; $post_id,\n 'post_status' =&gt; 'draft',\n );\n wp_update_post( $query, true );\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 254177, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 0, "selected": false, "text": "<p>To remove a hook, it has to have the same priority as when you add the hook. You add_action with a priority of 1. If you want to remove the action, you need to remove it with a priority of 1. See <a href=\"https://codex.wordpress.org/Function_Reference/remove_action\" rel=\"nofollow noreferrer\" title=\"remove_action\">the codex</a>.</p>\n\n<pre><code>add_action( 'save_post', 'change_post_status', 1 );\nfunction change_post_status( $post_id ){\n $my_post = array(\n 'ID' =&gt; 1,\n 'post_status' =&gt; 'draft',\n );\n // unhook this function, making sure to use the same priority, so it doesn't loop infinitely\n remove_action('save_post', 'change_post_status', 1 );\n if( $post_id == 1 ){\n wp_update_post( $my_post );\n }\n // re-hook this function with the initial priority\n add_action('save_post', 'change_post_status', 1 );\n}\n</code></pre>\n" } ]
2015/12/04
[ "https://wordpress.stackexchange.com/questions/210752", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84740/" ]
I want to change the status of already publish post to draft using its id. ``` add_action( 'save_post', 'change_post_status', 1 ); function change_post_status( $post_id ){ $my_post = array( 'ID' => 1, 'post_status' => 'draft', ); // unhook this function so it doesn't loop infinitely remove_action('save_post', 'change_post_status'); if( $post_id == 1 ){ wp_update_post( $my_post ); } // re-hook this function add_action('save_post', 'change_post_status'); } ``` I want to change the status of specific post which has id = 1 to be changed to draft.It is working but leading to > > Maximum function nesting level of '100' reached, aborting! > > > why it is getting this error ? What I think is it is running when post is updated or saving , I want to just run the function independent of save or update action like on `wp_init` or `wp_admin` or `admin_init` some other hook, is it possible.
In your `functions.php` : ``` add_action('publish_post', 'check_user_publish', 10, 2); function check_user_publish ($post_id, $post) { if($post_id == 1){ $query = array( 'ID' => $post_id, 'post_status' => 'draft', ); wp_update_post( $query, true ); } } ```
210,758
<p>I'm trying to add some static (welcome) text above my post excerpts, for which the posts page has been set up to display a category, in this case <code>News</code>. <a href="http://www.westcoast-mountainguides.co.uk/category/news/" rel="nofollow">Link</a></p> <p>I've tried entering the following:</p> <pre><code>&lt;?php echo category_description(); ?&gt; </code></pre> <p>into the <code>index.php</code> and then adding a category description, and it sort of works, but I end up with a huge white, empty space below the static text, and before the first blog excerpt. Any help will be greatly appreciated.</p>
[ { "answer_id": 210756, "author": "jas", "author_id": 80247, "author_profile": "https://wordpress.stackexchange.com/users/80247", "pm_score": 2, "selected": false, "text": "<p>In your <code>functions.php</code> :</p>\n\n<pre><code>add_action('publish_post', 'check_user_publish', 10, 2);\n\nfunction check_user_publish ($post_id, $post) {\n\n if($post_id == 1){\n $query = array(\n 'ID' =&gt; $post_id,\n 'post_status' =&gt; 'draft',\n );\n wp_update_post( $query, true );\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 254177, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 0, "selected": false, "text": "<p>To remove a hook, it has to have the same priority as when you add the hook. You add_action with a priority of 1. If you want to remove the action, you need to remove it with a priority of 1. See <a href=\"https://codex.wordpress.org/Function_Reference/remove_action\" rel=\"nofollow noreferrer\" title=\"remove_action\">the codex</a>.</p>\n\n<pre><code>add_action( 'save_post', 'change_post_status', 1 );\nfunction change_post_status( $post_id ){\n $my_post = array(\n 'ID' =&gt; 1,\n 'post_status' =&gt; 'draft',\n );\n // unhook this function, making sure to use the same priority, so it doesn't loop infinitely\n remove_action('save_post', 'change_post_status', 1 );\n if( $post_id == 1 ){\n wp_update_post( $my_post );\n }\n // re-hook this function with the initial priority\n add_action('save_post', 'change_post_status', 1 );\n}\n</code></pre>\n" } ]
2015/12/04
[ "https://wordpress.stackexchange.com/questions/210758", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84743/" ]
I'm trying to add some static (welcome) text above my post excerpts, for which the posts page has been set up to display a category, in this case `News`. [Link](http://www.westcoast-mountainguides.co.uk/category/news/) I've tried entering the following: ``` <?php echo category_description(); ?> ``` into the `index.php` and then adding a category description, and it sort of works, but I end up with a huge white, empty space below the static text, and before the first blog excerpt. Any help will be greatly appreciated.
In your `functions.php` : ``` add_action('publish_post', 'check_user_publish', 10, 2); function check_user_publish ($post_id, $post) { if($post_id == 1){ $query = array( 'ID' => $post_id, 'post_status' => 'draft', ); wp_update_post( $query, true ); } } ```
210,765
<p>I have read that it is advised (especially with php 7) to not close the php files with <code>?&gt;</code></p> <p>Many of my WP php files end like this:</p> <pre><code>&lt;?php get_sidebar(); ?&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>Should I remove the closing tag and have something like this</p> <pre><code>&lt;?php get_sidebar(); ?&gt; &lt;?php get_footer(); </code></pre> <p>at the end of my files?</p>
[ { "answer_id": 210790, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 6, "selected": true, "text": "<p>Yes, please avoid closing PHP tags at the end of the file, not only with PHP 7, but with PHP 5 as well.</p>\n\n<p>Reason is that if you close the tag, anything that is after the tag, even a blank line, will be sent to output and will make PHP to send headers as well preventing cookie to be set, redirect to work, feed to be valid, and so on.</p>\n\n<p>I guess that you ever encountered a message like</p>\n\n<blockquote>\n <p>Cannot modify header information - headers already sent by (output started at ...) in ... on line ...</p>\n</blockquote>\n\n<p>A closing <code>?&gt;</code> at end of the file can be the cause.</p>\n" }, { "answer_id": 210805, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 4, "selected": false, "text": "<p>Given your specific example, I would keep the closing tag i.e. one-line function calls within a template. It's consistent and aids clarity (in the same way WordPress recommend <a href=\"https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#indentation\">trailing commas for arrays</a>)- otherwise imagine if a non-developer picked up your file and started adding to it:</p>\n\n<pre><code>&lt;?php get_footer();\n\n&lt;div&gt;What the hell am I doing wrong?&lt;/div&gt;\n</code></pre>\n\n<p>However, for all other files (functions, includes etc.), the advice is most definitely a good idea:</p>\n\n<pre><code>&lt;?php // Start of file\n\nclass MY_Class {\n function just_do_it() {\n }\n}\n\n// Bye bye closing tag\n</code></pre>\n\n<p>I find it's cleaner, and as other's have mentioned, no risk of the dreaded \"headers already sent\".</p>\n" } ]
2015/12/04
[ "https://wordpress.stackexchange.com/questions/210765", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80031/" ]
I have read that it is advised (especially with php 7) to not close the php files with `?>` Many of my WP php files end like this: ``` <?php get_sidebar(); ?> <?php get_footer(); ?> ``` Should I remove the closing tag and have something like this ``` <?php get_sidebar(); ?> <?php get_footer(); ``` at the end of my files?
Yes, please avoid closing PHP tags at the end of the file, not only with PHP 7, but with PHP 5 as well. Reason is that if you close the tag, anything that is after the tag, even a blank line, will be sent to output and will make PHP to send headers as well preventing cookie to be set, redirect to work, feed to be valid, and so on. I guess that you ever encountered a message like > > Cannot modify header information - headers already sent by (output started at ...) in ... on line ... > > > A closing `?>` at end of the file can be the cause.
210,770
<p>I added a custom column to a custom post type:</p> <pre><code>add_filter('manage_posts_columns', 'custom_columns', 10); add_action('manage_posts_custom_column', 'custom_columns_thumb', 10, 2); function custom_columns($columns) { $columns = array( 'cb' =&gt; '&lt;input type="checkbox" /&gt;', 'title' =&gt; 'Title', 'categories' =&gt; 'Categories', // not showing 'thumb' =&gt; __('Thumb'), 'date' =&gt; __( 'Date' ) ); return $columns; } function custom_columns_thumb($column_name, $id){ if($column_name === 'thumb') { echo the_post_thumbnail( 'thumb' ); } } </code></pre> <p>The custom column "thumb" shows properly but the category is no longer displayed. Please see image.</p> <p><a href="https://i.stack.imgur.com/o6ykR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o6ykR.png" alt="enter image description here"></a></p> <p>What is causing this? The categories show if I remove the custom columns. </p>
[ { "answer_id": 211498, "author": "Abhik", "author_id": 26991, "author_profile": "https://wordpress.stackexchange.com/users/26991", "pm_score": 2, "selected": false, "text": "<p>Try adding the <code>Thumb</code> Column instead of re-defining the whole columns.</p>\n\n<pre><code>function custom_columns($columns) { \n return array_merge( $columns, \n array( 'thumb' =&gt; __('Thumb', 'mytextdomain' ),\n ) );\n} \n</code></pre>\n\n<p>Also, make sure if you accidentally <code>unset</code> the Categories column when you removed the <code>Tags</code>, <code>Author</code> and <code>Comments</code> columns.</p>\n\n<p><strong>EDIT</strong><br>\nAfter seeing the little search button label at the top right corner of the second screenshot, I can see that you are indeed using a Custom Post Type. In that case, if you want associate the default \"Categories\" to your CPT, use this piece of code with the current array of arguments that registers your CPT: </p>\n\n<p><code>'taxonomies' =&gt; array('category');</code> </p>\n\n<p>Also, change your filters to <code>manage_post_type_posts_columns</code> and <code>manage_post_type_posts_columns</code>. Where <code>post_type</code> is your CPT.</p>\n\n<p>Thanks to cybmeta and PieterGoosen for the comments.</p>\n" }, { "answer_id": 211502, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p>If you want to add new columns without breaking the bank, I find storing the old values first helps to make sure you keep what is there and only add what you need. If you want to see less then adjust with screen options.</p>\n\n<pre><code>$post_type = 'posts';\nadd_filter(\"manage_${post_type}_posts_columns\", 'posts_set_custom_columns', 10);\nadd_action(\"manage_${post_type}_posts_custom_column\", 'posts_render_custom_columns', 10, 2);\n\nfunction posts_set_custom_columns ($columns) {\n\n // save existing settings for columns\n\n $before = array(\n 'cb' =&gt; $columns ['cb'],\n 'title' =&gt; $columns ['title'],\n 'categories' =&gt; $columns ['categories'],\n );\n\n // remove all the items before our new columns\n\n foreach ($before as $inx =&gt; $label) {\n unset($columns[$inx]);\n }\n\n // push our new columns to the front\n\n $columns = array_merge(\n array(\n 'thumb' =&gt; __('Thumb'),\n ), $columns);\n\n // put the first items back in the front\n\n $columns = array_merge($before, $columns);\n\n return $columns;\n}\n\nfunction posts_render_custom_columns ($column_name, $id) {\n if($column_name === 'thumb') {\n\n $size = 'thumbnail';\n\n // display the image or a mark to let us know it's missing\n if ( has_post_thumbnail( $id ))\n the_post_thumbnail( $size );\n else\n echo \"-\";\n }\n}\n</code></pre>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/manage_$post_type_posts_columns\" rel=\"nofollow\">manage_$post_type_posts_columns</a></li>\n<li><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/manage_posts_custom_column\" rel=\"nofollow\">manage_posts_custom_column</a></li>\n</ul>\n" }, { "answer_id": 211511, "author": "Kvvaradha", "author_id": 43308, "author_profile": "https://wordpress.stackexchange.com/users/43308", "pm_score": 4, "selected": true, "text": "<p>Here I tested this code and its working fine and steps here. </p>\n\n<ol>\n<li><p>I am just creating a dummy <code>custom_post_type</code> here <code>book</code> with the following code.</p>\n\n<pre><code> function kv_custom_post_books() {\n $args = array(\n 'public' =&gt; true,\n 'label' =&gt; 'Books',\n 'taxonomies' =&gt; array('category', 'post_tag') , \n 'supports' =&gt; array( 'title', 'editor', 'thumbnail' )\n );\n register_post_type( 'book', $args );\n}\nadd_action( 'init', 'kv_custom_post_books' );\n</code></pre></li>\n</ol>\n\n<p>Here i am not sure, you used this line. <code>'taxonomies' =&gt; array('category', 'post_tag')</code> . This one gets you the default categoires to your custom post type. </p>\n\n<ol start=\"2\">\n<li><p>Now we will rewrite your action hook here. and we use the same functions no change in it.</p>\n\n<pre><code>add_filter('manage_edit-book_columns', 'custom_columns', 10); \nadd_action('manage_posts_custom_column', 'custom_columns_thumb', 10, 2); \n\nfunction custom_columns($columns) { \n $columns = array(\n 'cb' =&gt; '&lt;input type=\"checkbox\" /&gt;',\n 'title' =&gt; 'Title',\n 'categories' =&gt; 'Categories', // not showing\n 'thumb' =&gt; __('Thumb'),\n 'date' =&gt; __( 'Date' )\n );\n return $columns;\n} \n\nfunction custom_columns_thumb($column_name, $id){ \n if($column_name === 'thumb') { \n echo the_post_thumbnail( 'thumb' ); \n } \n}\n</code></pre></li>\n</ol>\n\n<p><strong>Note :</strong> I just edited only one line in your code. <code>add_filter('manage_edit-book_columns', 'custom_columns', 10);</code>. We have to specify your custom post type in your action hook. This is the ultimate thing here . <code>manage_edit-book_columns</code> Instead of default one we have to specify the custom post type name here. </p>\n\n<p>Here I attached a screenshot for you, </p>\n\n<p><a href=\"https://i.stack.imgur.com/8XhdF.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/8XhdF.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 212019, "author": "Ravi Patel", "author_id": 35477, "author_profile": "https://wordpress.stackexchange.com/users/35477", "pm_score": 0, "selected": false, "text": "<p><strong>slider</strong> to change your post name and \n<strong>slider_category</strong> to change <strong>your taxonomy category name</strong></p>\n\n<pre><code> &lt;?php\n/** Manage column Function */\nadd_filter(\"manage_edit-slider_columns\", \"slider_edit_columns\");\nadd_action(\"manage_posts_custom_column\", \"slider_custom_columns\");\n\nfunction slider_edit_columns($columns) {\n $columns = array(\n \"cb\" =&gt; \"&lt;input type=\\\"checkbox\\\" /&gt;\",\n \"title\" =&gt; \"Title\",\n \"slider_category\" =&gt; \"Categories\", \n \"date\" =&gt; \"Date\",\n );\n return $columns;\n}\n\nfunction slider_custom_columns($column) {\n global $post;\n switch ($column) {\n case 'thumb':\n echo the_post_thumbnail( 'thumb' ); \n break;\n case \"slider_category\": \n echo $cat = strip_tags(get_the_term_list($post-&gt;ID, 'slider_category', '', ', ','')); \n break; \n default:\n break;\n }\n}\n</code></pre>\n" } ]
2015/12/04
[ "https://wordpress.stackexchange.com/questions/210770", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1613/" ]
I added a custom column to a custom post type: ``` add_filter('manage_posts_columns', 'custom_columns', 10); add_action('manage_posts_custom_column', 'custom_columns_thumb', 10, 2); function custom_columns($columns) { $columns = array( 'cb' => '<input type="checkbox" />', 'title' => 'Title', 'categories' => 'Categories', // not showing 'thumb' => __('Thumb'), 'date' => __( 'Date' ) ); return $columns; } function custom_columns_thumb($column_name, $id){ if($column_name === 'thumb') { echo the_post_thumbnail( 'thumb' ); } } ``` The custom column "thumb" shows properly but the category is no longer displayed. Please see image. [![enter image description here](https://i.stack.imgur.com/o6ykR.png)](https://i.stack.imgur.com/o6ykR.png) What is causing this? The categories show if I remove the custom columns.
Here I tested this code and its working fine and steps here. 1. I am just creating a dummy `custom_post_type` here `book` with the following code. ``` function kv_custom_post_books() { $args = array( 'public' => true, 'label' => 'Books', 'taxonomies' => array('category', 'post_tag') , 'supports' => array( 'title', 'editor', 'thumbnail' ) ); register_post_type( 'book', $args ); } add_action( 'init', 'kv_custom_post_books' ); ``` Here i am not sure, you used this line. `'taxonomies' => array('category', 'post_tag')` . This one gets you the default categoires to your custom post type. 2. Now we will rewrite your action hook here. and we use the same functions no change in it. ``` add_filter('manage_edit-book_columns', 'custom_columns', 10); add_action('manage_posts_custom_column', 'custom_columns_thumb', 10, 2); function custom_columns($columns) { $columns = array( 'cb' => '<input type="checkbox" />', 'title' => 'Title', 'categories' => 'Categories', // not showing 'thumb' => __('Thumb'), 'date' => __( 'Date' ) ); return $columns; } function custom_columns_thumb($column_name, $id){ if($column_name === 'thumb') { echo the_post_thumbnail( 'thumb' ); } } ``` **Note :** I just edited only one line in your code. `add_filter('manage_edit-book_columns', 'custom_columns', 10);`. We have to specify your custom post type in your action hook. This is the ultimate thing here . `manage_edit-book_columns` Instead of default one we have to specify the custom post type name here. Here I attached a screenshot for you, [![enter image description here](https://i.stack.imgur.com/8XhdF.png)](https://i.stack.imgur.com/8XhdF.png)
210,793
<p>how can I get a pagination link URL instead of a made-up anchor link? currently, I used</p> <pre><code>&lt;?php next_posts_link(); ?&gt; &lt;?php previous_posts_link(); ?&gt; </code></pre> <p>for pagination but it returns <code>a</code>, I want to know is there any way to get just the next/prev URL?</p>
[ { "answer_id": 210795, "author": "flomei", "author_id": 65455, "author_profile": "https://wordpress.stackexchange.com/users/65455", "pm_score": -1, "selected": false, "text": "<p>There are <a href=\"https://codex.wordpress.org/Function_Reference/get_previous_posts_link\" rel=\"nofollow\"><code>get_previous_posts_link()</code></a> and <a href=\"https://codex.wordpress.org/Function_Reference/get_next_posts_link\" rel=\"nofollow\"><code>get_next_posts_link()</code></a>, they should do what you want.</p>\n" }, { "answer_id": 210808, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 4, "selected": true, "text": "<p>If you check out the source, they're both wrappers around <code>*_posts()</code>, which in turn are wrappers for <code>get_*_posts_page_link()</code> (where the wildcard indicates either <code>next</code> or <code>previous</code>).</p>\n\n<p>For example, <a href=\"https://developer.wordpress.org/reference/functions/next_posts/\" rel=\"noreferrer\"><code>next_posts()</code></a> will echo or return the escaped URL, depending on the first argument:</p>\n\n<pre><code>$escaped_url = next_posts( false /* Don't echo */ ); \nnext_posts(); // Prints escaped URL\n</code></pre>\n\n<p>Otherwise you can get the raw URL with <a href=\"https://developer.wordpress.org/reference/functions/get_next_posts_page_link/\" rel=\"noreferrer\"><code>get_next_posts_page_link()</code></a> and do with it as you wish:</p>\n\n<pre><code> $raw_url = get_next_posts_page_link();\n\n wp_redirect( $raw_url );\n\n // or...\n echo esc_url( $raw_url );\n</code></pre>\n" } ]
2015/12/04
[ "https://wordpress.stackexchange.com/questions/210793", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58133/" ]
how can I get a pagination link URL instead of a made-up anchor link? currently, I used ``` <?php next_posts_link(); ?> <?php previous_posts_link(); ?> ``` for pagination but it returns `a`, I want to know is there any way to get just the next/prev URL?
If you check out the source, they're both wrappers around `*_posts()`, which in turn are wrappers for `get_*_posts_page_link()` (where the wildcard indicates either `next` or `previous`). For example, [`next_posts()`](https://developer.wordpress.org/reference/functions/next_posts/) will echo or return the escaped URL, depending on the first argument: ``` $escaped_url = next_posts( false /* Don't echo */ ); next_posts(); // Prints escaped URL ``` Otherwise you can get the raw URL with [`get_next_posts_page_link()`](https://developer.wordpress.org/reference/functions/get_next_posts_page_link/) and do with it as you wish: ``` $raw_url = get_next_posts_page_link(); wp_redirect( $raw_url ); // or... echo esc_url( $raw_url ); ```
210,816
<p><a href="http://thewowstudio.com/quad/" rel="nofollow">http://thewowstudio.com/quad/</a></p> <p>I want my titles to be clickable</p> <p>Can anyone help me to figure it out how do I do this? I have been trying since a hour but no help.</p> <p>thanks</p> <pre><code>&lt;?php /** * The default template for displaying content * * Used for both single and index/archive/search. * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ ?&gt; &lt;article id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class(); ?&gt;&gt; &lt;?php if ( is_sticky() &amp;&amp; is_home() &amp;&amp; ! is_paged() ) : ?&gt; &lt;div class="featured-post"&gt; &lt;?php _e( 'Featured post', 'twentytwelve' ); ?&gt; &lt;/div&gt; &lt;?php endif; ?&gt; &lt;header class="entry-header"&gt; &lt;?php if ( ! post_password_required() &amp;&amp; ! is_attachment() ) : the_post_thumbnail(array(400,200)); endif; ?&gt; &lt;?php if ( is_single() ) : ?&gt; &lt;h3 class="entry-title"&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt; &lt;?php else : ?&gt; &lt;h4 class="entry-title"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" rel="bookmark"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;/h4&gt; &lt;?php endif; // is_single() ?&gt; &lt;?php if ( comments_open() ) : ?&gt; &lt;div class="comments-link"&gt; &lt;?php comments_popup_link( '&lt;span class="leave-reply"&gt;' . __( 'Leave a reply', 'twentytwelve' ) . '&lt;/span&gt;', __( '1 Reply', 'twentytwelve' ), __( '% Replies', 'twentytwelve' ) ); ?&gt; &lt;/div&gt;&lt;!-- .comments-link --&gt; &lt;?php endif; // comments_open() ?&gt; &lt;/header&gt;&lt;!-- .entry-header --&gt; &lt;?php if ( is_search() ) : // Only display Excerpts for Search ?&gt; &lt;div class="entry-summary"&gt; &lt;?php the_excerpt(); ?&gt; &lt;/div&gt;&lt;!-- .entry-summary --&gt; &lt;?php else : ?&gt; &lt;div class="entry-content"&gt; &lt;?php the_content( __( 'Continue reading &lt;span class="meta-nav"&gt;&amp;rarr;&lt;/span&gt;', 'twentytwelve' ) ); ?&gt; &lt;?php wp_link_pages( array( 'before' =&gt; '&lt;div class="page-links"&gt;' . __( 'Pages:', 'twentytwelve' ), 'after' =&gt; '&lt;/div&gt;' ) ); ?&gt; &lt;/div&gt;&lt;!-- .entry-content --&gt; &lt;?php endif; ?&gt; &lt;footer class="entry-meta"&gt; &lt;?php twentytwelve_entry_meta(); ?&gt; &lt;?php edit_post_link( __( 'Edit', 'twentytwelve' ), '&lt;span class="edit-link"&gt;', '&lt;/span&gt;' ); ?&gt; &lt;?php if ( is_singular() &amp;&amp; get_the_author_meta( 'description' ) &amp;&amp; is_multi_author() ) : // If a user has filled out their description and this is a multi-author blog, show a bio on their entries. ?&gt; &lt;div class="author-info"&gt; &lt;div class="author-avatar"&gt; &lt;?php /** This filter is documented in author.php */ $author_bio_avatar_size = apply_filters( 'twentytwelve_author_bio_avatar_size', 68 ); echo get_avatar( get_the_author_meta( 'user_email' ), $author_bio_avatar_size ); ?&gt; &lt;/div&gt;&lt;!-- .author-avatar --&gt; &lt;div class="author-description"&gt; &lt;h2&gt;&lt;?php printf( __( 'About %s', 'twentytwelve' ), get_the_author() ); ?&gt;&lt;/h2&gt; &lt;p&gt;&lt;?php the_author_meta( 'description' ); ?&gt;&lt;/p&gt; &lt;div class="author-link"&gt; &lt;a href="&lt;?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?&gt;" rel="author"&gt; &lt;?php printf( __( 'View all posts by %s &lt;span class="meta-nav"&gt;&amp;rarr;&lt;/span&gt;', 'twentytwelve' ), get_the_author() ); ?&gt; &lt;/a&gt; &lt;/div&gt;&lt;!-- .author-link --&gt; &lt;/div&gt;&lt;!-- .author-description --&gt; &lt;/div&gt;&lt;!-- .author-info --&gt; &lt;?php endif; ?&gt; &lt;/footer&gt;&lt;!-- .entry-meta --&gt; &lt;/article&gt;&lt;!-- #post --&gt; </code></pre> <p>content.php</p>
[ { "answer_id": 210795, "author": "flomei", "author_id": 65455, "author_profile": "https://wordpress.stackexchange.com/users/65455", "pm_score": -1, "selected": false, "text": "<p>There are <a href=\"https://codex.wordpress.org/Function_Reference/get_previous_posts_link\" rel=\"nofollow\"><code>get_previous_posts_link()</code></a> and <a href=\"https://codex.wordpress.org/Function_Reference/get_next_posts_link\" rel=\"nofollow\"><code>get_next_posts_link()</code></a>, they should do what you want.</p>\n" }, { "answer_id": 210808, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 4, "selected": true, "text": "<p>If you check out the source, they're both wrappers around <code>*_posts()</code>, which in turn are wrappers for <code>get_*_posts_page_link()</code> (where the wildcard indicates either <code>next</code> or <code>previous</code>).</p>\n\n<p>For example, <a href=\"https://developer.wordpress.org/reference/functions/next_posts/\" rel=\"noreferrer\"><code>next_posts()</code></a> will echo or return the escaped URL, depending on the first argument:</p>\n\n<pre><code>$escaped_url = next_posts( false /* Don't echo */ ); \nnext_posts(); // Prints escaped URL\n</code></pre>\n\n<p>Otherwise you can get the raw URL with <a href=\"https://developer.wordpress.org/reference/functions/get_next_posts_page_link/\" rel=\"noreferrer\"><code>get_next_posts_page_link()</code></a> and do with it as you wish:</p>\n\n<pre><code> $raw_url = get_next_posts_page_link();\n\n wp_redirect( $raw_url );\n\n // or...\n echo esc_url( $raw_url );\n</code></pre>\n" } ]
2015/12/04
[ "https://wordpress.stackexchange.com/questions/210816", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84503/" ]
<http://thewowstudio.com/quad/> I want my titles to be clickable Can anyone help me to figure it out how do I do this? I have been trying since a hour but no help. thanks ``` <?php /** * The default template for displaying content * * Used for both single and index/archive/search. * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php if ( is_sticky() && is_home() && ! is_paged() ) : ?> <div class="featured-post"> <?php _e( 'Featured post', 'twentytwelve' ); ?> </div> <?php endif; ?> <header class="entry-header"> <?php if ( ! post_password_required() && ! is_attachment() ) : the_post_thumbnail(array(400,200)); endif; ?> <?php if ( is_single() ) : ?> <h3 class="entry-title"><?php the_title(); ?></h3> <?php else : ?> <h4 class="entry-title"> <a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a> </h4> <?php endif; // is_single() ?> <?php if ( comments_open() ) : ?> <div class="comments-link"> <?php comments_popup_link( '<span class="leave-reply">' . __( 'Leave a reply', 'twentytwelve' ) . '</span>', __( '1 Reply', 'twentytwelve' ), __( '% Replies', 'twentytwelve' ) ); ?> </div><!-- .comments-link --> <?php endif; // comments_open() ?> </header><!-- .entry-header --> <?php if ( is_search() ) : // Only display Excerpts for Search ?> <div class="entry-summary"> <?php the_excerpt(); ?> </div><!-- .entry-summary --> <?php else : ?> <div class="entry-content"> <?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'twentytwelve' ) ); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . __( 'Pages:', 'twentytwelve' ), 'after' => '</div>' ) ); ?> </div><!-- .entry-content --> <?php endif; ?> <footer class="entry-meta"> <?php twentytwelve_entry_meta(); ?> <?php edit_post_link( __( 'Edit', 'twentytwelve' ), '<span class="edit-link">', '</span>' ); ?> <?php if ( is_singular() && get_the_author_meta( 'description' ) && is_multi_author() ) : // If a user has filled out their description and this is a multi-author blog, show a bio on their entries. ?> <div class="author-info"> <div class="author-avatar"> <?php /** This filter is documented in author.php */ $author_bio_avatar_size = apply_filters( 'twentytwelve_author_bio_avatar_size', 68 ); echo get_avatar( get_the_author_meta( 'user_email' ), $author_bio_avatar_size ); ?> </div><!-- .author-avatar --> <div class="author-description"> <h2><?php printf( __( 'About %s', 'twentytwelve' ), get_the_author() ); ?></h2> <p><?php the_author_meta( 'description' ); ?></p> <div class="author-link"> <a href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>" rel="author"> <?php printf( __( 'View all posts by %s <span class="meta-nav">&rarr;</span>', 'twentytwelve' ), get_the_author() ); ?> </a> </div><!-- .author-link --> </div><!-- .author-description --> </div><!-- .author-info --> <?php endif; ?> </footer><!-- .entry-meta --> </article><!-- #post --> ``` content.php
If you check out the source, they're both wrappers around `*_posts()`, which in turn are wrappers for `get_*_posts_page_link()` (where the wildcard indicates either `next` or `previous`). For example, [`next_posts()`](https://developer.wordpress.org/reference/functions/next_posts/) will echo or return the escaped URL, depending on the first argument: ``` $escaped_url = next_posts( false /* Don't echo */ ); next_posts(); // Prints escaped URL ``` Otherwise you can get the raw URL with [`get_next_posts_page_link()`](https://developer.wordpress.org/reference/functions/get_next_posts_page_link/) and do with it as you wish: ``` $raw_url = get_next_posts_page_link(); wp_redirect( $raw_url ); // or... echo esc_url( $raw_url ); ```
210,817
<p>With this loop I am displaying single posts on an archive page. The posts are being sorted by the category 'Banks'. In addition to that, how can I display them in alphabetical order? I've tried using <code>WP_Query</code>, but cannot get it to work; it breaks my loop each time.</p> <pre><code>&lt;h3&gt;Banks &amp; Credit Unions&lt;/h3&gt; &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); if ( in_category( 'Banks' ) ) { ?&gt; &lt;li&gt; &lt;a href="&lt;?php the_permalink() ?&gt;"&gt; &lt;img src="&lt;?php the_field( 'biller_logo' )?&gt;"&gt; &lt;?php the_field( 'biller_name' ) ?&gt; &lt;/a&gt; &lt;/li&gt; &lt;?php } endwhile; endif; ?&gt; &lt;/ul&gt; </code></pre>
[ { "answer_id": 210822, "author": "thebigtine", "author_id": 76059, "author_profile": "https://wordpress.stackexchange.com/users/76059", "pm_score": 4, "selected": false, "text": "<p>To display posts in descending alphabetical order add this to your <code>args</code> array (taken from the wp codex)</p>\n\n<pre><code>'orderby' =&gt; 'title',\n'order' =&gt; 'DESC',\n</code></pre>\n\n<p>To display posts in ascending alphabetical order just switch <code>DESC</code> to <code>ASC</code>.</p>\n\n<p>So the whole thing would look like:</p>\n\n<pre><code>$args = array(\n 'orderby' =&gt; 'title',\n 'order' =&gt; 'DESC',\n);\n$query = new WP_Query( $args );\n</code></pre>\n\n<h2><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"noreferrer\">WP_Query Order by Parameters</a></h2>\n\n<p>Or to use if you do not want to alter the main loop use <code>get_posts</code>. WP query alters the main loop by changing the variables of the global variable $wp_query. get_posts, on the other hand, simply references a new WP_Query object, and therefore does not affect or alter the main loop. It would be used in the same way, but changing <code>$query = new WP_Query( $args );</code> to something like <code>$query = get_posts( $args );</code>.</p>\n\n<p>If you would like to alter the main query before it is executed, you can hook into it using the function pre_get_posts. </p>\n" }, { "answer_id": 299608, "author": "Ryan Edmondson", "author_id": 141000, "author_profile": "https://wordpress.stackexchange.com/users/141000", "pm_score": 1, "selected": false, "text": "<p>Not the best code i've ever written here but if you want to create a list like:</p>\n\n<ul>\n<li>A</li>\n<li>America</li>\n<li>B</li>\n<li>Brazil</li>\n<li>Bahamas</li>\n</ul>\n\n<p>You could use..</p>\n\n<pre><code>&lt;ul&gt;\n &lt;?php \n query_posts(array( \n 'post_type' =&gt; 'franchise',\n 'showposts' =&gt; 100,\n 'orderby'=&gt;'title','order'=&gt;'ASC'\n ) ); \n $title_2 = 'A';\n ?&gt;\n &lt;?php while (have_posts()) : the_post(); ?&gt; \n &lt;?php\n $title = get_the_title();\n $title_1 = $title[0];\n if ($title_1 !== $title_2){\n echo '&lt;li&gt;&amp;nbsp;&lt;/li&gt;&lt;li&gt;&lt;h3&gt;' . $title_1 . '&lt;/h3&gt;&lt;/li&gt;&lt;li&gt;&amp;nbsp;&lt;/li&gt;';\n $title_2 = $title_1;\n }\n ?&gt; \n &lt;li&gt;&lt;a href=\"&lt;?php echo get_the_permalink(); ?&gt;\"&gt;&lt;?php echo get_the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt;\n &lt;?php endwhile;?&gt;\n &lt;/ul&gt;\n</code></pre>\n\n<p>Like i said - not the best practice.. but you can tidy up &amp; work from here :)</p>\n" } ]
2015/12/04
[ "https://wordpress.stackexchange.com/questions/210817", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84767/" ]
With this loop I am displaying single posts on an archive page. The posts are being sorted by the category 'Banks'. In addition to that, how can I display them in alphabetical order? I've tried using `WP_Query`, but cannot get it to work; it breaks my loop each time. ``` <h3>Banks & Credit Unions</h3> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); if ( in_category( 'Banks' ) ) { ?> <li> <a href="<?php the_permalink() ?>"> <img src="<?php the_field( 'biller_logo' )?>"> <?php the_field( 'biller_name' ) ?> </a> </li> <?php } endwhile; endif; ?> </ul> ```
To display posts in descending alphabetical order add this to your `args` array (taken from the wp codex) ``` 'orderby' => 'title', 'order' => 'DESC', ``` To display posts in ascending alphabetical order just switch `DESC` to `ASC`. So the whole thing would look like: ``` $args = array( 'orderby' => 'title', 'order' => 'DESC', ); $query = new WP_Query( $args ); ``` [WP\_Query Order by Parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters) ------------------------------------------------------------------------------------------------------------------ Or to use if you do not want to alter the main loop use `get_posts`. WP query alters the main loop by changing the variables of the global variable $wp\_query. get\_posts, on the other hand, simply references a new WP\_Query object, and therefore does not affect or alter the main loop. It would be used in the same way, but changing `$query = new WP_Query( $args );` to something like `$query = get_posts( $args );`. If you would like to alter the main query before it is executed, you can hook into it using the function pre\_get\_posts.
210,821
<p>I figured how to add an input value as a meta key value to a new post from a frontend post form (thanks to <a href="https://wordpress.stackexchange.com/a/210662/25187">@thedeadmedic</a>), but I can't figure <strong>how to add two or more meta keys at once</strong>. Is this possible with the next code? These meta keys are named 'location2' and 'price', and the input fields are respectively 'postLocation2' and 'postPrice' ('$safe_price' after validation).</p> <p>My code:</p> <pre><code>&lt;?php /* * Plugin Name: Submit From Front * Plugin URI: * Description: This creates a form so that posts can be submitted from the front end. * Version: 0.1 * Author: * Author URI: * Text Domain: submit-from-front */ class WPSE_Submit_From_Front { const NONCE_VALUE = 'front_end_new_post'; const NONCE_FIELD = 'fenp_nonce'; protected $pluginPath; protected $pluginUrl; protected $errors = array(); protected $data = array(); function __construct() { $this-&gt;pluginPath = plugin_dir_path( __file__ ); $this-&gt;pluginUrl = plugins_url( '', __file__ ); } /** * Shortcodes should return data, NOT echo it. * * @return string */ function shortcode() { if ( ! current_user_can( 'publish_posts' ) ) return sprintf( '&lt;p&gt;Please &lt;a href="%s"&gt;login&lt;/a&gt; to post adverts.&lt;/p&gt;', esc_url( wp_login_url( get_permalink() ) ) ); elseif ( $this-&gt;handleForm() ) return '&lt;p class="success"&gt;Nice one, post created!&lt;/p&gt;'; else return $this-&gt;getForm(); } /** * Process the form and return true if post successfully created. * * @return bool */ function handleForm() { if ( ! $this-&gt;isFormSubmitted() ) return false; // http://php.net/manual/en/function.filter-input-array.php $data = filter_input_array( INPUT_POST, array( 'postTitle' =&gt; FILTER_DEFAULT, 'postContent' =&gt; FILTER_DEFAULT, 'postCategory' =&gt; FILTER_DEFAULT, 'postLocation' =&gt; FILTER_DEFAULT, 'postLocation2' =&gt; FILTER_DEFAULT, 'postPrice' =&gt; FILTER_DEFAULT, )); $data = wp_unslash( $data ); $data = array_map( 'trim', $data ); // You might also want to more aggressively sanitize these fields // By default WordPress will handle it pretty well, based on the current user's "unfiltered_html" capability $data['postTitle'] = sanitize_text_field( $data['postTitle'] ); $data['postContent'] = wp_check_invalid_utf8( $data['postContent'] ); $data['postCategory'] = sanitize_text_field( $data['postCategory'] ); $data['postLocation'] = sanitize_text_field( $data['postLocation'] ); $data['postLocation2'] = sanitize_text_field( $data['postLocation2'] ); $data['postPrice'] = sanitize_text_field( $data['postPrice'] ); // Validate the Price field input $safe_price = intval( $data['postPrice'] ); if ( ! $safe_price ) { $safe_price = ''; } if ( strlen( $safe_price ) &gt; 10 ) { $safe_price = substr( $safe_price, 0, 10 ); } $this-&gt;data = $data; if ( ! $this-&gt;isNonceValid() ) $this-&gt;errors[] = 'Security check failed, please try again.'; if ( ! $data['postTitle'] ) $this-&gt;errors[] = 'Please enter a title.'; if ( ! $data['postContent'] ) $this-&gt;errors[] = 'Please enter the content.'; if ( ! $data['postCategory'] ) $this-&gt;errors[] = 'Please select a category.'; if ( ! $data['postLocation'] ) $this-&gt;errors[] = 'Please select a location.'; if ( ! $this-&gt;errors ) { $post_id = wp_insert_post( array( 'post_title' =&gt; $data['postTitle'], 'post_content' =&gt; $data['postContent'], 'post_category' =&gt; array( $data['postCategory'] ), 'tax_input' =&gt; array('loc' =&gt; array( $data['postLocation'] )), 'post_status' =&gt; 'publish', )); // This will add a meta key 'location2' to the post // How to add a second (the $safe_price value) meta key named 'price'? $post_id = add_post_meta($post_id, 'location2', $data['postLocation2']); if ( ! $post_id ) $this-&gt;errors[] = 'Whoops, please try again.'; } else { $post_id = 0; } return ( bool ) $post_id; } /** * Use output buffering to *return* the form HTML, not echo it. * * @return string */ function getForm() { ob_start(); ?&gt; &lt;div id ="frontpostform"&gt; &lt;?php foreach ( $this-&gt;errors as $error ) : ?&gt; &lt;p class="error"&gt;&lt;?php echo $error ?&gt;&lt;/p&gt; &lt;?php endforeach ?&gt; &lt;form id="formpost" method="post"&gt; &lt;fieldset&gt; &lt;label for="postTitle"&gt;Post Title&lt;/label&gt; &lt;input type="text" name="postTitle" id="postTitle" value="&lt;?php // "Sticky" field, will keep value from last POST if there were errors if ( isset( $this-&gt;data['postTitle'] ) ) echo esc_attr( $this-&gt;data['postTitle'] ); ?&gt;" /&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;label for="postContent"&gt;Content&lt;/label&gt; &lt;textarea name="postContent" id="postContent" rows="10" cols="35" &gt;&lt;?php if ( isset( $this-&gt;data['postContent'] ) ) echo esc_textarea( $this-&gt;data['postContent'] ); ?&gt;&lt;/textarea&gt; &lt;/fieldset&gt; &lt;!-- Category --&gt; &lt;fieldset&gt; &lt;label for="postCategory"&gt;Category&lt;/label&gt; &lt;select name="postCategory"&gt; &lt;option value=""&gt;&lt;?php echo esc_attr(__('Select Category')); ?&gt;&lt;/option&gt; &lt;?php $categories = get_categories( 'hide_empty=0' ); foreach ($categories as $category) { // keep post category value from last POST if there were errors if ( isset( $this-&gt;data['postCategory'] ) &amp;&amp; $this-&gt;data['postCategory'] == $category-&gt;cat_ID ) { $option = '&lt;option value="' . $category-&gt;cat_ID . '" selected="selected"&gt;'; } else { $option = '&lt;option value="' . $category-&gt;cat_ID . '"&gt;'; } $option .= $category-&gt;cat_name; $option .= ' ('.$category-&gt;category_count.')'; $option .= '&lt;/option&gt;'; echo $option; } ?&gt; &lt;/select&gt; &lt;/fieldset&gt; &lt;!-- Location --&gt; &lt;fieldset&gt; &lt;label for="postLocation"&gt;Location&lt;/label&gt; &lt;select name="postLocation"&gt; &lt;option value=""&gt;&lt;?php echo esc_attr(__('Select Location')); ?&gt;&lt;/option&gt; &lt;?php $categories = get_terms( 'loc', 'hide_empty=0' ); foreach ($categories as $category) { if ( isset( $this-&gt;data['postLocation'] ) &amp;&amp; $this-&gt;data['postLocation'] == $category-&gt;term_id ) { $option = '&lt;option value="' . $category-&gt;term_id . '" selected="selected"&gt;'; } else { $option = '&lt;option value="' . $category-&gt;term_id . '"&gt;'; } $option .= $category-&gt;name; $option .= ' ('.$category-&gt;count.')'; $option .= '&lt;/option&gt;'; echo $option; } ?&gt; &lt;/select&gt; &lt;/fieldset&gt; &lt;!-- Second Location --&gt; &lt;fieldset&gt; &lt;label for="postLocation2"&gt;Location 2&lt;/label&gt; &lt;input type="text" name="postLocation2" id="postLocation2" value="&lt;?php // "Sticky" field, will keep value from last POST if there were errors if ( isset( $this-&gt;data['postLocation2'] ) ) echo esc_attr( $this-&gt;data['postLocation2'] ); ?&gt;" /&gt; &lt;/fieldset&gt; &lt;!-- Price --&gt; &lt;fieldset&gt; &lt;label for="postPrice"&gt;Price&lt;/label&gt; &lt;input type="text" name="postPrice" id="postPrice" maxlength="10" value="&lt;?php // "Sticky" field, will keep value from last POST if there were errors if ( isset( $this-&gt;data['postPrice'] ) ) echo esc_attr( $this-&gt;data['postPrice'] ); ?&gt;" /&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;button type="submit" name="submitForm" &gt;Create Post&lt;/button&gt; &lt;/fieldset&gt; &lt;?php wp_nonce_field( self::NONCE_VALUE , self::NONCE_FIELD ) ?&gt; &lt;/form&gt; &lt;/div&gt; &lt;?php return ob_get_clean(); } /** * Has the form been submitted? * * @return bool */ function isFormSubmitted() { return isset( $_POST['submitForm'] ); } /** * Is the nonce field valid? * * @return bool */ function isNonceValid() { return isset( $_POST[ self::NONCE_FIELD ] ) &amp;&amp; wp_verify_nonce( $_POST[ self::NONCE_FIELD ], self::NONCE_VALUE ); } } new WPSE_Submit_From_Front; </code></pre>
[ { "answer_id": 210833, "author": "mrbobbybryant", "author_id": 64953, "author_profile": "https://wordpress.stackexchange.com/users/64953", "pm_score": 1, "selected": false, "text": "<p>As @milo was saying above each value that you wish to save as post meta will need it's own call to update_post_meta. And each usage of update_post_meta will need you to specific a unique name for that meta value.</p>\n\n<p>Since you have all the data in an array and you have already sanitized it you could do something like this:</p>\n\n<pre><code>foreach( $data as $key =&gt; $value ) {\n update_post_meta( $post_id, $key, $value );\n}\n</code></pre>\n\n<p>that will loop through the array and save each value and set is meta key/name to the array key you set previously in your code.</p>\n\n<p>So this should work for you, but I would say that it might be worth looking at your code more to ensure all data is present before looping through the data array.</p>\n" }, { "answer_id": 210849, "author": "Iurie", "author_id": 25187, "author_profile": "https://wordpress.stackexchange.com/users/25187", "pm_score": 1, "selected": true, "text": "<p>As @milo commented above, each value that I wish to save as post meta will need it's own call to <code>update_post_meta</code>. And because the <strong>$post_id</strong> variable will return the ID of the new post, it was sufficient instead of:</p>\n\n<pre><code>$post_id = add_post_meta($post_id, 'location2', $data['postLocation2']);\n</code></pre>\n\n<p>to insert, for each needed value:</p>\n\n<pre><code>add_post_meta($post_id, 'location2', $data['postLocation2']);\n</code></pre>\n\n<p>and then:</p>\n\n<pre><code>add_post_meta($post_id, 'price', $safe_price);\n</code></pre>\n" } ]
2015/12/04
[ "https://wordpress.stackexchange.com/questions/210821", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25187/" ]
I figured how to add an input value as a meta key value to a new post from a frontend post form (thanks to [@thedeadmedic](https://wordpress.stackexchange.com/a/210662/25187)), but I can't figure **how to add two or more meta keys at once**. Is this possible with the next code? These meta keys are named 'location2' and 'price', and the input fields are respectively 'postLocation2' and 'postPrice' ('$safe\_price' after validation). My code: ``` <?php /* * Plugin Name: Submit From Front * Plugin URI: * Description: This creates a form so that posts can be submitted from the front end. * Version: 0.1 * Author: * Author URI: * Text Domain: submit-from-front */ class WPSE_Submit_From_Front { const NONCE_VALUE = 'front_end_new_post'; const NONCE_FIELD = 'fenp_nonce'; protected $pluginPath; protected $pluginUrl; protected $errors = array(); protected $data = array(); function __construct() { $this->pluginPath = plugin_dir_path( __file__ ); $this->pluginUrl = plugins_url( '', __file__ ); } /** * Shortcodes should return data, NOT echo it. * * @return string */ function shortcode() { if ( ! current_user_can( 'publish_posts' ) ) return sprintf( '<p>Please <a href="%s">login</a> to post adverts.</p>', esc_url( wp_login_url( get_permalink() ) ) ); elseif ( $this->handleForm() ) return '<p class="success">Nice one, post created!</p>'; else return $this->getForm(); } /** * Process the form and return true if post successfully created. * * @return bool */ function handleForm() { if ( ! $this->isFormSubmitted() ) return false; // http://php.net/manual/en/function.filter-input-array.php $data = filter_input_array( INPUT_POST, array( 'postTitle' => FILTER_DEFAULT, 'postContent' => FILTER_DEFAULT, 'postCategory' => FILTER_DEFAULT, 'postLocation' => FILTER_DEFAULT, 'postLocation2' => FILTER_DEFAULT, 'postPrice' => FILTER_DEFAULT, )); $data = wp_unslash( $data ); $data = array_map( 'trim', $data ); // You might also want to more aggressively sanitize these fields // By default WordPress will handle it pretty well, based on the current user's "unfiltered_html" capability $data['postTitle'] = sanitize_text_field( $data['postTitle'] ); $data['postContent'] = wp_check_invalid_utf8( $data['postContent'] ); $data['postCategory'] = sanitize_text_field( $data['postCategory'] ); $data['postLocation'] = sanitize_text_field( $data['postLocation'] ); $data['postLocation2'] = sanitize_text_field( $data['postLocation2'] ); $data['postPrice'] = sanitize_text_field( $data['postPrice'] ); // Validate the Price field input $safe_price = intval( $data['postPrice'] ); if ( ! $safe_price ) { $safe_price = ''; } if ( strlen( $safe_price ) > 10 ) { $safe_price = substr( $safe_price, 0, 10 ); } $this->data = $data; if ( ! $this->isNonceValid() ) $this->errors[] = 'Security check failed, please try again.'; if ( ! $data['postTitle'] ) $this->errors[] = 'Please enter a title.'; if ( ! $data['postContent'] ) $this->errors[] = 'Please enter the content.'; if ( ! $data['postCategory'] ) $this->errors[] = 'Please select a category.'; if ( ! $data['postLocation'] ) $this->errors[] = 'Please select a location.'; if ( ! $this->errors ) { $post_id = wp_insert_post( array( 'post_title' => $data['postTitle'], 'post_content' => $data['postContent'], 'post_category' => array( $data['postCategory'] ), 'tax_input' => array('loc' => array( $data['postLocation'] )), 'post_status' => 'publish', )); // This will add a meta key 'location2' to the post // How to add a second (the $safe_price value) meta key named 'price'? $post_id = add_post_meta($post_id, 'location2', $data['postLocation2']); if ( ! $post_id ) $this->errors[] = 'Whoops, please try again.'; } else { $post_id = 0; } return ( bool ) $post_id; } /** * Use output buffering to *return* the form HTML, not echo it. * * @return string */ function getForm() { ob_start(); ?> <div id ="frontpostform"> <?php foreach ( $this->errors as $error ) : ?> <p class="error"><?php echo $error ?></p> <?php endforeach ?> <form id="formpost" method="post"> <fieldset> <label for="postTitle">Post Title</label> <input type="text" name="postTitle" id="postTitle" value="<?php // "Sticky" field, will keep value from last POST if there were errors if ( isset( $this->data['postTitle'] ) ) echo esc_attr( $this->data['postTitle'] ); ?>" /> </fieldset> <fieldset> <label for="postContent">Content</label> <textarea name="postContent" id="postContent" rows="10" cols="35" ><?php if ( isset( $this->data['postContent'] ) ) echo esc_textarea( $this->data['postContent'] ); ?></textarea> </fieldset> <!-- Category --> <fieldset> <label for="postCategory">Category</label> <select name="postCategory"> <option value=""><?php echo esc_attr(__('Select Category')); ?></option> <?php $categories = get_categories( 'hide_empty=0' ); foreach ($categories as $category) { // keep post category value from last POST if there were errors if ( isset( $this->data['postCategory'] ) && $this->data['postCategory'] == $category->cat_ID ) { $option = '<option value="' . $category->cat_ID . '" selected="selected">'; } else { $option = '<option value="' . $category->cat_ID . '">'; } $option .= $category->cat_name; $option .= ' ('.$category->category_count.')'; $option .= '</option>'; echo $option; } ?> </select> </fieldset> <!-- Location --> <fieldset> <label for="postLocation">Location</label> <select name="postLocation"> <option value=""><?php echo esc_attr(__('Select Location')); ?></option> <?php $categories = get_terms( 'loc', 'hide_empty=0' ); foreach ($categories as $category) { if ( isset( $this->data['postLocation'] ) && $this->data['postLocation'] == $category->term_id ) { $option = '<option value="' . $category->term_id . '" selected="selected">'; } else { $option = '<option value="' . $category->term_id . '">'; } $option .= $category->name; $option .= ' ('.$category->count.')'; $option .= '</option>'; echo $option; } ?> </select> </fieldset> <!-- Second Location --> <fieldset> <label for="postLocation2">Location 2</label> <input type="text" name="postLocation2" id="postLocation2" value="<?php // "Sticky" field, will keep value from last POST if there were errors if ( isset( $this->data['postLocation2'] ) ) echo esc_attr( $this->data['postLocation2'] ); ?>" /> </fieldset> <!-- Price --> <fieldset> <label for="postPrice">Price</label> <input type="text" name="postPrice" id="postPrice" maxlength="10" value="<?php // "Sticky" field, will keep value from last POST if there were errors if ( isset( $this->data['postPrice'] ) ) echo esc_attr( $this->data['postPrice'] ); ?>" /> </fieldset> <fieldset> <button type="submit" name="submitForm" >Create Post</button> </fieldset> <?php wp_nonce_field( self::NONCE_VALUE , self::NONCE_FIELD ) ?> </form> </div> <?php return ob_get_clean(); } /** * Has the form been submitted? * * @return bool */ function isFormSubmitted() { return isset( $_POST['submitForm'] ); } /** * Is the nonce field valid? * * @return bool */ function isNonceValid() { return isset( $_POST[ self::NONCE_FIELD ] ) && wp_verify_nonce( $_POST[ self::NONCE_FIELD ], self::NONCE_VALUE ); } } new WPSE_Submit_From_Front; ```
As @milo commented above, each value that I wish to save as post meta will need it's own call to `update_post_meta`. And because the **$post\_id** variable will return the ID of the new post, it was sufficient instead of: ``` $post_id = add_post_meta($post_id, 'location2', $data['postLocation2']); ``` to insert, for each needed value: ``` add_post_meta($post_id, 'location2', $data['postLocation2']); ``` and then: ``` add_post_meta($post_id, 'price', $safe_price); ```
210,829
<p>I'm trying to redirect my attachment-id pages to the correct post-id page (woocommerce single page). </p> <p>I got this URL with the attachment_id = 17381. How do I retrieve the products/post ID, which uses this attachment_id? I've searched for hours, and tried different approaches, but I can't find a solution.</p> <p><a href="https://www.ejstruplys.dk/no/?attachment_id=17381" rel="nofollow noreferrer">https://www.ejstruplys.dk/no/?attachment_id=17381</a></p> <p>I want it to be redirected to this page: <a href="https://www.ejstruplys.dk/no/produkt/block-candles-rustic-surface-3/" rel="nofollow noreferrer">https://www.ejstruplys.dk/no/produkt/block-candles-rustic-surface-3/</a></p> <p>Doing an <code>var_dump($post)</code> gives me this, but I can't figure out, where this attachment_id -> product ID is located: </p> <pre><code>OBJECT = WP_Post::__set_state(array( 'ID' =&gt; 17381, 'post_author' =&gt; '1', 'post_date' =&gt; '2015-08-24 19:32:00', 'post_date_gmt' =&gt; '2015-08-24 19:32:00', 'post_content' =&gt; '', 'post_title' =&gt; 'Orange. Bloklys. Rustikk overflate', 'post_excerpt' =&gt; '', 'post_status' =&gt; 'inherit', 'comment_status' =&gt; 'open', 'ping_status' =&gt; 'closed', 'post_password' =&gt; '', 'post_name' =&gt; 'bloklys_rustik_overflade_55_dia_orange-jpg-2', 'to_ping' =&gt; '', 'pinged' =&gt; '', 'post_modified' =&gt; '2015-08-24 19:32:00', 'post_modified_gmt' =&gt; '2015-08-24 19:32:00', 'post_content_filtered' =&gt; '', 'post_parent' =&gt; 0, 'guid' =&gt; 'https://www.ejstruplys.dk/wp-content/uploads/2015/08/bloklys_rustik_overflade_55_dia_orange.jpg', 'menu_order' =&gt; 0, 'post_type' =&gt; 'attachment', 'post_mime_type' =&gt; 'image/jpeg', 'comment_count' =&gt; '0', 'filter' =&gt; 'raw', 'post_title_ml' =&gt; '[:en]Orange. Block candles. Rustic surface[:no]Orange. Bloklys. Rustikk overflate[:sv]Orange. Blokljus. Rustik yta[:de]Orange. Stumpenkerzen. Rustikale Oberfläche[:da]Orange. Bloklys. Rustik overflade[:]', )); </code></pre> <p>How do I retrieve the post ID from the attachment ID?</p> <p><strong>Edit:</strong> I've tried this one: <a href="https://wordpress.stackexchange.com/questions/144614/get-post-id-by-attachment-id">Get post id by attachment id?</a></p> <p>But it just returns <code>null</code>.</p>
[ { "answer_id": 210832, "author": "mrbobbybryant", "author_id": 64953, "author_profile": "https://wordpress.stackexchange.com/users/64953", "pm_score": 0, "selected": false, "text": "<p>WordPress uses the post_parent column in the database to track which posts an attachment is linked to. You can use <code>wp_get_post_parent_id</code> to find an attachment's parent post. Simply pass it the attachment ID.</p>\n" }, { "answer_id": 210834, "author": "Mateusz Hajdziony", "author_id": 15865, "author_profile": "https://wordpress.stackexchange.com/users/15865", "pm_score": 1, "selected": false, "text": "<p>It looks like the image (for which you've done a var_dump) is not attached to any post. If an image is attached to a post - the post's ID would appear as <code>'post_parent'</code>, which in this case equals <code>0</code>. This is often the case if you upload the image directly from withing media library ('Media Library' page in your WP admin) - you can still place such image into post content, use it as post thumbnails, in galleries etc., but this doesn't mean that the image is attached to any post.</p>\n\n<p>To properly attach an image to a post you have to <strong>upload</strong> it by clicking the 'Add Media' button when creating/editing the post. This is the only way that you can be certain that the image will be labelled as post's attachment.</p>\n" }, { "answer_id": 210858, "author": "Unicco", "author_id": 52622, "author_profile": "https://wordpress.stackexchange.com/users/52622", "pm_score": 0, "selected": false, "text": "<p>Based on the previously answers, I managed to pull this off. Thanks for the replies stating the issue was based on wrong attachments (non-existing post_parent ID's).</p>\n\n<p>In case someone is struggling with the same issue, here is the solution I ended up with:</p>\n\n<p>The method hooks on Wordpress' <code>template_redirect</code>, check if the specific page has an parent_post, and uses two different approaches towards retriving the correct Product Post ID. It works on all \"~/?attachment_id\" and \"~/variation_product\"**.</p>\n\n<pre><code>/*\n* Redirect Attachment Pages\n*/\nadd_action( 'template_redirect', 'wpse27119_template_redirect' );\nfunction wpse27119_template_redirect() {\n global $post;\n\n /* Assign the specific post ID to local variable */\n $post_id = get_the_ID();\n\n /* If page has no attachment - no need to continue */\n if (!is_attachment() ) return false;\n\n if (empty($post)) $post = get_queried_object();\n\n /* Instantiating the product object based on currenct post ID */\n $_product = new WC_Product_Variation($post_id);\n\n /* Check if specific post got an post_parent ~ proper image-attachments and product_variation */\n if ($post-&gt;post_parent) {\n\n /* Retrieve the permalink ~ from the current product-object */\n $link = get_permalink($_product-&gt;post-&gt;ID);\n\n /* Redirect the user */\n wp_redirect( $link, '301' );\n\n exit();\n\n } else {\n\n /* Retrieve all product-pages */\n $args = array(\n 'post_type' =&gt; 'product',\n 'posts_per_page' =&gt; -1\n );\n\n /* Initialize WP_Query, and retrieve all product-pages */\n $loop = new WP_Query($args);\n\n /* Check if array contains any posts */\n if ($loop-&gt;have_posts()): while ($loop-&gt;have_posts()): $loop-&gt;the_post();\n global $product;\n\n /* Iterate through all children in product */\n foreach ($product-&gt;get_children() as $child_id) {\n\n /* Retrieve all children of the specific product */\n $variation = $product-&gt;get_child($child_id);\n\n /* Check if variation is an instance of product */\n if ($variation instanceof WC_Product_Variation) {\n\n /* Retrieve all image_ids from variation */\n $variation_image_id = $variation-&gt;get_image_id();\n\n /* Compare variation image id with the current post id ~ attachment id */\n if ($variation_image_id == $post_id) {\n\n /* Retrieve the correct product - using the post id */\n $_product = new WC_Product_Variation($post_id);\n\n /* Retrieve the permalink ~ from the current product-object */\n $link = get_permalink($_product-&gt;post-&gt;ID);\n\n /* Redirect the user */\n wp_redirect($link, '301');\n\n exit();\n\n }\n\n\n }\n\n\n }\n\n endwhile; endif; wp_reset_postdata();\n\n }\n\n}\n</code></pre>\n\n<p>I'm trying to parse the variations arguments to the redirect method. I'll update this post, if I find a solution.</p>\n" } ]
2015/12/04
[ "https://wordpress.stackexchange.com/questions/210829", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52622/" ]
I'm trying to redirect my attachment-id pages to the correct post-id page (woocommerce single page). I got this URL with the attachment\_id = 17381. How do I retrieve the products/post ID, which uses this attachment\_id? I've searched for hours, and tried different approaches, but I can't find a solution. <https://www.ejstruplys.dk/no/?attachment_id=17381> I want it to be redirected to this page: <https://www.ejstruplys.dk/no/produkt/block-candles-rustic-surface-3/> Doing an `var_dump($post)` gives me this, but I can't figure out, where this attachment\_id -> product ID is located: ``` OBJECT = WP_Post::__set_state(array( 'ID' => 17381, 'post_author' => '1', 'post_date' => '2015-08-24 19:32:00', 'post_date_gmt' => '2015-08-24 19:32:00', 'post_content' => '', 'post_title' => 'Orange. Bloklys. Rustikk overflate', 'post_excerpt' => '', 'post_status' => 'inherit', 'comment_status' => 'open', 'ping_status' => 'closed', 'post_password' => '', 'post_name' => 'bloklys_rustik_overflade_55_dia_orange-jpg-2', 'to_ping' => '', 'pinged' => '', 'post_modified' => '2015-08-24 19:32:00', 'post_modified_gmt' => '2015-08-24 19:32:00', 'post_content_filtered' => '', 'post_parent' => 0, 'guid' => 'https://www.ejstruplys.dk/wp-content/uploads/2015/08/bloklys_rustik_overflade_55_dia_orange.jpg', 'menu_order' => 0, 'post_type' => 'attachment', 'post_mime_type' => 'image/jpeg', 'comment_count' => '0', 'filter' => 'raw', 'post_title_ml' => '[:en]Orange. Block candles. Rustic surface[:no]Orange. Bloklys. Rustikk overflate[:sv]Orange. Blokljus. Rustik yta[:de]Orange. Stumpenkerzen. Rustikale Oberfläche[:da]Orange. Bloklys. Rustik overflade[:]', )); ``` How do I retrieve the post ID from the attachment ID? **Edit:** I've tried this one: [Get post id by attachment id?](https://wordpress.stackexchange.com/questions/144614/get-post-id-by-attachment-id) But it just returns `null`.
It looks like the image (for which you've done a var\_dump) is not attached to any post. If an image is attached to a post - the post's ID would appear as `'post_parent'`, which in this case equals `0`. This is often the case if you upload the image directly from withing media library ('Media Library' page in your WP admin) - you can still place such image into post content, use it as post thumbnails, in galleries etc., but this doesn't mean that the image is attached to any post. To properly attach an image to a post you have to **upload** it by clicking the 'Add Media' button when creating/editing the post. This is the only way that you can be certain that the image will be labelled as post's attachment.